Index: src/Actions/Action.cpp
===================================================================
--- src/Actions/Action.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/Action.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,6 +10,12 @@
 #include "Actions/Action.hpp"
 #include "Actions/ActionRegistry.hpp"
+#include "Actions/ActionHistory.hpp"
+#include "Helpers/MemDebug.hpp"
 
 using namespace std;
+
+// An empty state to indicate success
+Action::state_ptr Action::success = Action::state_ptr(Memory::ignore(new ActionState()));
+Action::state_ptr Action::failure = Action::state_ptr(Memory::ignore(new ActionState()));
 
 Action::Action(std::string _name,bool _doRegister) :
@@ -17,5 +23,5 @@
 {
   if(_doRegister){
-    ActionRegistry::getRegistry()->registerAction(this);
+    ActionRegistry::getInstance().registerAction(this);
   }
 }
@@ -27,2 +33,31 @@
   return name;
 }
+
+void Action::call(){
+  if(!isActive()){
+    return;
+  }
+  // forward to private virtual
+  state_ptr state = performCall();
+  if(shouldUndo() && state != failure){
+    if(canUndo()){
+      ActionHistory::getInstance().addElement(this,state);
+    }
+    else{
+      ActionHistory::getInstance().clear();
+    }
+  }
+}
+Action::state_ptr Action::undo(state_ptr _state) {
+  // forward to private virtual
+  return performUndo(_state);
+}
+Action::state_ptr Action::redo(state_ptr _state) {
+  // forward to private virtual
+  return performRedo(_state);
+}
+
+
+bool Action::isActive(){
+  return true;
+}
Index: src/Actions/Action.hpp
===================================================================
--- src/Actions/Action.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/Action.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,4 +10,237 @@
 
 #include <string>
+#include <boost/shared_ptr.hpp>
+
+// forward declaration
+
+class ActionState;
+class ActionSequence;
+
+/**
+ * @file
+ * <H1> Action Howto </H1>
+ *
+ * <H2> Introduction </H2>
+ *
+ * Actions are used in object oriented design as a replacement for callback functions.
+ * In most ways Actions can be used in the same way that callbacks were used in non
+ * OO-Systems, but can contain support for several extra mechanism such as undo/redo
+ * or progress indicators.
+ *
+ * The main purpose of an action class is to contain small procedures, that can be repeatedly
+ * called. These procedures can also be stored, passed around, so that the execution of an
+ * action can happen quite far away from the place of creation. For a detailed description of
+ * the Action pattern see GOF:1996.
+ *
+ * <H3> How to use an action </H3>
+ *
+ * The process of using an action is as easy as calling the call() method of the action. The
+ * action will then do whatever it is supposed to do. If it is an action that can be undone, it
+ * will also register itself in the history to make itself available for undo. To undo the last
+ * action, you can either use the undoLast() method inside the ActionHistory class or call the
+ * UndoAction also provided by the ActionHistory. If an action was undone it will be available for
+ * redo, using the redoLast() method of the ActionHistory or the RedoAction also provided by this
+ * class. To check whether undo/redo is available at any moment you can use the hasUndo() or
+ * hasRedo() method respectively.
+ *
+ * Actions can be set to be active or inactive. If an action is set to inactive it is signaling, that
+ * some condition necessary for this action to be executed is not currently met. For example the
+ * UndoAction will set itself to inactive, when there is no action at that time that can be undone.
+ * Using call() on an inactive Action results in a no-op. You can query the state of an action using
+ * the isActive() method.
+ *
+ * The undo capabilities of actions come in three types as signaled by two boolean flags (one
+ * combination of these flags is left empty as can be seen later).
+ * <ul>
+ * <li/> The first flag indicates if the undo mechanism for this action should be considered at all, i.e.
+ *   if the state of the application changes in a way that needs to be reverted. Actions that should
+ *   consider the undo mechanism are for example adding a molecule, moving atoms, changing
+ *   the name of a molecule etc. Changing the View-Area on the other hand should be an action that
+ *   does not consider the undo mechanism. This flag can be queried using the shouldUndo() method.
+ *
+ * <li/> The second flag indicates whether the changes can be undo for this action. If this flag is true
+ *   the action will be made available for undo using the ActionHistory class and the actions of this
+ *   class. If this flag is false while the shoudlUndo() flag is true this means that this action
+ *   changes the state of the application changes in a way that cannot be undone, but might cause
+ *   the undo of previous actions to fail. In this case the whole History is cleared, as to keep
+ *   the state of the application intact by avoiding dangerous undos. This flag can be queried
+ *   using the canUndo() method.
+ *</ul>
+ *
+ * Each action has a name, that can be used to identify it throughout the run of the application.
+ * This name can be retrieved using the getName() method. Most actions also register themselves with
+ * a global structure, called the ActionRegistry. Actions that register themselves need to have a
+ * unique name for the whole application. If the name is known these actions can be retrieved from
+ * the registry by their name and then be used as normal.
+ *
+ * <H2> Building your own actions </H2>
+ *
+ * Building actions is fairly easy. Simply derive from the abstract Action base class and implement
+ * the virtual methods. The main code that needs to be executed upon call() should be implemented in
+ * the performCall() method. You should also indicate whether the action supports undo by implementing
+ * the shouldUndo() and canUndo() methods to return the appropriate flags.
+ *
+ * The constructor of your derived class also needs to call the Base constructor, passing it the
+ * name of the Action and a flag indicating whether this action should be made available in the
+ * registry. WARNING: Do not use the virtual getName() method of the derived action to provide the
+ * constructor with the name, even if you overloaded this method to return a constant. Doing this
+ * will most likely not do what you think it does (see: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.5
+ * if you want to know why this wont work)
+ *
+ * <H3> Interfacing your Action with the Undo mechanism </H3>
+ *
+ * The performX() methods need to comply to a simple standard to allow for undo and redo. The first
+ * convention in this standard concerns the return type. All methods that handle calling, undoing
+ * or redoing return an object of Action::state_ptr. This is a smart pointer to a State object, that
+ * can be used to store state information that is needed by your action for later redo. A rename
+ * Action for example would need to store which object has been renamed and what the old name was.
+ * A move Action on the other hand would need to store the object that has been moved as well as the
+ * old position. If your Action does not need to store any kind of information for redo you can
+ * simply return Action::success and skip the rest of this paragraph. If your action has been
+ * abborted you can return Action::failure, which indicates to the history mechanism that this
+ * action should not be stored.
+ *
+ * If your Action needs any kind of information to undo its execution, you need to store this
+ * information in the state that is returned by the performCall() method. Since no assumptions
+ * can be made on the type or amount of information the ActionState base class is left empty.
+ * To use this class you need to derive a YourActionState class from the ActionState base class
+ * adding your data fields and accessor functions. Upon undo the ActionState object produced
+ * by the corresponding performCall() is then passed to the performUndo() method which should
+ * typecast the ActionState to the appropriate sub class, undo all the changes and produce
+ * a State object that can be used to redo the action if neccessary. This new state object is
+ * then used if the redo mechanism is invoked and passed to the performRedo() function, which
+ * again produces a State that can be used for performUndo().
+ *
+ * <H3> Outline of the implementation of Actions </H3>
+ *
+ * To sum up the actions necessary to build actions here is a brief outline of things methioned
+ * in the last paragraphs:
+ *
+ * <H4> Basics </H4>
+ *
+ * <ul>
+ *  <li/> derive YourAction from Action
+ *  <li/> pass name and flag for registry to the base constructor
+ *  <li/> implement performCall(), performUndo(), performRedo()
+ *  <li/> implement the functions that return the flags for the undo mechanism
+ *  <li/> Derive YourActionState from ActionState as necessary
+ * </ul>
+ *
+ * <H4> Implementing performX() methods </H4>
+ *
+ * <ul>
+ *  <li/> performCall():
+ *  <ul>
+ *   <li/> do whatever is needed to make the action work
+ *   <li/> if the action was abborted return Action::failure
+ *   <li/> if the action needs to save a state return a custom state object
+ *   <li/> otherwise return Action::success
+ *  </ul>
+ *  <li/> performUndo():
+ *  <ul>
+ *   <li/> typecast the ActionState pointer to a Pointer to YourActionState if necessary
+ *   <li/> undo the action using the information from the state
+ *   <li/> produce a new state that can be used for redoing and return it
+ *  </ul>
+ *  <li/> performRedo():
+ *  <ul>
+ *   <li/> take the ActionState produced by performUndo and typecast it to a pointer to YourActionState if necessary
+ *   <li/> redo the undone action using the information from the state
+ *   <li/> produce a new state that can be used by performUndo() and return it
+ *  </ul>
+ * </ul>
+ *
+ * <H2> Advanced techniques </H2>
+ *
+ * <H3> Predefined Actions </H3>
+ *
+ * To make construction of actions easy there are some predefined actions. Namely these are
+ * the MethodAction and the ErrorAction.
+ *
+ * The method action can be used to turn any function with empty arguments and return type void
+ * into an action (also works for functors with those types). Simply pass the constructor for the
+ * MethodAction a name to use for this action, the function to call inside the performCall()
+ * method and a flag indicating if this action should be made retrievable inside the registry
+ * (default is true). MethodActions always report themselves as changing the state of the
+ * application but cannot be undone. i.e. calling MethodActions will always cause the ActionHistory
+ * to be cleared.
+ *
+ * ErrorActions can be used to produce a short message using the Log() << Verbose() mechanism of
+ * the molecuilder. Simply pass the constructor a name for the action, the message to show upon
+ * calling this action and the flag for the registry (default is again true). Error action
+ * report that they do not change the state of the application and are therefore not considered
+ * for undo.
+ *
+ * <H3> Sequences of Actions and MakroActions </H3>
+ *
+ * <H4> Building sequences of Actions </H4>
+ *
+ * Actions can be chained to sequences using the ActionSequence class. Once an ActionSequence is
+ * constructed it will be initially empty. Any Actions can then be added to the sequence using the
+ * addAction() method of the ActionSequence class. The last added action can be removed using the
+ * removeLastAction() method. If the construction of the sequence is done, you can use the
+ * callAll() method. Each action called this way will register itself with the History to allow
+ * separate undo of all actions in the sequence.
+ *
+ * <H4> Building larger Actions from simple ones </H4>
+ *
+ * Using the pre-defined class MakroAction it is possible to construct bigger actions from a sequence
+ * of smaller ones. For this you first have to build a sequence of the actions using the ActionSequence
+ * as described above. Then you can construct a MakroAction passing it a name, the sequence to use
+ * and as usual a flag for the registry. You can then simply call the complete action-sequence through
+ * this makro action using the normal interface. Other than with the direct use of the action sequence
+ * only the complete MakroAction is registered inside the history, i.e. the complete sequence can be
+ * undone at once. Also there are a few caveats you have to take care of when using the MakroAction:
+ * <ul>
+ *  <li/> All Actions as well as the sequence should exclusively belong to the MakroAction. This
+ *        especially means, that the destruction of these objects should be handled by the MakroAction.
+ *  <li/> none of the Actions inside the MakroAction should be registered with the registry, since the
+ *        registry also assumes sole ownership of the actions.
+ *  <li/> Do not remove or add actions from the sequence once the MakroAction has been constructed, since this
+ *        might brake important assumptions for the undo/redo mechanism
+ * </ul>
+ *
+ * <H3> Special kinds of Actions </H3>
+ *
+ * To make the usage of Actions more versatile there are two special kinds of actions defined,
+ * that contain special mechanisms. These are defined inside the class Process, for actions that
+ * take some time and indicate their own progress, and in the class Calculations for actions that
+ * have a retrievable result.
+ *
+ * <H4> Processes </H4>
+ *
+ * Processes are Actions that might take some time and therefore contain special mechanisms
+ * to indicate their progress to the user. If you want to implement a process you can follow the
+ * guidelines for implementing actions. In addition to the normal Action constructor parameters,
+ * you also need to define the number of steps the process takes to finish (use 0 if that number is
+ * not known upon construction). At the beginning of your process you then simply call start() to
+ * indicate that the process is taking up its work. You might also want to set the number of steps it
+ * needs to finish, if it has changed since the last invocation/construction. You can use the
+ * setMaxSteps() method for this. Then after each finished step of calulation simply call step(),
+ * to let the indicators know that it should update itself. If the number of steps is not known
+ * at the time of calculation, you should make sure the maxSteps field is set to 0, either through
+ * the constructor or by using setMaxSteps(0). Indicators are required to handle both processes that
+ * know the number of steps needed as well as processes that cannot predict when they will be finished.
+ * Once your calculation is done call stop() to let every indicator know that the process is done with
+ * the work and to let the user know.
+ *
+ * Indicators that want to know about processes need to implement the Observer class with all the
+ * methods defined there. They can then globally sign on to all processes using the static
+ * Process::AddObserver() method and remove themselves using the Process::RemoveObserver()
+ * methods. When a process starts it will take care that the notification for this process
+ * is invoked at the right time. Indicators should not try to observe a single process, but rather
+ * be ready to observe the status of any kind of process using the methods described here.
+ *
+ * <H4> Calculations </H4>
+ *
+ * Calculations are special Actions that also return a result when called. Calculations are
+ * always derived from Process, so that the progress of a calculation can be shown. Also
+ * Calculations should not contain side-effects and not consider the undo mechanism.
+ * When a Calculation is called using the Action mechanism this will cause it to calculate
+ * the result and make it available using the getResult() method. Another way to have a Calculation
+ * produce a result is by using the function-call operator. When this operator is used, the Calculation
+ * will try to return a previously calculated and cached result and only do any actuall calculations
+ * when no such result is available. You can delete the cached result using the reset() method.
+ */
 
 /**
@@ -16,24 +249,133 @@
  * Actions describe something that has to be done.
  * Actions can be passed around, stored, performed and undone (Command-Pattern).
- *
- * TODO: Add queues of actions that have been performed to allow easy implementation of multiple-step undo
  */
 class Action
 {
-protected:
+friend class ActionSequence;
+friend class ActionHistory;
 public:
+
+  /**
+   * This type is used to store pointers to ActionStates while allowing multiple ownership
+   */
+  typedef boost::shared_ptr<ActionState> state_ptr;
+
+  /**
+   * Standard constructor of Action Base class
+   *
+   * All Actions need to have a name. The second flag indicates, whether the action should
+   * be registered with the ActionRegistry. If the Action is registered the name of the
+   * Action needs to be unique for all Actions that are registered.
+   */
   Action(std::string _name,bool _doRegister=true);
   virtual ~Action();
 
-  virtual void call()=0;
-  virtual void undo()=0;
+  /**
+   * This method is used to call an action. The basic operations for the Action
+   * are carried out and if necessary/possible the Action is added to the History
+   * to allow for undo of this action.
+   *
+   * If the call needs to undone you have to use the History, to avoid destroying
+   * invariants used by the History.
+   */
+  void call();
+
+  /**
+   * This method provides a flag that indicates if an undo mechanism is implemented
+   * for this Action. If this is true, and this action was called last, you can
+   * use the History to undo this action.
+   */
   virtual bool canUndo()=0;
-  //virtual bool shouldUndo()=0;
-
+
+  /**
+   * This method provides a flag, that indicates if the Action changes the state of
+   * the application in a way that needs to be undone for the History to work.
+   *
+   * If this is false the Action will not be added to the History upon calling. However
+   * Actions called before this one will still be available for undo.
+   */
+  virtual bool shouldUndo()=0;
+
+  /**
+   * Indicates whether the Action can do it's work at the moment. If this
+   * is false calling the action will result in a no-op.
+   */
+  virtual bool isActive();
+
+  /**
+   * Returns the name of the Action.
+   */
   virtual const std::string getName();
 
+protected:
+  /**
+   * This method is called by the History, when an undo is performed. It is
+   * provided with the corresponding state produced by the performCall or
+   * performRedo method and needs to provide a state that can be used for redo.
+   */
+  state_ptr undo(state_ptr);
+
+  /**
+   * This method is called by the Histor, when a redo is performed. It is
+   * provided with the corresponding state produced by the undo method and
+   * needs to produce a State that can then be used for another undo.
+   */
+  state_ptr redo(state_ptr);
+
+  /**
+   * This special state can be used to indicate that the Action was successfull
+   * without providing a special state. Use this if your Action does not need
+   * a speciallized state.
+   */
+  static state_ptr success;
+
+  /**
+   * This special state can be returned, to indicate that the action could not do it's
+   * work, was abborted by the user etc. If you return this state make sure to transactionize
+   * your Actions and unroll the complete transaction before this is returned.
+   */
+  static state_ptr failure;
+
 private:
+  /**
+   * This is called internally when the call is being done. Implement this method to do the actuall
+   * work of the Action. Implement this in your Derived classes. Needs to return a state that can be
+   * used to undo the action.
+   */
+  virtual state_ptr performCall()=0;
+
+  /**
+   * This is called internally when the undo process is chosen. This Method should use the state
+   * produced by the performCall method to return the state of the application to the state
+   * it had before the Action.
+   */
+  virtual state_ptr performUndo(state_ptr)=0;
+
+  /**
+   * This is called internally when the redo process is chosen. This method shoudl use the state
+   * produced by the performUndo method to return the application to the state it should have after
+   * the action.
+   *
+   * Often this method can be implement to re-use the performCall method. However if user interaction
+   * or further parameters are needed, those should be taken from the state and not query the user
+   * again.
+   */
+  virtual state_ptr performRedo(state_ptr)=0;
+
   std::string name;
 };
 
+/**
+ * This class can be used by actions to save the state.
+ *
+ * It is implementing a memento pattern. The base class is completely empty,
+ * since no general state internals can be given. The Action performing
+ * the Undo should downcast to the apropriate type.
+ */
+class ActionState{
+public:
+  ActionState(){}
+  virtual ~ActionState(){}
+};
+
 #endif /* ACTION_H_ */
Index: src/Actions/ActionHistory.cpp
===================================================================
--- src/Actions/ActionHistory.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/ActionHistory.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,133 @@
+/*
+ * ActionHistory.cpp
+ *
+ *  Created on: Mar 25, 2010
+ *      Author: crueger
+ */
+
+#include "ActionHistory.hpp"
+
+#include <iostream>
+
+#include "Patterns/Singleton_impl.hpp"
+#include "Helpers/Assert.hpp"
+#include "Helpers/MemDebug.hpp"
+
+using namespace std;
+
+ActionHistory::ActionHistory()
+{}
+
+ActionHistory::~ActionHistory()
+{}
+
+void ActionHistory::undoLast(){
+  ASSERT(history.size(),"Undo performed when the undo-queue was empty");
+  HistoryElement elem = history.back();
+  history.pop_back();
+  Action::state_ptr newState = elem.action->undo(elem.state);
+  yrotsih.push_back(HistoryElement(elem.action,newState));
+}
+void ActionHistory::redoLast(){
+  ASSERT(yrotsih.size(),"Redo performed when the redo-queue was empty");
+  HistoryElement elem = yrotsih.back();
+  yrotsih.pop_back();
+  Action::state_ptr oldState = elem.action->redo(elem.state);
+  history.push_back(HistoryElement(elem.action,oldState));
+}
+
+bool ActionHistory::hasUndo(){
+  return history.size()>0;
+}
+
+bool ActionHistory::hasRedo(){
+  return yrotsih.size()>0;
+}
+
+void ActionHistory::addElement(Action* action,Action::state_ptr state){
+  yrotsih.clear();
+  history.push_back(HistoryElement(action,state));
+}
+
+void ActionHistory::clear(){
+  history.clear();
+  yrotsih.clear();
+}
+
+void ActionHistory::init(){
+  ActionHistory *hist = new ActionHistory();
+  setInstance(hist);
+  new UndoAction(hist);
+  new RedoAction(hist);
+}
+
+CONSTRUCT_SINGLETON(ActionHistory)
+
+/****************** Contained actions *******************/
+ActionHistory::UndoAction::UndoAction(ActionHistory *_hist) :
+  Action("Undo"),
+  hist(_hist)
+{}
+
+ActionHistory::UndoAction::~UndoAction(){}
+
+bool ActionHistory::UndoAction::canUndo(){
+  return false;
+}
+
+bool ActionHistory::UndoAction::shouldUndo(){
+  return false;
+}
+
+bool ActionHistory::UndoAction::isActive(){
+  return hist->hasUndo();
+}
+
+Action::state_ptr ActionHistory::UndoAction::performCall(){
+  hist->undoLast();
+  return Action::success;
+}
+
+Action::state_ptr ActionHistory::UndoAction::performUndo(Action::state_ptr){
+  ASSERT(0,"Cannot undo an undo (should use redo for this");
+  return Action::success;
+}
+
+Action::state_ptr ActionHistory::UndoAction::performRedo(Action::state_ptr){
+  ASSERT(0,"Cannot redo an undo");
+  return Action::success;
+}
+
+ActionHistory::RedoAction::RedoAction(ActionHistory *_hist) :
+    Action("Redo"),
+    hist(_hist)
+{}
+
+ActionHistory::RedoAction::~RedoAction(){}
+
+bool ActionHistory::RedoAction::canUndo(){
+  return false;
+}
+
+bool ActionHistory::RedoAction::shouldUndo(){
+  return false;
+}
+
+bool ActionHistory::RedoAction::isActive(){
+  return hist->hasRedo();
+}
+
+Action::state_ptr ActionHistory::RedoAction::performCall(){
+  hist->redoLast();
+  return Action::success;
+}
+
+Action::state_ptr ActionHistory::RedoAction::performUndo(Action::state_ptr){
+  ASSERT(0,"Cannot undo a redo (should use undo for this");
+  return Action::success;
+}
+
+Action::state_ptr ActionHistory::RedoAction::performRedo(Action::state_ptr){
+  ASSERT(0,"Cannot redo a redo");
+  return Action::success;
+}
Index: src/Actions/ActionHistory.hpp
===================================================================
--- src/Actions/ActionHistory.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/ActionHistory.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,92 @@
+/*
+ * ActionHistory.hpp
+ *
+ *  Created on: Mar 25, 2010
+ *      Author: crueger
+ */
+
+#ifndef ACTIONHISTORY_HPP_
+#define ACTIONHISTORY_HPP_
+
+#include "Patterns/Singleton.hpp"
+
+#include <deque>
+
+#include "Actions/Action.hpp"
+
+
+class ActionHistory : public Singleton<ActionHistory,false>
+{
+  friend class Singleton<ActionHistory,false>;
+
+  struct HistoryElement {
+    HistoryElement(Action *_action, Action::state_ptr _state) :
+      action(_action),
+      state(_state)
+    {}
+    Action *action;
+    Action::state_ptr state;
+  };
+
+  class UndoAction : public Action {
+  public:
+    UndoAction(ActionHistory*);
+    virtual ~UndoAction();
+
+    virtual bool canUndo();
+    virtual bool shouldUndo();
+
+    virtual bool isActive();
+
+  private:
+    virtual Action::state_ptr performCall();
+    virtual Action::state_ptr performUndo(Action::state_ptr);
+    virtual Action::state_ptr performRedo(Action::state_ptr);
+
+    ActionHistory *hist;
+  };
+
+  class RedoAction : public Action {
+  public:
+    RedoAction(ActionHistory*);
+    virtual ~RedoAction();
+
+    virtual bool canUndo();
+    virtual bool shouldUndo();
+
+    virtual bool isActive();
+
+  private:
+    virtual Action::state_ptr performCall();
+    virtual Action::state_ptr performUndo(Action::state_ptr);
+    virtual Action::state_ptr performRedo(Action::state_ptr);
+
+    ActionHistory *hist;
+  };
+
+public:
+
+  void undoLast();
+  void redoLast();
+
+  bool hasUndo();
+  bool hasRedo();
+
+  void addElement(Action*,Action::state_ptr);
+  void clear();
+protected:
+  ActionHistory();
+  virtual ~ActionHistory();
+private:
+  std::deque<HistoryElement> history;
+  std::deque<HistoryElement> yrotsih;
+
+public:
+  // when constructing the actions we need the Actionregistry Singleton
+  // Singletons need static variables to work, but we cannot access statics
+  // inside a static initialization, so we have this init function that
+  // needs to be called at a non-static point at the start of the program
+  static void init();
+};
+
+#endif /* ACTIONHISTORY_HPP_ */
Index: src/Actions/ActionRegistry.cpp
===================================================================
--- src/Actions/ActionRegistry.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/ActionRegistry.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,11 +9,11 @@
 #include "Actions/Action.hpp"
 
+#include "Patterns/Singleton_impl.hpp"
+
 #include <string>
-#include <cassert>
+#include "Helpers/Assert.hpp"
 #include <iostream>
 
 using namespace std;
-
-ActionRegistry *ActionRegistry::theInstance=0;
 
 ActionRegistry::ActionRegistry()
@@ -24,8 +24,8 @@
 {
   map<const string,Action*>::iterator iter;
-  for(iter=actionMap.begin();iter!=actionMap.end();iter++) {
+  for(iter=actionMap.begin();iter!=actionMap.end();++iter) {
     delete iter->second;
-    actionMap.erase(iter);
   }
+  actionMap.clear();
 }
 
@@ -33,5 +33,5 @@
   map<const string,Action*>::iterator iter;
   iter = actionMap.find(name);
-  assert(iter!=actionMap.end() && "Query for an action not stored in registry");
+  ASSERT(iter!=actionMap.end(),"Query for an action not stored in registry");
   return iter->second;
 }
@@ -40,19 +40,16 @@
   pair<map<const string,Action*>::iterator,bool> ret;
   ret = actionMap.insert(pair<const string,Action*>(action->getName(),action));
-  assert(ret.second && "Two actions with the same name added to registry");
+  ASSERT(ret.second,"Two actions with the same name added to registry");
 }
 
-// singleton stuff
-ActionRegistry* ActionRegistry::getRegistry(){
-  if(!theInstance){
-    theInstance = new ActionRegistry();
-  }
-  return theInstance;
+std::map<const std::string,Action*>::iterator ActionRegistry::getBeginIter()
+{
+  return actionMap.begin();
 }
 
-void ActionRegistry::purgeRegistry(){
-  if(theInstance){
-    delete theInstance;
-    theInstance = 0;
-  }
+std::map<const std::string,Action*>::iterator ActionRegistry::getEndIter()
+{
+  return actionMap.end();
 }
+
+CONSTRUCT_SINGLETON(ActionRegistry)
Index: src/Actions/ActionRegistry.hpp
===================================================================
--- src/Actions/ActionRegistry.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/ActionRegistry.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -12,23 +12,24 @@
 #include <map>
 
+#include "Patterns/Singleton.hpp"
+
 class Action;
 
-class ActionRegistry
+class ActionRegistry : public Singleton<ActionRegistry>
 {
+  friend class Singleton<ActionRegistry>;
 public:
   Action* getActionByName(const std::string);
   void registerAction(Action*);
 
+  std::map<const std::string,Action*>::iterator getBeginIter();
+  std::map<const std::string,Action*>::iterator getEndIter();
+
 private:
   std::map<const std::string,Action*> actionMap;
 
-// singleton stuff
-public:
-  static ActionRegistry* getRegistry();
-  static void purgeRegistry();
 private:
   ActionRegistry();
   virtual ~ActionRegistry();
-  static ActionRegistry *theInstance;
 };
 
Index: src/Actions/ActionSequence.cpp
===================================================================
--- src/Actions/ActionSequence.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/ActionSequence.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -8,4 +8,6 @@
 #include "Actions/ActionSequence.hpp"
 #include "Actions/Action.hpp"
+
+#include "Helpers/Assert.hpp"
 
 using namespace std;
@@ -34,21 +36,80 @@
 }
 
+// this method is used outside the ActionModule
+// Each action registers itself with the history
 void ActionSequence::callAll(){
-  deque<Action*>::iterator it;
-  for(it=actions.begin(); it!=actions.end(); it++)
+  for(actionSet::iterator it=actions.begin(); it!=actions.end(); it++){
+    // we want to have a global bookkeeping for all actions in the sequence, so
+    // we bypass the normal call
     (*it)->call();
+  }
 }
 
-void ActionSequence::undoAll(){
-  deque<Action*>::reverse_iterator rit;
-  for(rit=actions.rbegin(); rit!=actions.rend(); rit++)
-    (*rit)->undo();
+// This method is used internally when MakroActions are constructed.
+// In this case only the makro Action should be registered and
+// handle the states
+ActionSequence::stateSet ActionSequence::callAll(bool){
+  stateSet states;
+  for(actionSet::iterator it=actions.begin(); it!=actions.end(); it++){
+    // we want to have a global bookkeeping for all actions in the sequence, so
+    // we bypass the normal call
+    Action::state_ptr state = (*it)->performCall();
+    states.push_back(state);
+  }
+  return states;
+}
+
+ActionSequence::stateSet ActionSequence::undoAll(stateSet states){
+  ASSERT(canUndo(),"Trying to undo a sequence that contains methods that can't be undone");
+  stateSet res;
+  actionSet::reverse_iterator actionRit = actions.rbegin();
+  stateSet::reverse_iterator stateRit = states.rbegin();
+  for(;actionRit!=actions.rend();++actionRit,++stateRit){
+    ASSERT(stateRit!=states.rend(),"End of states prematurely reached.");
+    if((*actionRit)->shouldUndo()){
+      Action::state_ptr newState = (*actionRit)->performUndo(*stateRit);
+      // The order of the states has to correspond to the order of the actions
+      // this is why we have to add at the beginning
+      res.push_front(newState);
+    }
+    else{
+      res.push_front(Action::success);
+    }
+  }
+  return res;
+}
+
+ActionSequence::stateSet ActionSequence::redoAll(stateSet states){
+  stateSet res;
+  actionSet::iterator actionIt = actions.begin();
+  stateSet::iterator stateIt = states.begin();
+  for(;actionIt!=actions.end();++actionIt,++stateIt){
+    ASSERT(stateIt!=states.end(),"End of states prematurely reached.");
+    if((*actionIt)->shouldUndo()){
+      Action::state_ptr newState =(*actionIt)->performRedo(*stateIt);
+      res.push_back(newState);
+    }
+    else{
+      res.push_back(Action::success);
+    }
+  }
+  return res;
 }
 
 bool ActionSequence::canUndo(){
   bool canUndo=true;
-  deque<Action*>::iterator it;
-  for(it=actions.begin(); it!=actions.end(); it++)
-    canUndo &= (*it)->canUndo();
+  for(deque<Action*>::iterator it=actions.begin(); it!=actions.end(); ++it){
+    if((*it)->shouldUndo()){
+      canUndo &= (*it)->canUndo();
+    }
+  }
   return canUndo;
 }
+
+bool ActionSequence::shouldUndo(){
+  bool shouldUndo = false;
+  for(deque<Action*>::iterator it=actions.begin();it!=actions.end();++it){
+    shouldUndo |= (*it)->shouldUndo();
+  }
+  return shouldUndo;
+}
Index: src/Actions/ActionSequence.hpp
===================================================================
--- src/Actions/ActionSequence.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/ActionSequence.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,7 +9,7 @@
 #define ACTIONSEQUENZE_HPP_
 
+#include "Actions/Action.hpp"
+
 #include <deque>
-
-class Action;
 
 /**
@@ -18,5 +18,9 @@
 class ActionSequence
 {
+  friend class MakroAction;
 public:
+  typedef std::deque<Action*> actionSet;
+  typedef std::deque<Action::state_ptr> stateSet;
+
   ActionSequence();
   virtual ~ActionSequence();
@@ -26,10 +30,14 @@
 
   void callAll();
-  void undoAll();
 
   bool canUndo();
+  bool shouldUndo();
 
+protected:
+  stateSet callAll(bool); // Dummy parameter to allow overloading
+  stateSet undoAll(stateSet);
+  stateSet redoAll(stateSet);
 private:
-  std::deque<Action*> actions;
+  actionSet actions;
 };
 
Index: src/Actions/AtomsCalculation.hpp
===================================================================
--- src/Actions/AtomsCalculation.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/AtomsCalculation.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,28 @@
+/*
+ * AtomsCalculation.hpp
+ *
+ *  Created on: Feb 19, 2010
+ *      Author: crueger
+ */
+
+#ifndef ATOMSCALCULATION_HPP_
+#define ATOMSCALCULATION_HPP_
+
+#include "Actions/Calculation.hpp"
+
+template<typename T>
+class AtomsCalculation : public Calculation<std::vector<T> >
+{
+public:
+  AtomsCalculation(boost::function<T(atom*)> op,std::string name,AtomDescriptor descr);
+  virtual ~AtomsCalculation();
+
+protected:
+  virtual std::vector<T>* doCalc();
+
+private:
+  AtomDescriptor descr;
+  boost::function<T(atom*)> op;
+};
+
+#endif /* ATOMSCALCULATION_HPP_ */
Index: src/Actions/AtomsCalculation_impl.hpp
===================================================================
--- src/Actions/AtomsCalculation_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/AtomsCalculation_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,46 @@
+/*
+ * AtomsCalculation_impl.hpp
+ *
+ *  Created on: Feb 19, 2010
+ *      Author: crueger
+ */
+
+#ifndef ATOMSCALCULATION_IMPL_HPP_
+#define ATOMSCALCULATION_IMPL_HPP_
+
+#include "Actions/AtomsCalculation.hpp"
+#include "Actions/Calculation_impl.hpp"
+
+#include <iostream>
+
+using namespace std;
+
+template<typename T>
+AtomsCalculation<T>::AtomsCalculation(boost::function<T(atom*)> _op,std::string name,AtomDescriptor _descr) :
+  Calculation<std::vector<T> >(0,name,false),
+  descr(_descr),
+  op(_op)
+{}
+
+template<typename T>
+AtomsCalculation<T>::~AtomsCalculation(){
+}
+
+template<typename T>
+std::vector<T>* AtomsCalculation<T>::doCalc(){
+  World* world = World::getPointer();
+  int steps = world->numAtoms();
+  std::vector<T> *res = new std::vector<T>();
+  res->reserve(steps);
+  Process::setMaxSteps(steps);
+  Process::start();
+  for(World::AtomIterator iter=world->getAtomIter(descr);iter!=world->atomEnd();++iter){
+    Process::setCurrStep(iter.getCount());
+    res->push_back(op(*iter));
+  }
+  Process::stop();
+  return res;
+}
+
+
+#endif /* ATOMSCALCULATION_IMPL_HPP_ */
Index: src/Actions/Calculation.hpp
===================================================================
--- src/Actions/Calculation.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/Calculation.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,73 @@
+/*
+ * Calculation.hpp
+ *
+ *  Created on: Feb 19, 2010
+ *      Author: crueger
+ */
+
+#ifndef CALCULATION_HPP_
+#define CALCULATION_HPP_
+
+#include "Actions/Process.hpp"
+
+/**
+ * A calculation is a Process that has some kind of result.
+ *
+ * This class can be used in the same way as any other Action or Process, but has some special methods
+ * for inspecting the result of the calculation.
+ */
+template<typename T>
+class Calculation : public Process
+{
+public:
+  Calculation(int _maxSteps, std::string _name, bool _doRegister=true);
+  virtual ~Calculation();
+
+  /**
+   * Reimplemented call method for Action Base class.
+   * Resets the result and then redoes the calculation. Can be used to retrigger calculations
+   * from menu Items or other places.
+   */
+  virtual bool canUndo();
+
+  virtual bool shouldUndo();
+
+  /**
+   * Does the actual calculation and returns the result.
+   * When the calculation has been done before it is not redone, but the previous cached result is returned.
+   * Call reset to delete the cached value.
+   */
+  virtual T operator()();
+
+  /**
+   * Check if a cached result is available.
+   */
+  virtual bool hasResult();
+
+  /**
+   * Get the cached result.
+   * Fails if there is no cached result.
+   */
+  virtual T getResult();
+
+  /**
+   * Delete a previously calculated result from the cache.
+   */
+  virtual void reset();
+
+protected:
+  T* result;
+
+  /**
+   * Pure virtual method for implementation of the actual calculation procedure.
+   */
+  virtual T* doCalc()=0;
+private:
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
+  bool done;
+};
+
+#endif /* CALCULATION_HPP_ */
Index: src/Actions/Calculation_impl.hpp
===================================================================
--- src/Actions/Calculation_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/Calculation_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,89 @@
+/*
+ * Calculation_impl.hpp
+ *
+ *  Created on: Feb 19, 2010
+ *      Author: crueger
+ */
+
+#ifndef CALCULATION_IMPL_HPP_
+#define CALCULATION_IMPL_HPP_
+
+#include "Actions/Calculation.hpp"
+
+#include <cassert>
+
+template<typename T>
+Calculation<T>::Calculation(int _maxSteps, std::string _name, bool _doRegister) :
+  Process(_maxSteps,_name,_doRegister),
+  result(0),
+  done(false)
+{}
+
+template<typename T>
+Calculation<T>::~Calculation()
+{
+  delete result;
+}
+
+// methods inherited from Action
+
+template<typename T>
+Action::state_ptr Calculation<T>::performCall(){
+  reset();
+  (*this)();
+  return Action::success;
+}
+
+template<typename T>
+Action::state_ptr Calculation<T>::performUndo(Action::state_ptr){
+  ASSERT(0,"Cannot undo a calculation");
+  return Action::success;
+}
+template<typename T>
+Action::state_ptr Calculation<T>::performRedo(Action::state_ptr){
+  ASSERT(0,"Cannot redo a calculation");
+  return Action::success;
+}
+
+template<typename T>
+bool Calculation<T>::canUndo()
+{
+  return false;
+}
+
+template<typename T>
+bool Calculation<T>::shouldUndo()
+{
+  return false;
+}
+
+// methods for calculation infrastructure
+
+template<typename T>
+T Calculation<T>::operator()(){
+  if(!done){
+    result = doCalc();
+    done = true;
+  }
+  return *result;
+}
+
+template<typename T>
+bool Calculation<T>::hasResult(){
+  return done;
+}
+
+template<typename T>
+T Calculation<T>::getResult(){
+  assert(done && "No result calculated");
+  return *result;
+}
+
+template<typename T>
+void Calculation<T>::reset(){
+  done = false;
+  delete result;
+  result = 0;
+}
+
+#endif /* CALCULATION_IMPL_HPP_ */
Index: src/Actions/CmdAction/HelpAction.cpp
===================================================================
--- src/Actions/CmdAction/HelpAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/CmdAction/HelpAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,68 @@
+/*
+ * HelpAction.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#include "Actions/CmdAction/HelpAction.hpp"
+#include "CommandLineParser.hpp"
+
+#include <iostream>
+#include <string>
+
+using namespace std;
+
+#include "UIElements/UIFactory.hpp"
+#include "UIElements/Dialog.hpp"
+
+const char CommandLineHelpAction::NAME[] = "help";
+
+CommandLineHelpAction::CommandLineHelpAction() :
+  Action(NAME)
+{}
+
+CommandLineHelpAction::~CommandLineHelpAction()
+{}
+
+Action::state_ptr CommandLineHelpAction::performCall() {
+  ostringstream usage;
+  Dialog *dialog = UIFactory::getInstance().makeDialog();
+
+  usage << CommandLineParser::getInstance().visible << endl;
+  dialog->queryEmpty(NAME, usage.str());
+
+  if(dialog->display()) {
+    delete dialog;
+    return Action::success;
+  } else {
+    delete dialog;
+    return Action::failure;
+  }
+}
+
+Action::state_ptr CommandLineHelpAction::performUndo(Action::state_ptr _state) {
+//  ParserLoadXyzState *state = assert_cast<ParserLoadXyzState*>(_state.get());
+
+  return Action::failure;
+//  string newName = state->mol->getName();
+//  state->mol->setName(state->lastName);
+//
+//  return Action::state_ptr(new ParserLoadXyzState(state->mol,newName));
+}
+
+Action::state_ptr CommandLineHelpAction::performRedo(Action::state_ptr _state){
+  return Action::failure;
+}
+
+bool CommandLineHelpAction::canUndo() {
+  return false;
+}
+
+bool CommandLineHelpAction::shouldUndo() {
+  return false;
+}
+
+const string CommandLineHelpAction::getName() {
+  return NAME;
+}
Index: src/Actions/CmdAction/HelpAction.hpp
===================================================================
--- src/Actions/CmdAction/HelpAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/CmdAction/HelpAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,30 @@
+/*
+ * HelpAction.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef HELPACTION_HPP_
+#define HELPACTION_HPP_
+
+#include "Actions/Action.hpp"
+
+class CommandLineHelpAction : public Action {
+public:
+  CommandLineHelpAction();
+  virtual ~CommandLineHelpAction();
+
+  bool canUndo();
+  bool shouldUndo();
+
+  virtual const std::string getName();
+private:
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
+  static const char NAME[];
+};
+
+#endif /* HELPACTION_HPP_ */
Index: src/Actions/CmdAction/VersionAction.cpp
===================================================================
--- src/Actions/CmdAction/VersionAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/CmdAction/VersionAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,66 @@
+/*
+ * VersionAction.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#include "Actions/CmdAction/VersionAction.hpp"
+#include "CommandLineParser.hpp"
+
+#include <iostream>
+#include <string>
+
+using namespace std;
+
+#include "UIElements/UIFactory.hpp"
+#include "UIElements/Dialog.hpp"
+
+const char CommandLineVersionAction::NAME[] = "version";
+
+CommandLineVersionAction::CommandLineVersionAction() :
+  Action(NAME)
+{}
+
+CommandLineVersionAction::~CommandLineVersionAction()
+{}
+
+Action::state_ptr CommandLineVersionAction::performCall() {
+  Dialog *dialog = UIFactory::getInstance().makeDialog();
+
+  dialog->queryEmpty(NAME, ESPACKVersion);
+
+  if(dialog->display()) {
+    delete dialog;
+    return Action::success;
+  } else {
+    delete dialog;
+    return Action::failure;
+  }
+}
+
+Action::state_ptr CommandLineVersionAction::performUndo(Action::state_ptr _state) {
+//  ParserLoadXyzState *state = assert_cast<ParserLoadXyzState*>(_state.get());
+
+  return Action::failure;
+//  string newName = state->mol->getName();
+//  state->mol->setName(state->lastName);
+//
+//  return Action::state_ptr(new ParserLoadXyzState(state->mol,newName));
+}
+
+Action::state_ptr CommandLineVersionAction::performRedo(Action::state_ptr _state){
+  return Action::failure;
+}
+
+bool CommandLineVersionAction::canUndo() {
+  return false;
+}
+
+bool CommandLineVersionAction::shouldUndo() {
+  return false;
+}
+
+const string CommandLineVersionAction::getName() {
+  return NAME;
+}
Index: src/Actions/CmdAction/VersionAction.hpp
===================================================================
--- src/Actions/CmdAction/VersionAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/CmdAction/VersionAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,31 @@
+/*
+ * VersionAction.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef VERSIONACTION_HPP_
+#define VERSIONACTION_HPP_
+
+#include "Actions/Action.hpp"
+#include "version.h"
+
+class CommandLineVersionAction : public Action {
+public:
+  CommandLineVersionAction();
+  virtual ~CommandLineVersionAction();
+
+  bool canUndo();
+  bool shouldUndo();
+
+  virtual const std::string getName();
+private:
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
+  static const char NAME[];
+};
+
+#endif /* VERSIONACTION_HPP_ */
Index: src/Actions/ErrorAction.cpp
===================================================================
--- src/Actions/ErrorAction.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/ErrorAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -11,4 +11,5 @@
 #include "log.hpp"
 #include "verbose.hpp"
+#include "Helpers/Assert.hpp"
 
 using namespace std;
@@ -24,8 +25,16 @@
 }
 
-void ErrorAction::call() {
+Action::state_ptr ErrorAction::performCall() {
   Log() << Verbose(0) << errorMsg << endl;
+  return Action::success;
 }
-void ErrorAction::undo() {
+Action::state_ptr ErrorAction::performUndo(Action::state_ptr) {
+  ASSERT(0,"Undo called for an ErrorAction");
+  return Action::success;
+}
+
+Action::state_ptr ErrorAction::performRedo(Action::state_ptr) {
+  ASSERT(0,"Redo called for an ErrorAction");
+  return Action::success;
 }
 
@@ -33,2 +42,6 @@
   return false;
 }
+
+bool ErrorAction::shouldUndo(){
+  return false;
+}
Index: src/Actions/ErrorAction.hpp
===================================================================
--- src/Actions/ErrorAction.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/ErrorAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -18,9 +18,13 @@
   virtual ~ErrorAction();
 
-  virtual void call();
-  virtual void undo();
   virtual bool canUndo();
+  virtual bool shouldUndo();
 
 private:
+
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
   std::string errorMsg;
 };
Index: src/Actions/MakroAction.cpp
===================================================================
--- src/Actions/MakroAction.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/MakroAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -11,6 +11,19 @@
 #include "Actions/Action.hpp"
 #include "Actions/ActionSequence.hpp"
+#include "Helpers/Assert.hpp"
 
 using namespace std;
+
+class MakroActionState : public ActionState{
+public:
+  MakroActionState(ActionSequence::stateSet _states) :
+    states(_states)
+  {}
+  virtual ~MakroActionState(){
+    // All contained states are destroyed by the shared ptrs
+  }
+
+  ActionSequence::stateSet states;
+};
 
 MakroAction::MakroAction(string _name,ActionSequence* _actions,bool _doRegister) :
@@ -23,5 +36,5 @@
 {
   Action* action;
-  while(action=actions->removeLastAction()){
+  while((action=actions->removeLastAction())){
     delete action;
   }
@@ -30,10 +43,21 @@
 
 
-void MakroAction::call(){
-  actions->callAll();
+Action::state_ptr MakroAction::performCall(){
+  ActionSequence::stateSet states = actions->callAll(true);
+  return Action::state_ptr(new MakroActionState(states));
 }
 
-void MakroAction::undo() {
-  actions->undoAll();
+Action::state_ptr MakroAction::performUndo(Action::state_ptr _state) {
+  MakroActionState *state = dynamic_cast<MakroActionState*>(_state.get());
+  ASSERT(state,"Type mismatch for the state of the MakroAction");
+  ActionSequence::stateSet states = actions->undoAll(state->states);
+  return Action::state_ptr(new MakroActionState(states));
+}
+
+Action::state_ptr MakroAction::performRedo(Action::state_ptr _state){
+  MakroActionState *state = dynamic_cast<MakroActionState*>(_state.get());
+  ASSERT(state,"Type mismatch for the state of the MakroAction");
+  ActionSequence::stateSet states = actions->redoAll(state->states);
+  return Action::state_ptr(new MakroActionState(states));
 }
 
@@ -41,2 +65,6 @@
   return actions->canUndo();
 }
+
+bool MakroAction::shouldUndo() {
+  return actions->shouldUndo();
+}
Index: src/Actions/MakroAction.hpp
===================================================================
--- src/Actions/MakroAction.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/MakroAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -26,9 +26,12 @@
   virtual ~MakroAction();
 
-  virtual void call();
-  virtual void undo();
-  virtual bool canUndo();
+  bool canUndo();
+  bool shouldUndo();
 
 private:
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
   ActionSequence *actions;
 };
Index: src/Actions/ManipulateAtomsProcess.cpp
===================================================================
--- src/Actions/ManipulateAtomsProcess.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/ManipulateAtomsProcess.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,58 @@
+/*
+ * ManipulateAtomsProcess.cpp
+ *
+ *  Created on: Feb 18, 2010
+ *      Author: crueger
+ */
+
+#include "ManipulateAtomsProcess.hpp"
+
+#include <iostream>
+
+#include "World.hpp"
+#include "Helpers/Assert.hpp"
+
+using namespace std;
+
+ManipulateAtomsProcess::ManipulateAtomsProcess(boost::function<void(atom*)> _operation, AtomDescriptor _descr,
+                                               std::string _name,bool _doRegister) :
+  Process(0,_name,_doRegister),
+  descr(_descr),
+  operation(_operation)
+{}
+
+ManipulateAtomsProcess::~ManipulateAtomsProcess()
+{}
+
+Action::state_ptr ManipulateAtomsProcess::performCall(){
+  World::getInstance().doManipulate(this);
+  return Action::success;
+}
+
+Action::state_ptr ManipulateAtomsProcess::performUndo(Action::state_ptr){
+  ASSERT(0,"Undo called for a ManipulateAtomsProcess");
+  return Action::success;
+}
+
+Action::state_ptr ManipulateAtomsProcess::performRedo(Action::state_ptr){
+  ASSERT(0,"Redo called for a ManipulateAtomsProcess");
+  return Action::success;
+}
+
+bool ManipulateAtomsProcess::canUndo(){
+  return false;
+}
+
+bool ManipulateAtomsProcess::shouldUndo(){
+  return true;
+}
+
+void ManipulateAtomsProcess::doManipulate(World *world){
+  setMaxSteps(world->numAtoms());
+  start();
+  for(World::AtomIterator iter=world->getAtomIter(descr);iter!=world->atomEnd();++iter){
+    setCurrStep(iter.getCount());
+    operation(*iter);
+  }
+  stop();
+}
Index: src/Actions/ManipulateAtomsProcess.hpp
===================================================================
--- src/Actions/ManipulateAtomsProcess.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/ManipulateAtomsProcess.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,39 @@
+/*
+ * ManipulateAtomsProcess.hpp
+ *
+ *  Created on: Feb 18, 2010
+ *      Author: crueger
+ */
+
+#ifndef MANIPULATEATOMSPROCESS_HPP_
+#define MANIPULATEATOMSPROCESS_HPP_
+
+#include "Actions/Process.hpp"
+
+#include<boost/function.hpp>
+
+#include "Descriptors/AtomDescriptor.hpp"
+
+class World;
+
+class ManipulateAtomsProcess : public Process
+{
+public:
+  ManipulateAtomsProcess(boost::function<void(atom*)> _operation, AtomDescriptor descr,std::string _name,bool _doRegister=true);
+  virtual ~ManipulateAtomsProcess();
+
+  virtual bool canUndo();
+  virtual bool shouldUndo();
+
+  virtual void doManipulate(World *);
+private:
+
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
+  AtomDescriptor descr;
+  boost::function<void(atom*)> operation;
+};
+
+#endif /* MANIPULATEATOMSPROCESS_HPP_ */
Index: src/Actions/MethodAction.cpp
===================================================================
--- src/Actions/MethodAction.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/MethodAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,5 +10,6 @@
 #include <string>
 
-#include "MethodAction.hpp"
+#include "Actions/MethodAction.hpp"
+#include "Helpers/Assert.hpp"
 
 using namespace std;
@@ -21,14 +22,21 @@
 
 MethodAction::~MethodAction()
-{
-  // TODO Auto-generated destructor stub
+{}
+
+
+Action::state_ptr MethodAction::performCall() {
+  executeMethod();
+  // we don't have a state to save so we return Action::success
+  return Action::success;
 }
 
+Action::state_ptr MethodAction::performUndo(Action::state_ptr) {
+  ASSERT(0,"Cannot undo a MethodAction");
+  return Action::success;
+}
 
-void MethodAction::call() {
-  executeMethod();
-}
-void MethodAction::undo() {
-
+Action::state_ptr MethodAction::performRedo(Action::state_ptr){
+  ASSERT(0,"Cannot redo a MethodAction");
+  return Action::success;
 }
 
@@ -36,2 +44,6 @@
   return false;
 }
+
+bool MethodAction::shouldUndo(){
+  return true;
+}
Index: src/Actions/MethodAction.hpp
===================================================================
--- src/Actions/MethodAction.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/MethodAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -22,12 +22,14 @@
   MethodAction(std::string _name,boost::function<void()> _executeMethod,bool _doRegister=true);
   virtual ~MethodAction();
+  virtual bool canUndo();
+  virtual bool shouldUndo();
 
-  virtual void call();
-  virtual void undo();
-  virtual bool canUndo();
+private:
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
 
   boost::function<void()> executeMethod; //!< this stores the method to be called
-
-
 };
 
Index: src/Actions/MoleculeAction/ChangeNameAction.cpp
===================================================================
--- src/Actions/MoleculeAction/ChangeNameAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/MoleculeAction/ChangeNameAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,87 @@
+/*
+ * ChangeNameAction.cpp
+ *
+ *  Created on: Jan 15, 2010
+ *      Author: crueger
+ */
+
+#include "Actions/MoleculeAction/ChangeNameAction.hpp"
+
+#include <iostream>
+#include <string>
+
+using namespace std;
+
+#include "UIElements/UIFactory.hpp"
+#include "UIElements/Dialog.hpp"
+
+#include "atom.hpp"
+#include "molecule.hpp"
+
+/****** MoleculeChangeNameAction *****/
+
+// memento to remember the state when undoing
+
+class MoleculeChangeNameState : public ActionState {
+public:
+  MoleculeChangeNameState(molecule* _mol,std::string _lastName) :
+    mol(_mol),
+    lastName(_lastName)
+  {}
+  molecule* mol;
+  std::string lastName;
+};
+
+const char MoleculeChangeNameAction::NAME[] = "Change filename of Molecule";
+
+MoleculeChangeNameAction::MoleculeChangeNameAction(MoleculeListClass *_molecules) :
+  Action(NAME),
+  molecules(_molecules)
+{}
+
+MoleculeChangeNameAction::~MoleculeChangeNameAction()
+{}
+
+Action::state_ptr MoleculeChangeNameAction::performCall() {
+  string filename;
+  molecule *mol = NULL;
+  Dialog *dialog = UIFactory::getInstance().makeDialog();
+
+  dialog->queryMolecule("Enter index of molecule: ",&mol,molecules);
+  dialog->queryString("Enter name: ",&filename);
+
+  if(dialog->display()) {
+    string oldName = mol->getName();
+    mol->setName(filename);
+    delete dialog;
+    return Action::state_ptr(new MoleculeChangeNameState(mol,oldName));
+  }
+  delete dialog;
+  return Action::failure;
+}
+
+Action::state_ptr MoleculeChangeNameAction::performUndo(Action::state_ptr _state) {
+  MoleculeChangeNameState *state = assert_cast<MoleculeChangeNameState*>(_state.get());
+
+  string newName = state->mol->getName();
+  state->mol->setName(state->lastName);
+
+  return Action::state_ptr(new MoleculeChangeNameState(state->mol,newName));
+}
+
+Action::state_ptr MoleculeChangeNameAction::performRedo(Action::state_ptr _state){
+  // Undo and redo have to do the same for this action
+  return performUndo(_state);
+}
+
+bool MoleculeChangeNameAction::canUndo() {
+  return true;
+}
+
+bool MoleculeChangeNameAction::shouldUndo() {
+  return true;
+}
+
+const string MoleculeChangeNameAction::getName() {
+  return NAME;
+}
Index: src/Actions/MoleculeAction/ChangeNameAction.hpp
===================================================================
--- src/Actions/MoleculeAction/ChangeNameAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/MoleculeAction/ChangeNameAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,35 @@
+/*
+ * ChangeNameAction.hpp
+ *
+ *  Created on: Jan 15, 2010
+ *      Author: crueger
+ */
+
+#ifndef CHANGENAMEACTION_HPP
+#define CHANGENAMEACTION_HPP
+
+#include "Actions/Action.hpp"
+#include "Actions/Process.hpp"
+
+class MoleculeListClass;
+
+class MoleculeChangeNameAction : public Action {
+public:
+  MoleculeChangeNameAction(MoleculeListClass*);
+  virtual ~MoleculeChangeNameAction();
+
+  bool canUndo();
+  bool shouldUndo();
+
+  virtual const std::string getName();
+private:
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
+  MoleculeListClass *molecules;
+  static const char NAME[];
+};
+
+
+#endif // CHANGENAMEACTION_HPP
Index: src/Actions/ParserAction/LoadXyzAction.cpp
===================================================================
--- src/Actions/ParserAction/LoadXyzAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/ParserAction/LoadXyzAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,88 @@
+/*
+ * LoadXyzAction.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#include "Actions/ParserAction/LoadXyzAction.hpp"
+#include "Parser/XyzParser.hpp"
+
+#include <iostream>
+#include <string>
+
+using namespace std;
+
+#include "UIElements/UIFactory.hpp"
+#include "UIElements/Dialog.hpp"
+
+#include "atom.hpp"
+#include "molecule.hpp"
+
+/****** ParserLoadXyzAction *****/
+
+//// memento to remember the state when undoing
+//
+//class ParserLoadXyzState : public ActionState {
+//public:
+//  ParserLoadXyzState(molecule* _mol,std::string _lastName) :
+//    mol(_mol),
+//    lastName(_lastName)
+//  {}
+//  molecule* mol;
+//  std::string lastName;
+//};
+
+const char ParserLoadXyzAction::NAME[] = "LoadXyz";
+
+ParserLoadXyzAction::ParserLoadXyzAction() :
+  Action(NAME)
+{}
+
+ParserLoadXyzAction::~ParserLoadXyzAction()
+{}
+
+Action::state_ptr ParserLoadXyzAction::performCall() {
+  string filename;
+  XyzParser parser;
+  Dialog *dialog = UIFactory::getInstance().makeDialog();
+
+  dialog->queryString("filename",&filename, "Filename of the xyz file");
+
+  if(dialog->display()) {
+    // parse xyz file
+    ifstream input;
+    input.open(filename.c_str());
+    if (!input.fail())
+      parser.load(&input);
+    input.close();
+  }
+  delete dialog;
+  return Action::failure;
+}
+
+Action::state_ptr ParserLoadXyzAction::performUndo(Action::state_ptr _state) {
+//  ParserLoadXyzState *state = assert_cast<ParserLoadXyzState*>(_state.get());
+
+  return Action::failure;
+//  string newName = state->mol->getName();
+//  state->mol->setName(state->lastName);
+//
+//  return Action::state_ptr(new ParserLoadXyzState(state->mol,newName));
+}
+
+Action::state_ptr ParserLoadXyzAction::performRedo(Action::state_ptr _state){
+  return Action::failure;
+}
+
+bool ParserLoadXyzAction::canUndo() {
+  return false;
+}
+
+bool ParserLoadXyzAction::shouldUndo() {
+  return false;
+}
+
+const string ParserLoadXyzAction::getName() {
+  return NAME;
+}
Index: src/Actions/ParserAction/LoadXyzAction.hpp
===================================================================
--- src/Actions/ParserAction/LoadXyzAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/ParserAction/LoadXyzAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,31 @@
+/*
+ * LoadXyzAction.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef LOADXYZACTION_HPP_
+#define LOADXYZACTION_HPP_
+
+#include "Actions/Action.hpp"
+#include "Actions/Process.hpp"
+
+class ParserLoadXyzAction : public Action {
+public:
+  ParserLoadXyzAction();
+  virtual ~ParserLoadXyzAction();
+
+  bool canUndo();
+  bool shouldUndo();
+
+  virtual const std::string getName();
+private:
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
+  static const char NAME[];
+};
+
+#endif /* LOADXYZACTION_HPP_ */
Index: src/Actions/ParserAction/SaveXyzAction.cpp
===================================================================
--- src/Actions/ParserAction/SaveXyzAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/ParserAction/SaveXyzAction.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,90 @@
+/*
+ * SaveXyzAction.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#include "Actions/ParserAction/SaveXyzAction.hpp"
+#include "Parser/XyzParser.hpp"
+
+#include <iostream>
+#include <string>
+
+using namespace std;
+
+#include "UIElements/UIFactory.hpp"
+#include "UIElements/Dialog.hpp"
+
+#include "atom.hpp"
+#include "molecule.hpp"
+
+/****** ParserSaveXyzAction *****/
+
+//// memento to remember the state when undoing
+//
+//class ParserSaveXyzState : public ActionState {
+//public:
+//  ParserSaveXyzState(molecule* _mol,std::string _lastName) :
+//    mol(_mol),
+//    lastName(_lastName)
+//  {}
+//  molecule* mol;
+//  std::string lastName;
+//};
+
+const char ParserSaveXyzAction::NAME[] = "SaveXyz";
+
+ParserSaveXyzAction::ParserSaveXyzAction() :
+  Action(NAME)
+{}
+
+ParserSaveXyzAction::~ParserSaveXyzAction()
+{}
+
+Action::state_ptr ParserSaveXyzAction::performCall() {
+  string filename;
+  XyzParser parser;
+  Dialog *dialog = UIFactory::getInstance().makeDialog();
+
+  dialog->queryString("filename",&filename, "Filename of the xyz file");
+
+  if(dialog->display()) {
+    // store xyz file
+    ofstream output;
+    output.open(filename.c_str());
+    if (!output.fail())
+      parser.save(&output);
+    output.close();
+  }
+  delete dialog;
+  return Action::failure;
+}
+
+Action::state_ptr ParserSaveXyzAction::performUndo(Action::state_ptr _state) {
+//  ParserSaveXyzState *state = assert_cast<ParserSaveXyzState*>(_state.get());
+
+  return Action::failure;
+//  string newName = state->mol->getName();
+//  state->mol->setName(state->lastName);
+//
+//  return Action::state_ptr(new ParserSaveXyzState(state->mol,newName));
+}
+
+Action::state_ptr ParserSaveXyzAction::performRedo(Action::state_ptr _state){
+  return Action::failure;
+//  // Undo and redo have to do the same for this action
+//  return performUndo(_state);
+}
+
+bool ParserSaveXyzAction::canUndo() {
+  return false;
+}
+
+bool ParserSaveXyzAction::shouldUndo() {
+  return false;
+}
+
+const string ParserSaveXyzAction::getName() {
+  return NAME;
+}
Index: src/Actions/ParserAction/SaveXyzAction.hpp
===================================================================
--- src/Actions/ParserAction/SaveXyzAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Actions/ParserAction/SaveXyzAction.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,31 @@
+/*
+ * SaveXyzAction.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef SAVEXYZACTION_HPP_
+#define SAVEXYZACTION_HPP_
+
+#include "Actions/Action.hpp"
+#include "Actions/Process.hpp"
+
+class ParserSaveXyzAction : public Action {
+public:
+  ParserSaveXyzAction();
+  virtual ~ParserSaveXyzAction();
+
+  bool canUndo();
+  bool shouldUndo();
+
+  virtual const std::string getName();
+private:
+  virtual Action::state_ptr performCall();
+  virtual Action::state_ptr performUndo(Action::state_ptr);
+  virtual Action::state_ptr performRedo(Action::state_ptr);
+
+  static const char NAME[];
+};
+
+#endif /* SAVEXYZACTION_HPP_ */
Index: src/Actions/Process.cpp
===================================================================
--- src/Actions/Process.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/Process.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -13,7 +13,7 @@
   Action(_name,_doRegister),
   maxSteps(_maxSteps),
+  active(false),
   starts(false),
-  stops(false),
-  active(false)
+  stops(false)
 {}
 
@@ -25,5 +25,5 @@
 
 
-bool Process::isActive(){
+bool Process::isRunning(){
   return active;
 }
@@ -38,5 +38,10 @@
 
 int Process::getCurrStep(){
+  OBSERVE;
   return currStep;
+}
+
+void Process::setCurrStep(int _currStep){
+  currStep = _currStep;
 }
 
@@ -47,8 +52,12 @@
     return 0;
 }
+
 int Process::getMaxSteps(){
   return maxSteps;
 }
 
+void Process::setMaxSteps(int _maxSteps){
+  maxSteps = _maxSteps;
+}
 
 void Process::start(){
@@ -64,19 +73,21 @@
   {
     OBSERVE;
-    active = true;
     currStep=0;
   }
   starts = false;
+  active = true;
 }
+
 void Process::step(){
   OBSERVE;
   currStep++;
 }
+
 void Process::stop(){
+  active=false;
   stops = true;
   {
     OBSERVE;
     currStep=0;
-    active=false;
   }
   {
Index: src/Actions/Process.hpp
===================================================================
--- src/Actions/Process.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Actions/Process.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -19,4 +19,22 @@
 #include "Actions/Action.hpp"
 
+/**
+ * A Process is an Action that might take some time and therefore has special
+ * methods to allow communication with progress indicators. Indicators
+ * can sign on at a global place and will be notified when any process is doing
+ * a calculation.
+ *
+ * A Process has four states:
+ *  - starting: It is in the process of setting itself up, and wants everybody to know that it will start
+ *              the calculation soon. Indicators should set up anything they need for displaying the progress
+ *              when they are notified by a process in this state.
+ *  - active:   The process is currently doing it's thing and wants any indicator to know it's status, i.e.
+ *              the percentage done.
+ *  - stopping: The process has fullfilled it's purpose and is shutting down. Indicators recieving this status
+ *              should also use it to shut down their indication mechanism and delete any objects allocated for
+ *              this Process
+ *  - inactive: This Process is currently sleeping. If a Process is sending out any signals in this state, there
+ *              is something seriously wrong.
+ */
 class Process : public Action, public Observable
 {
@@ -25,10 +43,12 @@
   virtual ~Process();
 
-  bool  isActive();
+  bool  isRunning();
   bool  doesStart();
   bool  doesStop();
   int   getCurrStep();
+  void  setCurrStep(int _currStep);
   float getDoneRatio();
   int   getMaxSteps();
+  void  setMaxSteps(int _maxSteps);
 
 protected:
Index: src/Actions/small_actions.cpp
===================================================================
--- src/Actions/small_actions.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ 	(revision )
@@ -1,54 +1,0 @@
-#include "Actions/small_actions.hpp"
-
-#include <iostream>
-#include <string>
-
-using namespace std;
-
-#include "UIElements/UIFactory.hpp"
-#include "UIElements/Dialog.hpp"
-
-#include "atom.hpp"
-#include "molecule.hpp"
-
-/****** ChangeMoleculeNameAction *****/
-
-char ChangeMoleculeNameAction::NAME[] = "Change filename of Molecule";
-
-ChangeMoleculeNameAction::ChangeMoleculeNameAction(MoleculeListClass *_molecules) :
-  Action(NAME),
-  molecules(_molecules)
-{}
-
-ChangeMoleculeNameAction::~ChangeMoleculeNameAction()
-{}
-
-void ChangeMoleculeNameAction::call() {
-  string filename;
-  molecule *mol = NULL;
-  Dialog *dialog = UIFactory::get()->makeDialog();
-
-  dialog->queryMolecule("Enter index of molecule: ",&mol,molecules);
-  dialog->queryString("Enter name: ",&filename);
-  if(dialog->display()) {
-    mol->setName(filename);
-  }
-
-  delete dialog;
-}
-
-void ChangeMoleculeNameAction::undo() {
-
-}
-
-bool ChangeMoleculeNameAction::canUndo() {
-  return false;
-}
-
-bool ChangeMoleculeNameAction::shouldUndo() {
-  return true;
-}
-
-const string ChangeMoleculeNameAction::getName() {
-  return NAME;
-}
Index: src/Actions/small_actions.hpp
===================================================================
--- src/Actions/small_actions.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ 	(revision )
@@ -1,28 +1,0 @@
-// All rather small Actions should go into this file for simplicities sake
-
-#ifndef _SMALL_ACTIONS_HPP
-#define _SMALL_ACTIONS_HPP
-
-#include "Actions/Action.hpp"
-#include "Actions/Process.hpp"
-
-class MoleculeListClass;
-
-class ChangeMoleculeNameAction : public Action {
-public:
-  ChangeMoleculeNameAction(MoleculeListClass*);
-  virtual ~ChangeMoleculeNameAction();
-
-  void call();
-  void undo();
-  bool canUndo();
-  bool shouldUndo();
-
-  virtual const std::string getName();
-private:
-  MoleculeListClass *molecules;
-  static char NAME[];
-};
-
-
-#endif // _SMALL_ACTIONS_HPP
Index: src/CommandLineParser.cpp
===================================================================
--- src/CommandLineParser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/CommandLineParser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,79 @@
+/*
+ * CommandLineParser.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#include <boost/program_options.hpp>
+#include <fstream>
+#include <iostream>
+
+#include "Patterns/Singleton_impl.hpp"
+#include "CommandLineParser.hpp"
+
+using namespace std;
+
+/** Constructor of class CommandLineParser.
+ *
+ */
+CommandLineParser::CommandLineParser() :
+  generic("Generic options"),
+  config("Configuration"),
+  hidden("Hidden options"),
+  visible("Allowed options")
+{}
+
+/** Destructor of class CommandLineParser.
+ *
+ */
+CommandLineParser::~CommandLineParser()
+{}
+
+/** Parses the command line arguments.
+ * Calls program_options::store() and program_options::notify()
+ */
+void CommandLineParser::Parse()
+{
+  po::store(po::command_line_parser(argc,argv).options(cmdline_options).run(), vm);
+  po::store(po::command_line_parser(argc,argv).options(visible).run(), vm);
+  ifstream input;
+  input.open("example.cfg");
+  if (!input.fail())
+    po::store(po::parse_config_file(input, config_file_options), vm);
+  input.close();
+  po::notify(vm);
+}
+
+/** States whether there are command line arguments.
+ * \return true - there are none, false - there is at least one command line argument
+ */
+bool CommandLineParser::isEmpty()
+{
+  return vm.empty();
+}
+
+/** Sets the options.
+ * \param _argc arg count from main()
+ * \param **_argv argument array from main()
+ */
+void CommandLineParser::setOptions(int _argc, char **_argv)
+{
+  argc = _argc;
+  argv = _argv;
+  cmdline_options.add(generic).add(config).add(hidden);
+  config_file_options.add(config).add(hidden);
+  visible.add(generic).add(config);
+}
+
+/** Makes the Parser parse the command line options with current known options.
+ * \param _argc arg count from main()
+ * \param **_argv argument array from main()
+ */
+void CommandLineParser::Run(int _argc, char **_argv)
+{
+  setOptions(_argc,_argv);
+  Parse();
+}
+
+CONSTRUCT_SINGLETON(CommandLineParser)
Index: src/CommandLineParser.hpp
===================================================================
--- src/CommandLineParser.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/CommandLineParser.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,63 @@
+/*
+ * CommandLineParser.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef COMMANDLINEPARSER_HPP_
+#define COMMANDLINEPARSER_HPP_
+
+#include <boost/program_options.hpp>
+
+namespace po = boost::program_options;
+
+#include "Patterns/Singleton.hpp"
+
+
+class CommandLineParser : public Singleton<CommandLineParser> {
+  friend class Singleton<CommandLineParser>;
+public:
+
+  // Parses the command line arguments in CommandLineParser::**argv with currently known options.
+  void Run(int _argc, char **_argv);
+
+  // Checks whether there have been any commands on the command line.
+  bool isEmpty();
+
+  /* boost's program_options are sorted into three categories:
+   * -# generic options: option available to both command line and config
+   * -# config options: only available in the config file
+   * -# hidden options: options which the user is not shown on "help"
+   */
+  po::options_description generic;
+  po::options_description config;
+  po::options_description hidden;
+
+  po::options_description visible;
+
+  po::variables_map vm;
+
+private:
+  // private constructor and destructor
+  CommandLineParser();
+  virtual ~CommandLineParser();
+
+  /* The following program_options options_decriptions are used to
+   * generate the various cases and call differently in Parse().
+   */
+  po::options_description cmdline_options;
+  po::options_description config_file_options;
+
+  // Sets the options from the three cases.
+  void setOptions(int _argc, char **_argv);
+
+  // Parses all options from command line and config file
+  void Parse();
+
+  // argument counter and array passed on from main()
+  int argc;
+  char **argv;
+};
+
+#endif /* COMMANDLINEPARSER_HPP_ */
Index: src/Descriptors/AtomDescriptor.cpp
===================================================================
--- src/Descriptors/AtomDescriptor.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Descriptors/AtomDescriptor.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -19,6 +19,5 @@
 using namespace std;
 
-typedef map<int,atom*> atoms_t;
-typedef atoms_t::iterator atoms_iter_t;
+typedef World::AtomSet::iterator atoms_iter_t;
 
 /************************ Forwarding object **************************************/
@@ -68,10 +67,10 @@
 }
 
-atoms_t& AtomDescriptor_impl::getAtoms(){
-  return World::get()->atoms;
+World::AtomSet& AtomDescriptor_impl::getAtoms(){
+  return World::getInstance().atoms;
 }
 
 atom* AtomDescriptor_impl::find() {
-  atoms_t atoms = getAtoms();
+  World::AtomSet atoms = getAtoms();
   atoms_iter_t res = find_if(atoms.begin(),atoms.end(),boost::bind(&AtomDescriptor_impl::predicate,this,_1));
   return (res!=atoms.end())?((*res).second):0;
@@ -80,5 +79,5 @@
 vector<atom*> AtomDescriptor_impl::findAll() {
   vector<atom*> res;
-  atoms_t atoms = getAtoms();
+  World::AtomSet atoms = getAtoms();
   atoms_iter_t iter;
   for(iter=atoms.begin();iter!=atoms.end();++iter) {
@@ -98,5 +97,5 @@
 {}
 
-bool AtomAllDescriptor_impl::predicate(std::pair<int,atom*>){
+bool AtomAllDescriptor_impl::predicate(std::pair<atomId_t,atom*>){
   return true;
 }
@@ -112,5 +111,5 @@
 {}
 
-bool AtomNoneDescriptor_impl::predicate(std::pair<int,atom*>){
+bool AtomNoneDescriptor_impl::predicate(std::pair<atomId_t,atom*>){
   return false;
 }
@@ -130,5 +129,5 @@
 {}
 
-bool AtomAndDescriptor_impl::predicate(std::pair<int,atom*> atom){
+bool AtomAndDescriptor_impl::predicate(std::pair<atomId_t,atom*> atom){
   return lhs->predicate(atom) && rhs->predicate(atom);
 }
@@ -146,5 +145,5 @@
 }
 
-bool AtomOrDescriptor_impl::predicate(std::pair<int,atom*> atom){
+bool AtomOrDescriptor_impl::predicate(std::pair<atomId_t,atom*> atom){
   return lhs->predicate(atom) || rhs->predicate(atom);
 }
@@ -166,5 +165,5 @@
 }
 
-bool AtomNotDescriptor_impl::predicate(std::pair<int,atom*> atom){
+bool AtomNotDescriptor_impl::predicate(std::pair<atomId_t,atom*> atom){
  return !(arg->predicate(atom));
 }
Index: src/Descriptors/AtomDescriptor.hpp
===================================================================
--- src/Descriptors/AtomDescriptor.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Descriptors/AtomDescriptor.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -15,4 +15,5 @@
 #include "World.hpp"
 
+class World;
 class atom;
 
@@ -20,7 +21,20 @@
 class AtomDescripter_impl;
 
+/**
+ * An AtomDescriptor describes a Set of Atoms from the World. Can be used for any method that needs to work on
+ * a specific set of Atoms.
+ *
+ * This Class is implemented using the PIMPL-Idion, i.e. this class only contains an abstract structure
+ * that forwards any request to a wrapped pointer-to-implementation. This way operators and calculations
+ * on Descriptors are possible.
+ *
+ * Concrete Implementation Objects can be shared between multiple Wrappers, so make sure that
+ * any Implementation remainst constant during lifetime.
+ */
 class AtomDescriptor {
+  // close coupling to the world to allow access
   friend atom* World::getAtom(AtomDescriptor descriptor);
   friend std::vector<atom*> World::getAllAtoms(AtomDescriptor descriptor);
+  template <class,class,class> friend class SelectiveIterator;
 
   friend AtomDescriptor operator&&(const AtomDescriptor &lhs, const AtomDescriptor &rhs);
@@ -29,15 +43,38 @@
 
 public:
-  typedef boost::shared_ptr<AtomDescriptor_impl> impl_ptr;
+  typedef boost::shared_ptr<AtomDescriptor_impl> impl_ptr; //!< Allow easy changes of the pointer-to-implementation type
 
   AtomDescriptor(impl_ptr);
+
+  /**
+   * Copy constructor.
+   * Takes the Implementation from the copied object and sets it's own pointer to link there.
+   * This way the actuall implementation object is shared between copy and original
+   */
   AtomDescriptor(const AtomDescriptor&);
   ~AtomDescriptor();
 
+  /**
+   * Assignment Operator.
+   *
+   * Implemented by setting the pointer to the new Implementation.
+   */
   AtomDescriptor &operator=(AtomDescriptor &);
 
 protected:
+  /**
+   * forward Method to implementation
+   */
   atom* find();
+
+  /**
+   * forward Method to implementation
+   */
   std::vector<atom*> findAll();
+
+  /**
+   * Return the implementation this Wrapper currently points to.
+   * Used for copying, assignment and in Iterators over subsets of the World.
+   */
   impl_ptr get_impl() const;
 
@@ -46,11 +83,31 @@
 };
 
-// Functions to construct actual descriptors
+/**
+ * produce an Atomdescriptor that at the point of construction contains an implementation that matches all Atoms
+ */
 AtomDescriptor AllAtoms();
+
+/**
+ * produce an Atomdescriptor that at the point of construction contains an implementation that matches no Atoms
+ */
 AtomDescriptor NoAtoms();
 
-// no true short circuit, but the test of the second descriptor wont be done
+/**
+ * Set Intersection for two Atomdescriptors. The resulting Atomdescriptor will only match an Atom if both
+ * given Atomdescriptors also match. Uses short circuit inside, so the second predicate wont be called
+ * when the first one failed.
+ */
 AtomDescriptor operator&&(const AtomDescriptor &lhs, const AtomDescriptor &rhs);
+
+/**
+ * Set Union for two AtomDescriptors. The resulting AtomDescriptor will match an Atom if at least one of
+ * the two given AtomDescriptors does match. Used short circuit inside, so the second predicate wont
+ * be called when the first one failed.
+ */
 AtomDescriptor operator||(const AtomDescriptor &lhs, const AtomDescriptor &rhs);
+
+/**
+ * Set inversion for an AtomDescriptor. Matches an Atom if the given AtomDescriptor did not match.
+ */
 AtomDescriptor operator!(const AtomDescriptor &arg);
 
Index: src/Descriptors/AtomDescriptor_impl.hpp
===================================================================
--- src/Descriptors/AtomDescriptor_impl.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Descriptors/AtomDescriptor_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -1,5 +1,15 @@
+#ifndef ATOMDESCRIPTOR_IMPL_HPP
+#define ATOMDESCRIPTOR_IMPL_HPP
+
 #include "Descriptors/AtomDescriptor.hpp"
 
 /************************ Declarations of implementation Objects ************************/
+
+/**
+ * This class implements a general Base class for AtomDescriptors using the PIMPL-Idiom
+ *
+ * The predicate for this class is empty and should be implemented by derived classes.
+ * By the predicate it is described which atoms should be picked for a given descriptor.
+ */
 
 class AtomDescriptor_impl
@@ -11,30 +21,71 @@
   virtual ~AtomDescriptor_impl();
 
-  virtual bool predicate(std::pair<int,atom*>)=0;
+  /**
+   * Implement this abstract Method to make a concrete AtomDescriptor pick certain Atoms
+   */
+  virtual bool predicate(std::pair<atomId_t,atom*>)=0;
 
 protected:
+
+  /**
+   * This method is called when the Descriptor is used to find the first matching
+   * Atom. Walks through all Atoms and stops on the first match. Can be implemented
+   * when the searched Atom can be found in a more efficient way. Calculated
+   * Atomdescriptors will always use this method, so no improvement there.
+   */
   virtual atom* find();
+
+  /**
+   * This method is called when the Descriptor is used to find all matching Atoms.
+   * Walks through all Atoms and tests the predicate on each one. A vector of all
+   * matching Atoms is returned.
+   */
   virtual std::vector<atom*> findAll();
-  std::map<int,atom*>& getAtoms();
+
+  /**
+   * This method is used internally to query the Set of Atoms from the world.
+   * By using this method derived classes can also access the Internal World Datastructre.
+   * Implemented in full in the Base Descriptor Implementation, so only this one method
+   * needs to be friend with the World class.
+   */
+  World::AtomSet& getAtoms();
 };
 
 /************************** Universe and Emptyset *****************/
 
+/**
+ * A simple AtomDescriptor that will always match all Atoms present in the World.
+ */
 class AtomAllDescriptor_impl : public AtomDescriptor_impl {
 public:
   AtomAllDescriptor_impl();
   virtual ~AtomAllDescriptor_impl();
-  virtual bool predicate(std::pair<int,atom*>);
+
+  /**
+   * Always returns true for any Atom
+   */
+  virtual bool predicate(std::pair<atomId_t,atom*>);
 };
 
+
+/**
+ * An AtomDescriptor that never matches any Atom in the World.
+ */
 class AtomNoneDescriptor_impl : public AtomDescriptor_impl {
 public:
   AtomNoneDescriptor_impl();
   virtual ~AtomNoneDescriptor_impl();
-  virtual bool predicate(std::pair<int,atom*>);
+
+  /**
+   * Always returns false for any Atom
+   */
+  virtual bool predicate(std::pair<atomId_t,atom*>);
 };
 
 /************************** Operator stuff ************************/
 
+/**
+ * Intersection of two AtomDescriptors
+ */
 class AtomAndDescriptor_impl : public AtomDescriptor_impl
 {
@@ -42,5 +93,10 @@
   AtomAndDescriptor_impl(AtomDescriptor::impl_ptr _lhs, AtomDescriptor::impl_ptr _rhs);
   ~AtomAndDescriptor_impl();
-  virtual bool predicate(std::pair<int,atom*>);
+
+  /**
+   * This predicate uses the predicate from the first && the predicate from the
+   * second Descriptor to decide if an Atom should be selected.
+   */
+  virtual bool predicate(std::pair<atomId_t,atom*>);
 
 private:
@@ -49,4 +105,7 @@
 };
 
+/**
+ * Union of two AtomDescriptors
+ */
 class AtomOrDescriptor_impl : public AtomDescriptor_impl
 {
@@ -54,5 +113,10 @@
   AtomOrDescriptor_impl(AtomDescriptor::impl_ptr _lhs, AtomDescriptor::impl_ptr _rhs);
   virtual ~AtomOrDescriptor_impl();
-  virtual bool predicate(std::pair<int,atom*>);
+
+  /**
+   * This predicate uses the predicate form the first || the predicate from the
+   * second Descriptor to decide if an Atom should be selected.
+   */
+  virtual bool predicate(std::pair<atomId_t,atom*>);
 
 private:
@@ -61,4 +125,7 @@
 };
 
+/**
+ * Set Inversion of a Descriptor
+ */
 class AtomNotDescriptor_impl : public AtomDescriptor_impl
 {
@@ -67,7 +134,12 @@
   virtual ~AtomNotDescriptor_impl();
 
-  virtual bool predicate(std::pair<int,atom*>);
+  /**
+   * Opposite of the given descriptor predicate.
+   */
+  virtual bool predicate(std::pair<atomId_t,atom*>);
 
 private:
   AtomDescriptor::impl_ptr arg;
 };
+
+#endif //ATOMDESCRIPTOR_IMPL_HPP
Index: src/Descriptors/AtomIdDescriptor.cpp
===================================================================
--- src/Descriptors/AtomIdDescriptor.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Descriptors/AtomIdDescriptor.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -14,5 +14,5 @@
 
 
-AtomIdDescriptor_impl::AtomIdDescriptor_impl(int _id) :
+AtomIdDescriptor_impl::AtomIdDescriptor_impl(atomId_t _id) :
   id(_id)
 {}
@@ -21,27 +21,20 @@
 {}
 
-bool AtomIdDescriptor_impl::predicate(std::pair<int,atom*> atom) {
-  return atom.second->getId()==id;
+bool AtomIdDescriptor_impl::predicate(std::pair<atomId_t,atom*> atom) {
+  return atom.first==id;
 }
 
-AtomDescriptor AtomById(int id){
+AtomDescriptor AtomById(atomId_t id){
   return AtomDescriptor(AtomDescriptor::impl_ptr(new AtomIdDescriptor_impl(id)));
 }
 
-#if 0
-
-// so far the lookuptable for Atoms-by-id does not work, since atoms don't get an ID upon creation.
-// instead of this we rely on walking through all atoms.
-
-atom *AtomIdDescriptor::find(){
-  map<int,atom*> atoms = getAtoms();
-  map<int,atom*>::iterator res = atoms.find(id);
+atom *AtomIdDescriptor_impl::find(){
+  World::AtomSet atoms = getAtoms();
+  World::AtomSet::iterator res = atoms.find(id);
   return (res!=atoms.end())?((*res).second):0;
 }
 
-vector<atom*> AtomIdDescriptor::findAll(){
+vector<atom*> AtomIdDescriptor_impl::findAll(){
   atom *res = find();
   return (res)?(vector<atom*>(1,res)):(vector<atom*>());
 }
-
-#endif
Index: src/Descriptors/AtomIdDescriptor.hpp
===================================================================
--- src/Descriptors/AtomIdDescriptor.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Descriptors/AtomIdDescriptor.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,7 +9,8 @@
 #define ATOMIDDESCRIPTOR_HPP_
 
+#include "defs.hpp"
 #include "Descriptors/AtomDescriptor.hpp"
 
-AtomDescriptor AtomById(int id);
+AtomDescriptor AtomById(atomId_t id);
 
 #endif /* ATOMIDDESCRIPTOR_HPP_ */
Index: src/Descriptors/AtomIdDescriptor_impl.hpp
===================================================================
--- src/Descriptors/AtomIdDescriptor_impl.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Descriptors/AtomIdDescriptor_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -1,3 +1,5 @@
-#include "Descriptors/AtomIdDescriptor.hpp"
+#ifndef ATOMIDDESCRIPTOR_IMPL_HPP
+#define ATOMIDDESCRIPTOR_IMPL_HPP
+
 #include "Descriptors/AtomDescriptor_impl.hpp"
 
@@ -5,15 +7,15 @@
 {
 public:
-  AtomIdDescriptor_impl(int _id);
+  AtomIdDescriptor_impl(atomId_t _id);
   virtual ~AtomIdDescriptor_impl();
 
-  bool predicate(std::pair<int,atom*> atom);
+  bool predicate(std::pair<atomId_t,atom*> atom);
 
 protected:
-#if 0
-  atom *find();
-  std::vector<atom*> findAll();
-#endif
+  virtual atom *find();
+  virtual std::vector<atom*> findAll();
 private:
-  int id;
+  atomId_t id;
 };
+
+#endif //ATOMIDDESCRIPTOR_IMPL_HPP
Index: src/Descriptors/AtomTypeDescriptor.cpp
===================================================================
--- src/Descriptors/AtomTypeDescriptor.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/AtomTypeDescriptor.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,33 @@
+/*
+ * AtomTypeDescriptor_impl.cpp
+ *
+ *  Created on: Feb 25, 2010
+ *      Author: crueger
+ */
+
+#include "Descriptors/AtomTypeDescriptor.hpp"
+#include "Descriptors/AtomTypeDescriptor_impl.hpp"
+
+#include "atom.hpp"
+#include "World.hpp"
+#include "periodentafel.hpp"
+
+AtomTypeDescriptor_impl::AtomTypeDescriptor_impl(const element* _type) :
+  type(_type)
+{}
+
+AtomTypeDescriptor_impl::~AtomTypeDescriptor_impl()
+{}
+
+bool AtomTypeDescriptor_impl::predicate(std::pair<atomId_t,atom*> atom) {
+  return (atom.second->getType()==type);
+}
+
+AtomDescriptor AtomByType(const element *elem){
+  return AtomDescriptor(AtomDescriptor::impl_ptr(new AtomTypeDescriptor_impl(elem)));
+}
+
+AtomDescriptor AtomByType(int Z){
+  const element * elem = World::getInstance().getPeriode()->FindElement(Z);
+  return AtomByType(elem);
+}
Index: src/Descriptors/AtomTypeDescriptor.hpp
===================================================================
--- src/Descriptors/AtomTypeDescriptor.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/AtomTypeDescriptor.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,18 @@
+/*
+ * AtomTypeDescriptor.h
+ *
+ *  Created on: Feb 25, 2010
+ *      Author: crueger
+ */
+
+#ifndef ATOMTYPEDESCRIPTOR_HPP
+#define ATOMTYPEDESCRIPTOR_HPP
+
+#include "Descriptors/AtomDescriptor.hpp"
+
+class element;
+
+AtomDescriptor AtomByType(const element *);
+AtomDescriptor AtomByType(int);
+
+#endif /* ATOMTYPEDESCRIPTOR_HPP */
Index: src/Descriptors/AtomTypeDescriptor_impl.hpp
===================================================================
--- src/Descriptors/AtomTypeDescriptor_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/AtomTypeDescriptor_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,24 @@
+/*
+ * AtomTypeDescriptor_impl.hpp
+ *
+ *  Created on: Feb 25, 2010
+ *      Author: crueger
+ */
+
+#ifndef ATOMTYPEDESCRIPTOR_IMPL_HPP_
+#define ATOMTYPEDESCRIPTOR_IMPL_HPP_
+
+#include "Descriptors/AtomDescriptor_impl.hpp"
+
+class AtomTypeDescriptor_impl : public AtomDescriptor_impl
+{
+public:
+  AtomTypeDescriptor_impl(const element* _type);
+  virtual ~AtomTypeDescriptor_impl();
+
+  bool predicate(std::pair<atomId_t,atom*> atom);
+private:
+  const element * const type;
+};
+
+#endif /* ATOMTYPEDESCRIPTOR_IMPL_HPP_ */
Index: src/Descriptors/DescriptorBase.hpp
===================================================================
--- src/Descriptors/DescriptorBase.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/DescriptorBase.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,101 @@
+/*
+ * DescriptorBase.hpp
+ *
+ *  Created on: Mar 12, 2010
+ *      Author: crueger
+ */
+
+#ifndef DESCRIPTORBASE_HPP_
+#define DESCRIPTORBASE_HPP_
+
+#include <vector>
+#include <boost/shared_ptr.hpp>
+
+/***
+ * Code in this file is not used.
+ *
+ * I was not able to figure out how to factor out the common code for
+ * descriptors and have given up :-( . If somebody else wants to have
+ * another shot just go ahead, but expect a hard ride from here on.
+ */
+
+template<class _Target,
+         class _Container>
+class DescriptorBase_impl;
+
+
+template<class _Target,
+         class _Container>
+class SelectiveIterator;
+
+template<class _Target,
+         class _Container>
+class DescriptorBase
+{
+  friend class DescriptorBase_impl<_Target,_Container>;
+  friend class SelectiveIterator<_Target,_Container>;
+
+
+  // expose the type of this descriptor to the public
+public:
+  typedef _Target     Target;
+  typedef std::vector<Target> TargetVec;
+
+protected:
+  typedef _Container  Container;
+  typedef typename Container::iterator iterator;
+
+  typedef DescriptorBase_impl<Target,Container>  impl;
+  typedef boost::shared_ptr<impl> impl_ptr;
+
+
+public:
+
+  DescriptorBase();
+  DescriptorBase(const DescriptorBase&);
+  DescriptorBase(impl_ptr);
+  virtual ~DescriptorBase();
+
+  DescriptorBase& operator=(const DescriptorBase&);
+
+  /**
+   * forward Method to implementation
+   */
+  Target find(Container&);
+
+  /**
+   * forward Method to implementation
+   */
+  TargetVec findAll(Container&);
+
+
+private:
+  impl_ptr theImpl;
+};
+
+template<class _Target,
+         class _Container>
+DescriptorBase<_Target,_Container> AllX();
+
+template<class _Target,
+         class _Container>
+DescriptorBase<_Target,_Container> NoX();
+
+template<class _Target,
+         class _Container>
+DescriptorBase<_Target,_Container>
+  operator&&(DescriptorBase<_Target,_Container>&,
+             DescriptorBase<_Target,_Container>&);
+
+template<class _Target,
+         class _Container>
+DescriptorBase<_Target,_Container>
+  operator||(DescriptorBase<_Target,_Container>&,
+             DescriptorBase<_Target,_Container>&);
+
+template<class _Target,
+         class _Container>
+DescriptorBase<_Target,_Container>
+  operator!(DescriptorBase<_Target,_Container>&);
+
+#endif /* DESCRIPTORBASE_HPP_ */
Index: src/Descriptors/DescriptorBase_impl.hpp
===================================================================
--- src/Descriptors/DescriptorBase_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/DescriptorBase_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,68 @@
+/*
+ * DescriptorBase_impl.hpp
+ *
+ *  Created on: Mar 12, 2010
+ *      Author: crueger
+ */
+
+#ifndef DESCRIPTORBASE_IMPL_HPP_
+#define DESCRIPTORBASE_IMPL_HPP_
+
+#include "Descriptors/DescriptorBase.hpp"
+#include <utility>
+#include <boost/bind.hpp>
+
+template<class _Target,
+         class _Container>
+class DescriptorBase_impl{
+public:
+  typedef _Target Target;
+  typedef std::vector<Target> TargetVec;
+  typedef _Container Container;
+  typedef typename Container::value_type value_type;
+  typedef typename Container::iterator iterator;
+
+  DescriptorBase_impl();
+  ~DescriptorBase_impl();
+
+  virtual bool predicate(value_type)=0;
+
+  virtual Target    find(Container&);
+  virtual TargetVec findAll(Container&);
+protected:
+  const _take<Target,value_type> take;
+};
+
+template<class _Target,
+         class _Container>
+DescriptorBase_impl<_Target,_Container>::DescriptorBase_impl(){}
+
+template<class _Target,
+         class _Container>
+DescriptorBase_impl<_Target,_Container>::~DescriptorBase_impl(){}
+
+template<class _Target,
+         class _Container>
+typename DescriptorBase_impl<_Target,_Container>::Target
+  DescriptorBase_impl<_Target,_Container>::find(DescriptorBase_impl<_Target,_Container>::Container& container){
+    iterator res = find_if(container.begin(),
+                           container.end(),
+                           boost::bind(&DescriptorBase_impl<_Target,_Container>::predicate,this,_1));
+    return (res!=container.end())?(take(*res)):0;
+  }
+
+template<class _Target,
+         class _Container>
+typename DescriptorBase_impl<_Target,_Container>::TargetVec
+  DescriptorBase_impl<_Target,_Container>::findAll(DescriptorBase_impl<_Target,_Container>::Container& container) {
+  TargetVec res;
+  iterator iter;
+  for(iter=container.begin();iter!=container.end();++iter) {
+    if(predicate(*iter)){
+      res.push_back(take(*iter));
+    }
+  }
+  return res;
+}
+
+#endif /* DESCRIPTORBASE_IMPL_HPP_ */
Index: src/Descriptors/MoleculeDescriptor.cpp
===================================================================
--- src/Descriptors/MoleculeDescriptor.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/MoleculeDescriptor.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,174 @@
+/*
+ * MoleculeDescriptor.cpp
+ *
+ *  Created on: Feb 5, 2010
+ *      Author: crueger
+ */
+
+#include "Descriptors/MoleculeDescriptor.hpp"
+#include "Descriptors/MoleculeDescriptor_impl.hpp"
+
+#include "World.hpp"
+
+#include "molecule.hpp"
+
+#include <boost/bind.hpp>
+#include <cassert>
+#include <iostream>
+
+using namespace std;
+
+typedef World::MoleculeSet::iterator molecules_iter_t;
+
+/************************ Forwarding object **************************************/
+
+
+MoleculeDescriptor::MoleculeDescriptor(impl_ptr _impl) :
+    impl(_impl)
+{}
+
+MoleculeDescriptor::MoleculeDescriptor(const MoleculeDescriptor& src) :
+    impl(src.get_impl())
+{}
+
+MoleculeDescriptor::~MoleculeDescriptor()
+{}
+
+MoleculeDescriptor& MoleculeDescriptor::operator=(MoleculeDescriptor &src){
+  if(&src!=this) {
+    impl=src.get_impl();
+  }
+  return *this;
+}
+
+molecule* MoleculeDescriptor::find(){
+  return impl->find();
+}
+
+std::vector<molecule*> MoleculeDescriptor::findAll(){
+  return impl->findAll();
+}
+
+MoleculeDescriptor::impl_ptr MoleculeDescriptor::get_impl() const{
+  return impl;
+}
+
+
+
+
+/**************************** implementation ********************/
+
+MoleculeDescriptor_impl::MoleculeDescriptor_impl()
+{
+}
+
+MoleculeDescriptor_impl::~MoleculeDescriptor_impl()
+{
+}
+
+World::MoleculeSet& MoleculeDescriptor_impl::getMolecules(){
+  return World::getInstance().molecules;
+}
+
+molecule* MoleculeDescriptor_impl::find() {
+  World::MoleculeSet molecules = getMolecules();
+  molecules_iter_t res = find_if(molecules.begin(),molecules.end(),boost::bind(&MoleculeDescriptor_impl::predicate,this,_1));
+  return (res!=molecules.end())?((*res).second):0;
+}
+
+vector<molecule*> MoleculeDescriptor_impl::findAll() {
+  vector<molecule*> res;
+  World::MoleculeSet molecules = getMolecules();
+  molecules_iter_t iter;
+  for(iter=molecules.begin();iter!=molecules.end();++iter) {
+    if(predicate(*iter)){
+      res.push_back((*iter).second);
+    }
+  }
+  return res;
+}
+
+/************************** Universe and Emptyset *****************/
+
+MoleculeAllDescriptor_impl::MoleculeAllDescriptor_impl()
+{}
+
+MoleculeAllDescriptor_impl::~MoleculeAllDescriptor_impl()
+{}
+
+bool MoleculeAllDescriptor_impl::predicate(std::pair<moleculeId_t,molecule*>){
+  return true;
+}
+
+MoleculeDescriptor AllMolecules(){
+  return MoleculeDescriptor(MoleculeDescriptor::impl_ptr(new MoleculeAllDescriptor_impl));
+}
+
+MoleculeNoneDescriptor_impl::MoleculeNoneDescriptor_impl()
+{}
+
+MoleculeNoneDescriptor_impl::~MoleculeNoneDescriptor_impl()
+{}
+
+bool MoleculeNoneDescriptor_impl::predicate(std::pair<moleculeId_t,molecule*>){
+  return false;
+}
+
+MoleculeDescriptor NoMolecules(){
+  return MoleculeDescriptor(MoleculeDescriptor::impl_ptr(new MoleculeNoneDescriptor_impl));
+}
+
+/************************** Operator stuff ************************/
+
+// AND
+MoleculeAndDescriptor_impl::MoleculeAndDescriptor_impl(MoleculeDescriptor::impl_ptr _lhs, MoleculeDescriptor::impl_ptr _rhs) :
+    lhs(_lhs), rhs(_rhs)
+{}
+
+MoleculeAndDescriptor_impl::~MoleculeAndDescriptor_impl()
+{}
+
+bool MoleculeAndDescriptor_impl::predicate(std::pair<moleculeId_t,molecule*> molecule){
+  return lhs->predicate(molecule) && rhs->predicate(molecule);
+}
+MoleculeDescriptor operator&&(const MoleculeDescriptor &lhs, const MoleculeDescriptor &rhs){
+  MoleculeDescriptor::impl_ptr newImpl = MoleculeDescriptor::impl_ptr(new MoleculeAndDescriptor_impl(lhs.get_impl(),rhs.get_impl()));
+  return MoleculeDescriptor(newImpl);
+}
+
+// OR
+MoleculeOrDescriptor_impl::MoleculeOrDescriptor_impl(MoleculeDescriptor::impl_ptr _lhs ,MoleculeDescriptor::impl_ptr _rhs) :
+    lhs(_lhs), rhs(_rhs)
+{}
+
+MoleculeOrDescriptor_impl::~MoleculeOrDescriptor_impl(){
+}
+
+bool MoleculeOrDescriptor_impl::predicate(std::pair<moleculeId_t,molecule*> molecule){
+  return lhs->predicate(molecule) || rhs->predicate(molecule);
+}
+
+MoleculeDescriptor  operator||(const MoleculeDescriptor &lhs, const MoleculeDescriptor &rhs){
+  MoleculeDescriptor::impl_ptr newImpl = MoleculeDescriptor::impl_ptr(new MoleculeOrDescriptor_impl(lhs.get_impl(),rhs.get_impl()));
+  return MoleculeDescriptor(newImpl);
+}
+
+// NOT
+
+MoleculeNotDescriptor_impl::MoleculeNotDescriptor_impl(MoleculeDescriptor::impl_ptr _arg) :
+    arg(_arg)
+{}
+
+
+MoleculeNotDescriptor_impl::~MoleculeNotDescriptor_impl()
+{
+}
+
+bool MoleculeNotDescriptor_impl::predicate(std::pair<moleculeId_t,molecule*> molecule){
+ return !(arg->predicate(molecule));
+}
+
+MoleculeDescriptor operator!(const MoleculeDescriptor &arg){
+  MoleculeDescriptor::impl_ptr newImpl = MoleculeDescriptor::impl_ptr(new MoleculeNotDescriptor_impl(arg.get_impl()));
+  return MoleculeDescriptor(newImpl);
+}
Index: src/Descriptors/MoleculeDescriptor.hpp
===================================================================
--- src/Descriptors/MoleculeDescriptor.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/MoleculeDescriptor.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,115 @@
+/*
+ * MoleculeDescriptor.hpp
+ *
+ *  Created on: Feb 5, 2010
+ *      Author: crueger
+ */
+
+#ifndef MOLECULEDESCRIPTOR_HPP_
+#define MOLECULEDESCRIPTOR_HPP_
+
+
+#include <vector>
+#include <map>
+#include <boost/shared_ptr.hpp>
+#include "World.hpp"
+
+class World;
+class molecule;
+
+// internal implementation, allows assignment, copying etc
+class MoleculeDescriptor_impl;
+
+/**
+ * An MoleculeDescriptor describes a Set of Molecules from the World. Can be used for any method that needs to work on
+ * a specific set of Molecules.
+ *
+ * This Class is implemented using the PIMPL-Idion, i.e. this class only contains an abstract structure
+ * that forwards any request to a wrapped pointer-to-implementation. This way operators and calculations
+ * on Descriptors are possible.
+ *
+ * Concrete Implementation Objects can be shared between multiple Wrappers, so make sure that
+ * any Implementation remainst constant during lifetime.
+ */
+class MoleculeDescriptor {
+  // close coupling to the world to allow access
+  friend molecule* World::getMolecule(MoleculeDescriptor descriptor);
+  friend std::vector<molecule*> World::getAllMolecules(MoleculeDescriptor descriptor);
+  template <class,class,class> friend class SelectiveIterator;
+
+  friend MoleculeDescriptor operator&&(const MoleculeDescriptor &lhs, const MoleculeDescriptor &rhs);
+  friend MoleculeDescriptor operator||(const MoleculeDescriptor &lhs, const MoleculeDescriptor &rhs);
+  friend MoleculeDescriptor operator!(const MoleculeDescriptor &arg);
+
+public:
+  typedef MoleculeDescriptor_impl impl_t;
+  typedef boost::shared_ptr<impl_t> impl_ptr; //!< Allow easy changes of the pointer-to-implementation type
+
+  MoleculeDescriptor(impl_ptr);
+
+  /**
+   * Copy constructor.
+   * Takes the Implementation from the copied object and sets it's own pointer to link there.
+   * This way the actuall implementation object is shared between copy and original
+   */
+  MoleculeDescriptor(const MoleculeDescriptor&);
+  ~MoleculeDescriptor();
+
+  /**
+   * Assignment Operator.
+   *
+   * Implemented by setting the pointer to the new Implementation.
+   */
+  MoleculeDescriptor &operator=(MoleculeDescriptor &);
+
+protected:
+  /**
+   * forward Method to implementation
+   */
+  molecule* find();
+
+  /**
+   * forward Method to implementation
+   */
+  std::vector<molecule*> findAll();
+
+  /**
+   * Return the implementation this Wrapper currently points to.
+   * Used for copying, assignment and in Iterators over subsets of the World.
+   */
+  impl_ptr get_impl() const;
+
+private:
+  impl_ptr impl;
+};
+
+/**
+ * produce an Moleculedescriptor that at the point of construction contains an implementation that matches all Molecules
+ */
+MoleculeDescriptor AllMolecules();
+
+/**
+ * produce an Moleculedescriptor that at the point of construction contains an implementation that matches no Molecules
+ */
+MoleculeDescriptor NoMolecules();
+
+/**
+ * Set Intersection for two Moleculedescriptors. The resulting Moleculedescriptor will only match an Molecule if both
+ * given Moleculedescriptors also match. Uses short circuit inside, so the second predicate wont be called
+ * when the first one failed.
+ */
+MoleculeDescriptor operator&&(const MoleculeDescriptor &lhs, const MoleculeDescriptor &rhs);
+
+/**
+ * Set Union for two MoleculeDescriptors. The resulting MoleculeDescriptor will match an Molecule if at least one of
+ * the two given MoleculeDescriptors does match. Used short circuit inside, so the second predicate wont
+ * be called when the first one failed.
+ */
+MoleculeDescriptor operator||(const MoleculeDescriptor &lhs, const MoleculeDescriptor &rhs);
+
+/**
+ * Set inversion for an MoleculeDescriptor. Matches an Molecule if the given MoleculeDescriptor did not match.
+ */
+MoleculeDescriptor operator!(const MoleculeDescriptor &arg);
+
+#endif /* MOLECULEDESCRIPTOR_HPP_ */
Index: src/Descriptors/MoleculeDescriptor_impl.hpp
===================================================================
--- src/Descriptors/MoleculeDescriptor_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/MoleculeDescriptor_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,145 @@
+#ifndef MOLECULEDESCRIPTOR_IMPL_HPP
+#define MOLECULEDESCRIPTOR_IMPL_HPP
+
+#include "Descriptors/MoleculeDescriptor.hpp"
+
+/************************ Declarations of implementation Objects ************************/
+
+/**
+ * This class implements a general Base class for MoleculeDescriptors using the PIMPL-Idiom
+ *
+ * The predicate for this class is empty and should be implemented by derived classes.
+ * By the predicate it is described which molecules should be picked for a given descriptor.
+ */
+
+class MoleculeDescriptor_impl
+{
+  friend class MoleculeDescriptor;
+public:
+
+  MoleculeDescriptor_impl();
+  virtual ~MoleculeDescriptor_impl();
+
+  /**
+   * Implement this abstract Method to make a concrete MoleculeDescriptor pick certain Molecules
+   */
+  virtual bool predicate(std::pair<moleculeId_t,molecule*>)=0;
+
+protected:
+
+  /**
+   * This method is called when the Descriptor is used to find the first matching
+   * Molecule. Walks through all Molecules and stops on the first match. Can be implemented
+   * when the searched Molecule can be found in a more efficient way. Calculated
+   * Moleculedescriptors will always use this method, so no improvement there.
+   */
+  virtual molecule* find();
+
+  /**
+   * This method is called when the Descriptor is used to find all matching Molecules.
+   * Walks through all Molecules and tests the predicate on each one. A vector of all
+   * matching Molecules is returned.
+   */
+  virtual std::vector<molecule*> findAll();
+
+  /**
+   * This method is used internally to query the Set of Molecules from the world.
+   * By using this method derived classes can also access the Internal World Datastructre.
+   * Implemented in full in the Base Descriptor Implementation, so only this one method
+   * needs to be friend with the World class.
+   */
+  World::MoleculeSet& getMolecules();
+};
+
+/************************** Universe and Emptyset *****************/
+
+/**
+ * A simple MoleculeDescriptor that will always match all Molecules present in the World.
+ */
+class MoleculeAllDescriptor_impl : public MoleculeDescriptor_impl {
+public:
+  MoleculeAllDescriptor_impl();
+  virtual ~MoleculeAllDescriptor_impl();
+
+  /**
+   * Always returns true for any Molecule
+   */
+  virtual bool predicate(std::pair<moleculeId_t,molecule*>);
+};
+
+
+/**
+ * An MoleculeDescriptor that never matches any Molecule in the World.
+ */
+class MoleculeNoneDescriptor_impl : public MoleculeDescriptor_impl {
+public:
+  MoleculeNoneDescriptor_impl();
+  virtual ~MoleculeNoneDescriptor_impl();
+
+  /**
+   * Always returns false for any Molecule
+   */
+  virtual bool predicate(std::pair<moleculeId_t,molecule*>);
+};
+
+/************************** Operator stuff ************************/
+
+/**
+ * Intersection of two MoleculeDescriptors
+ */
+class MoleculeAndDescriptor_impl : public MoleculeDescriptor_impl
+{
+public:
+  MoleculeAndDescriptor_impl(MoleculeDescriptor::impl_ptr _lhs, MoleculeDescriptor::impl_ptr _rhs);
+  ~MoleculeAndDescriptor_impl();
+
+  /**
+   * This predicate uses the predicate from the first && the predicate from the
+   * second Descriptor to decide if an Molecule should be selected.
+   */
+  virtual bool predicate(std::pair<moleculeId_t,molecule*>);
+
+private:
+  MoleculeDescriptor::impl_ptr lhs;
+  MoleculeDescriptor::impl_ptr rhs;
+};
+
+/**
+ * Union of two MoleculeDescriptors
+ */
+class MoleculeOrDescriptor_impl : public MoleculeDescriptor_impl
+{
+public:
+  MoleculeOrDescriptor_impl(MoleculeDescriptor::impl_ptr _lhs, MoleculeDescriptor::impl_ptr _rhs);
+  virtual ~MoleculeOrDescriptor_impl();
+
+  /**
+   * This predicate uses the predicate form the first || the predicate from the
+   * second Descriptor to decide if an Molecule should be selected.
+   */
+  virtual bool predicate(std::pair<moleculeId_t,molecule*>);
+
+private:
+  MoleculeDescriptor::impl_ptr lhs;
+  MoleculeDescriptor::impl_ptr rhs;
+};
+
+/**
+ * Set Inversion of a Descriptor
+ */
+class MoleculeNotDescriptor_impl : public MoleculeDescriptor_impl
+{
+public:
+  MoleculeNotDescriptor_impl(MoleculeDescriptor::impl_ptr _arg);
+  virtual ~MoleculeNotDescriptor_impl();
+
+  /**
+   * Opposite of the given descriptor predicate.
+   */
+  virtual bool predicate(std::pair<moleculeId_t,molecule*>);
+
+private:
+  MoleculeDescriptor::impl_ptr arg;
+};
+
+#endif //MOLECULEDESCRIPTOR_IMPL_HPP
Index: src/Descriptors/MoleculeIdDescriptor.cpp
===================================================================
--- src/Descriptors/MoleculeIdDescriptor.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/MoleculeIdDescriptor.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,40 @@
+/*
+ * MoleculeIdDescriptor.cpp
+ *
+ *  Created on: Feb 5, 2010
+ *      Author: crueger
+ */
+
+#include "MoleculeIdDescriptor.hpp"
+#include "MoleculeIdDescriptor_impl.hpp"
+
+#include "molecule.hpp"
+
+using namespace std;
+
+
+MoleculeIdDescriptor_impl::MoleculeIdDescriptor_impl(moleculeId_t _id) :
+  id(_id)
+{}
+
+MoleculeIdDescriptor_impl::~MoleculeIdDescriptor_impl()
+{}
+
+bool MoleculeIdDescriptor_impl::predicate(std::pair<moleculeId_t,molecule*> molecule) {
+  return molecule.first==id;
+}
+
+MoleculeDescriptor MoleculeById(moleculeId_t id){
+  return MoleculeDescriptor(MoleculeDescriptor::impl_ptr(new MoleculeIdDescriptor_impl(id)));
+}
+
+molecule *MoleculeIdDescriptor_impl::find(){
+  World::MoleculeSet molecules = getMolecules();
+  World::MoleculeSet::iterator res = molecules.find(id);
+  return (res!=molecules.end())?((*res).second):0;
+}
+
+vector<molecule*> MoleculeIdDescriptor_impl::findAll(){
+  molecule *res = find();
+  return (res)?(vector<molecule*>(1,res)):(vector<molecule*>());
+}
Index: src/Descriptors/MoleculeIdDescriptor.hpp
===================================================================
--- src/Descriptors/MoleculeIdDescriptor.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/MoleculeIdDescriptor.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,16 @@
+/*
+ * MoleculeIdDescriptor.hpp
+ *
+ *  Created on: Feb 5, 2010
+ *      Author: crueger
+ */
+
+#ifndef MOLECULEIDDESCRIPTOR_HPP_
+#define MOLECULEIDDESCRIPTOR_HPP_
+
+#include "defs.hpp"
+#include "Descriptors/MoleculeDescriptor.hpp"
+
+MoleculeDescriptor MoleculeById(moleculeId_t id);
+
+#endif /* MOLECULEIDDESCRIPTOR_HPP_ */
Index: src/Descriptors/MoleculeIdDescriptor_impl.hpp
===================================================================
--- src/Descriptors/MoleculeIdDescriptor_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/MoleculeIdDescriptor_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,21 @@
+#ifndef MOLECULEIDDESCRIPTOR_IMPL_HPP
+#define MOLECULEIDDESCRIPTOR_IMPL_HPP
+
+#include "Descriptors/MoleculeDescriptor_impl.hpp"
+
+class MoleculeIdDescriptor_impl : public MoleculeDescriptor_impl
+{
+public:
+  MoleculeIdDescriptor_impl(moleculeId_t _id);
+  virtual ~MoleculeIdDescriptor_impl();
+
+  bool predicate(std::pair<moleculeId_t,molecule*> molecule);
+
+protected:
+  virtual molecule *find();
+  virtual std::vector<molecule*> findAll();
+private:
+  moleculeId_t id;
+};
+
+#endif //MOLECULEIDDESCRIPTOR_IMPL_HPP
Index: src/Descriptors/SelectiveIterator.hpp
===================================================================
--- src/Descriptors/SelectiveIterator.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/SelectiveIterator.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,52 @@
+/*
+ * SelectiveIterator.hpp
+ *
+ *  Created on: Mar 17, 2010
+ *      Author: crueger
+ */
+
+#ifndef SELECTIVEITERATOR_HPP_
+#define SELECTIVEITERATOR_HPP_
+
+#include <iterator>
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+class SelectiveIterator :
+  public std::iterator<typename std::iterator_traits<typename _Container::iterator>::difference_type,
+                       typename std::iterator_traits<typename _Container::iterator>::value_type,
+                       typename std::iterator_traits<typename _Container::iterator>::pointer,
+                       typename std::iterator_traits<typename _Container::iterator>::reference>
+{
+public:
+  typedef typename _Container::iterator     Iter;
+  typedef          _Target                  Target;
+  typedef typename Iter::value_type         value_type;
+  typedef typename Iter::difference_type    difference_type;
+  typedef typename Iter::pointer            pointer;
+  typedef typename Iter::reference          reference;
+  typedef typename Iter::iterator_category  iterator_category;
+
+
+  SelectiveIterator(_Descriptor, _Container&);
+  SelectiveIterator(_Descriptor, _Container&, Iter);
+  SelectiveIterator(const SelectiveIterator&);
+  SelectiveIterator& operator=(const SelectiveIterator&);
+  SelectiveIterator& operator++();     // prefix
+  SelectiveIterator  operator++(int);  // postfix with dummy parameter
+  bool operator==(const SelectiveIterator&);
+  bool operator!=(const SelectiveIterator&);
+  Target operator*();
+
+  int getCount();
+protected:
+  void advanceState();
+  Iter state;
+  typename _Descriptor::impl_ptr descr;
+  int index;
+
+  _Container &content;
+};
+
+#endif /* SELECTIVEITERATOR_HPP_ */
Index: src/Descriptors/SelectiveIterator_impl.hpp
===================================================================
--- src/Descriptors/SelectiveIterator_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Descriptors/SelectiveIterator_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,137 @@
+/*
+ * SelectiveIterator_impl.hpp
+ *
+ *  Created on: Mar 17, 2010
+ *      Author: crueger
+ */
+
+#ifndef SELECTIVEITERATOR_IMPL_HPP_
+#define SELECTIVEITERATOR_IMPL_HPP_
+
+#include "helpers.hpp"
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+SelectiveIterator<_Target,_Container,_Descriptor>::SelectiveIterator(_Descriptor _descr, _Container &_content) :
+    descr(_descr.get_impl()),
+    index(0),
+    content(_content)
+{
+  state = content.begin();
+  advanceState();
+}
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+SelectiveIterator<_Target,_Container,_Descriptor>::SelectiveIterator(_Descriptor _descr, _Container &_content, SelectiveIterator<_Target,_Container,_Descriptor>::Iter _state) :
+    state(_state),
+    descr(_descr.get_impl()),
+    index(0),
+    content(_content)
+{
+  advanceState();
+}
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+SelectiveIterator<_Target,_Container,_Descriptor>::SelectiveIterator(const SelectiveIterator<_Target,_Container,_Descriptor>& rhs) :
+    state(rhs.state),
+    descr(rhs.descr),
+    index(rhs.index),
+    content(rhs.content)
+  {}
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+SelectiveIterator<_Target,_Container,_Descriptor>& SelectiveIterator<_Target,_Container,_Descriptor>::operator=(const SelectiveIterator<_Target,_Container,_Descriptor>& rhs)
+{
+  if(&rhs!=this){
+    state=rhs.state;
+    descr=rhs.descr;
+    index=rhs.index;
+  }
+  return *this;
+}
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+SelectiveIterator<_Target,_Container,_Descriptor>&
+  SelectiveIterator<_Target,_Container,_Descriptor>::operator++(){
+    ++state;
+    ++index;
+    advanceState();
+    return *this;
+  }
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+SelectiveIterator<_Target,_Container,_Descriptor> SelectiveIterator<_Target,_Container,_Descriptor>::operator++(int){
+    SelectiveIterator<_Target,_Container,_Descriptor> res = SelectiveIterator<_Target,_Container,_Descriptor>(*this);
+    ++(*this);
+    return res;
+  }
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+bool
+  SelectiveIterator<_Target,_Container,_Descriptor>::operator==(const SelectiveIterator<_Target,_Container,_Descriptor>& rhs){
+    return state==rhs.state;
+  }
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+bool
+  SelectiveIterator<_Target,_Container,_Descriptor>::operator!=(const SelectiveIterator<_Target,_Container,_Descriptor>& rhs){
+    return state!=rhs.state;
+  }
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+typename SelectiveIterator<_Target,_Container,_Descriptor>::Target
+  SelectiveIterator<_Target,_Container,_Descriptor>::operator*(){
+    return _take<_Target,value_type>::get(*state);
+  }
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+void
+  SelectiveIterator<_Target,_Container,_Descriptor>::advanceState(){
+    // go forward until we have a matching atom or the end is reached
+    while((state!=content.end()) && (!descr->predicate(*state))){
+      ++state;
+      ++index;
+    }
+  }
+
+template<class _Target,
+         class _Container,
+         class _Descriptor>
+int
+  SelectiveIterator<_Target,_Container,_Descriptor>::getCount(){
+    return index;
+  }
+
+
+#define CONSTRUCT_SELECTIVE_ITERATOR(_Target,_Container,_Descriptor) \
+		template SelectiveIterator<_Target,_Container,_Descriptor>::SelectiveIterator(_Descriptor, _Container&); \
+		template SelectiveIterator<_Target,_Container,_Descriptor>::SelectiveIterator(_Descriptor, _Container&, SelectiveIterator<_Target,_Container,_Descriptor>::Iter); \
+    template SelectiveIterator<_Target,_Container,_Descriptor>::SelectiveIterator(const SelectiveIterator<_Target,_Container,_Descriptor>&); \
+    template SelectiveIterator<_Target,_Container,_Descriptor>& SelectiveIterator<_Target,_Container,_Descriptor>::operator=(const SelectiveIterator<_Target,_Container,_Descriptor>&); \
+    template SelectiveIterator<_Target,_Container,_Descriptor>& SelectiveIterator<_Target,_Container,_Descriptor>::operator++(); \
+    template SelectiveIterator<_Target,_Container,_Descriptor> SelectiveIterator<_Target,_Container,_Descriptor>::operator++(int); \
+    template bool SelectiveIterator<_Target,_Container,_Descriptor>::operator==(const SelectiveIterator<_Target,_Container,_Descriptor>&); \
+    template bool SelectiveIterator<_Target,_Container,_Descriptor>::operator!=(const SelectiveIterator<_Target,_Container,_Descriptor>&); \
+    template SelectiveIterator<_Target,_Container,_Descriptor>::Target SelectiveIterator<_Target,_Container,_Descriptor>::operator*(); \
+    template int SelectiveIterator<_Target,_Container,_Descriptor>::getCount();
+
+#endif /* SELECTIVEITERATOR_IMPL_HPP_ */
Index: src/Exceptions/CustomException.cpp
===================================================================
--- src/Exceptions/CustomException.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Exceptions/CustomException.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,25 @@
+/*
+ * CustomException.cpp
+ *
+ *  Created on: Apr 7, 2010
+ *      Author: crueger
+ */
+
+#include "CustomException.hpp"
+
+using namespace std;
+
+CustomException::CustomException(std::string _file, int _line):
+ file(_file),
+ line(_line)
+{}
+
+CustomException::~CustomException() throw ()
+{}
+
+
+ostream& operator<<(ostream &ost,CustomException &excp){
+  // we use this to let others know from where the exception was thrown
+  ost << excp.what() << "\nIn " << excp.file << ":" << excp.line;
+  return ost;
+}
Index: src/Exceptions/CustomException.hpp
===================================================================
--- src/Exceptions/CustomException.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Exceptions/CustomException.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,32 @@
+/*
+ * CustomException.hpp
+ *
+ *  Created on: Apr 7, 2010
+ *      Author: crueger
+ */
+
+#ifndef CUSTOMEXCEPTION_HPP_
+#define CUSTOMEXCEPTION_HPP_
+
+#include <exception>
+#include <iostream>
+
+/**
+ * Custom Exceptions are simply a bit more verbose versions of the
+ * std::exceptions.
+ */
+class CustomException : public std::exception
+{
+  friend std::ostream& operator<<(std::ostream &ost, CustomException &excp);
+public:
+  CustomException(std::string file, int line);
+  virtual ~CustomException() throw();
+
+private:
+  std::string file;
+  int line;
+};
+
+std::ostream& operator<<(std::ostream &ost, CustomException &excp);
+
+#endif /* CUSTOMEXCEPTION_HPP_ */
Index: src/Exceptions/LinearDependenceException.cpp
===================================================================
--- src/Exceptions/LinearDependenceException.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Exceptions/LinearDependenceException.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,22 @@
+/*
+ * LinearDependenceException.cpp
+ *
+ *  Created on: Apr 7, 2010
+ *      Author: crueger
+ */
+
+#include "LinearDependenceException.hpp"
+
+using namespace std;
+
+LinearDependenceException::LinearDependenceException(string _file, int _line) :
+  MathException(_file,_line)
+{}
+
+LinearDependenceException::~LinearDependenceException() throw ()
+{}
+
+const char* LinearDependenceException::what() const throw()
+{
+  return "Given vectors are linear dependent.";
+}
Index: src/Exceptions/LinearDependenceException.hpp
===================================================================
--- src/Exceptions/LinearDependenceException.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Exceptions/LinearDependenceException.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,22 @@
+/*
+ * LinearDependenceException.hpp
+ *
+ *  Created on: Apr 7, 2010
+ *      Author: crueger
+ */
+
+#ifndef LINEARDEPENDENCEEXCEPTION_HPP_
+#define LINEARDEPENDENCEEXCEPTION_HPP_
+
+#include "Exceptions/MathException.hpp"
+
+class LinearDependenceException : public MathException
+{
+public:
+  LinearDependenceException(std::string _file, int _line);
+  virtual ~LinearDependenceException() throw ();
+
+  virtual const char* what() const throw();
+};
+
+#endif /* LINEARDEPENDENCEEXCEPTION_HPP_ */
Index: src/Exceptions/MathException.cpp
===================================================================
--- src/Exceptions/MathException.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Exceptions/MathException.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,15 @@
+/*
+ * MathException.cpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#include "MathException.hpp"
+
+MathException::MathException(std::string file, int line) :
+  CustomException(file,line)
+{}
+
+MathException::~MathException() throw ()
+{}
Index: src/Exceptions/MathException.hpp
===================================================================
--- src/Exceptions/MathException.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Exceptions/MathException.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,20 @@
+/*
+ * MathException.hpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#ifndef MATHEXCEPTION_HPP_
+#define MATHEXCEPTION_HPP_
+
+#include "Exceptions/CustomException.hpp"
+
+class MathException : public CustomException
+{
+public:
+  MathException(std::string file, int line);
+  virtual ~MathException() throw();
+};
+
+#endif /* MATHEXCEPTION_HPP_ */
Index: src/Exceptions/ZeroVectorException.cpp
===================================================================
--- src/Exceptions/ZeroVectorException.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Exceptions/ZeroVectorException.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,20 @@
+/*
+ * ZeroVectorException.cpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#include "ZeroVectorException.hpp"
+
+ZeroVectorException::ZeroVectorException(std::string file, int line) :
+  MathException(file,line)
+{}
+
+ZeroVectorException::~ZeroVectorException() throw ()
+{}
+
+const char* ZeroVectorException::what() const throw()
+{
+  return "Given vector was a zero Vector.";
+}
Index: src/Exceptions/ZeroVectorException.hpp
===================================================================
--- src/Exceptions/ZeroVectorException.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Exceptions/ZeroVectorException.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,22 @@
+/*
+ * ZeroVectorException.hpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#ifndef ZEROVECTOREXCEPTION_HPP_
+#define ZEROVECTOREXCEPTION_HPP_
+
+#include "Exceptions/MathException.hpp"
+
+class ZeroVectorException : public MathException
+{
+public:
+  ZeroVectorException(std::string file, int line);
+  virtual ~ZeroVectorException() throw();
+
+  virtual const char* what() const throw();
+};
+
+#endif /* ZEROVECTOREXCEPTION_HPP_ */
Index: src/Helpers/Assert.cpp
===================================================================
--- src/Helpers/Assert.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Helpers/Assert.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,124 @@
+/*
+ * Assert.cpp
+ *
+ *  Created on: Mar 18, 2010
+ *      Author: crueger
+ */
+
+#include "Helpers/Assert.hpp"
+#include <iostream>
+
+using namespace std;
+
+namespace Assert{
+  AssertionFailure::AssertionFailure(std::string _condition,
+                                     std::string _file,
+                                     int _line,
+                                     std::string _message) :
+    condition(_condition),
+    file(_file),
+    line(_line),
+    message(_message)
+  {}
+
+  std::string AssertionFailure::getFile(){
+    return file;
+  }
+
+  int AssertionFailure::getLine(){
+    return line;
+  }
+
+  std::string AssertionFailure::getMessage(){
+    return message;
+  }
+
+  std::ostream& AssertionFailure::operator<<(std::ostream& out){
+    out << "Assertion \"" << condition << "\" failed in file " << file << " at line " << line << endl;
+    out << "Assertion Message: " << message << std::endl;
+    return out;
+  }
+
+  const char  ActionKeys[]  = {'\0','a','t','i'};
+  const char* ActionNames[] = {"Ask","Abort","Throw","Ignore"};
+}
+
+using namespace Assert;
+
+Action _my_assert::defaultAction = Ask;
+std::vector<Assert::hook_t> _my_assert::hooks;
+
+std::map<std::string,bool> _wrapper::ignores;
+const char* _wrapper::message_ptr = "source pointer did not point to object of desired type";
+const char* _wrapper::message_ref = "source reference did not contain object of desired type";
+
+
+
+bool _my_assert::check(const bool res,
+                       const char* condition,
+                       const char* message,
+                       const char* filename,
+                       const int line,
+                       bool& ignore)
+{
+  if(!res){
+    cout << "Assertion " << condition << " failed in file " << filename << " at line " << line << endl;
+    cout << "Assertion Message: " << message << std::endl;
+    while(true){
+      char choice;
+      if(defaultAction==Ask) {
+        cout << "Please choose: (a)bort, (t)hrow execption, (i)gnore, al(w)ays ignore" << endl;
+        cin >> choice;
+      }
+      else{
+        choice = ActionKeys[defaultAction];
+      }
+      switch(choice){
+        case 'a':
+          return true;
+          break;
+        case 't':
+          throw AssertionFailure(condition,filename,line,message);
+          break;
+        case 'w':
+          ignore = true;
+          // fallthrough
+        case 'i':
+          return false;
+          break;
+      }
+    }
+  }
+  return false;
+}
+
+void _my_assert::doHooks(){
+  for(vector<hook_t>::reverse_iterator iter = hooks.rbegin(); iter!=hooks.rend(); ++iter ){
+    (*iter)();
+  }
+}
+
+void _my_assert::addHook(hook_t hook){
+  hooks.push_back(hook);
+}
+
+void _my_assert::removeHook(Assert::hook_t hook){
+  for(vector<hook_t>::iterator iter = hooks.begin(); iter!=hooks.end();){
+    if((*iter)==hook){
+      iter = hooks.erase(iter);
+    }
+    else{
+      ++iter;
+    }
+  }
+}
+
+void _my_assert::setDefault(Assert::Action action){
+  defaultAction = action;
+}
+Assert::Action _my_assert::getDefault(){
+  return defaultAction;
+}
+std::string _my_assert::printDefault(){
+  return ActionNames[defaultAction];
+}
Index: src/Helpers/Assert.hpp
===================================================================
--- src/Helpers/Assert.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Helpers/Assert.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,380 @@
+/*
+ * Assert.hpp
+ *
+ *  Created on: Mar 18, 2010
+ *      Author: crueger
+ */
+
+#ifndef ASSERT_HPP_
+#define ASSERT_HPP_
+
+#include<sstream>
+#include<string>
+#include<iostream>
+#include<vector>
+#include<map>
+
+/**
+ * \file Helpers/Assert.hpp
+ * <H1> ASSERT Howto </H1>
+ *
+ * <H2> Introduction </H2>
+ *
+ * ASSERT() is a small macro that allows easier debugging, when it is widely used. The custom
+ * ASSERT macro defined in this file works mainly the same way as the assert() macro that
+ * is defined in the Ansi-C standard, but includes a few nice additions.
+ *
+ * <H3> What ASSERT() does </H3>
+ *
+ * ASSERT can be used to make sure that a condition that always needs to be true for the code to
+ * work correctly is holding. If you have a function that takes a value greater than 0 and a value
+ * smaller than 0 indicates a mistake you should always do it the following way: <br>
+ * @code
+ * void foo(int a) // a should be greater 0
+ * {
+ *  ASSERT(a>0,"Parameter passed to foo was smaller than 0");
+ *  ...
+ * }
+ * @endcode
+ *
+ * (Note: some people say, that assertions like these should not be used to check function parameters.
+ * This is mainly due to the reason, that a failed assertion will show up inside the function. The buggy
+ * code however is at a completely different place, i.e. at the callers side. Always put the
+ * Assertions as close to the code that produces the value as possible, when looking at function
+ * parameters however this would mean, that any code calling foo would have an ASSERT(...) before
+ * it, which makes it easy to forget the Assertion at some places. Also this makes an easy example.)
+ *
+ * If the condition inside the ASSERT does not evaluate to true the user is shown a message, including
+ * the condition that failed, the line in which the failure was observed and the message of the assertion.
+ * In the above case that would look something like this:<br>
+ * @code
+ * Assertion "a>0" failed in foo.cpp in line 3.
+ * Assertion Message: Parameter passed to foo was smaller than 0
+ * @endcode
+ *
+ * In normal conditions, i.e. when no default action is set (see below for default actions) the user
+ * is then shown a short choice menu, on how to handle the assertion. The user can choose to abort the
+ * program, throw an exception of type AssertionFailure that contains the file, line and message,
+ * ignore the assertion or even to always ignore the assertion at that point (i.e. the ASSERT() macro
+ * at this file and line is fully disabled).
+ *
+ * Both ASSERT() and assert() handle debugging in the same way, i.e. they are only used when the
+ * NDEBUG macro is not defined. If the NDEBUG macro is defined, for example using a CXXFLAG then
+ * all asserts and ASSERTs will be disabled in the compiled program. That way in a end-user version
+ * all assertions can be removed with a single switch, thus not hassling the end-user with potential
+ * bugs.
+ *
+ * <H2> Special functions of ASSERT() </H2>
+ *
+ * Compared to the standard assert() macro the custom ASSERT() contains a few special functions. As
+ * first it is possible to set a global default behavior that is used anytime an assertion fails.
+ * This default behavior can be either of Assert::Ask, Assert::Abort, Assert::Throw or Assert::ignore.
+ * The default behavior is set using the ASSERT_DO() macro. For example if you want to check in a
+ * unittest that wrong code at another point actually makes a certain assert fail you could set
+ * ASSERT_DO(Assert::Throw) to make sure a exception is thrown and catch that exception using
+ * the CPPUNIT_ASSERT_THROW() macro. The current set default behavior can be queried as a string
+ * using the ASSERT_DEFAULT macro.
+ *
+ * As a second enhancement it is possible to install callback functions as hooks that will be executed
+ * when an assertion aborts the program. These callback functions could for example be used to flush
+ * any open streams, thus making sure files on the disk are not corrupted by a unexpected abortion.
+ * It would also be possible to install functions that produce some kind of "coredump" of important
+ * internal data-structures, thus giving the person looking for the bug some valuable information.
+ * These assertion hooks should however not be used to clean up the reserved memory of the program,
+ * because a) this memory is under normal circumstances reclaimed by the OS anyway, once the program
+ * has aborted and b) the memory might still contain some hints that could be useful when running
+ * the program inside a debugger and which could be destroyed by the clean-up. To use the hooking
+ * mechanism you can simply use the ASSERT_HOOK() macro, passing this macro any kind of void function.
+ * For example:<br/>
+ * @code
+ * void foo(){
+ *   // produce a coredump
+ *   ...
+ *   // close and flush all open handles
+ *   ...
+ * }
+ *
+ * int main(int argc, char **argv){
+ *   ASSERT_HOOK(foo);
+ *   ...
+ *   return 0;
+ * }
+ * @endcode
+ *
+ * All hooks will be executed in the reverse order of hooking, i.e. the function hooked last will be
+ * executed first when the abortion is handled. It is also possible to remove a hook to any function
+ * using the ASSERT_UNHOOK() macro and passing it the pointer to the function one wants to remove.
+ *
+ * Assertion hooks will only be executed when the program is terminated by an assertion using the
+ * abort mechanism. They will not be executed when the program exits in any other way. They also
+ * wont be executed when the assertion is ignored or an exception is thrown (even when the exception
+ * is not caught and thus terminates the program).
+ *
+ * <H2> Rules for using ASSERT() </H2>
+ *
+ * The rules for using ASSERT() are basically the same ones that can be used as guidlines for the
+ * standard assert() macro. So if you think you know those guidelines you can skip the following.
+ *
+ * <ul>
+ * <li> ASSERT() should be used only for problems that indicate a bug, i.e. problems that can be
+ * improved by rewriting parts of the program. ASSERT() should not be used to query problems that
+ * can go wrong during the normal execution of the program. For example ASSERT() should not be
+ * used to test whether a file could be opened, or memory could be reserved, as a failure of either
+ * of those tasks can not be improved upon by rewriting the code.
+ * <li> The condition in the ASSERT() macro should never contain any side-effects. Only call methods,
+ * when you are absolutely certain that these methods wont have any side-effects. Calling ASSERT()
+ * should in no way change the state of the program, because once the end-user version is produced
+ * using the NDEBUG flag all assertions are removed and so are the conditions. If the condition did
+ * cause a state transition, this state transition would be removed and the behavior of the end-user
+ * and the debug version might differ. Things you should watch out for are for example<br/>
+ * @code
+ * ASSERT(++i,"i was zero after incrementing");
+ * @endcode
+ * instead always do
+ * @code
+ * ++i;
+ * ASSERT(i,"i was zero after incrementing");
+ * @endcode
+ * <li> Give descriptive error messages. This one is a bit obvious but easy to do wrong, so I included
+ * it here. An
+ * @code
+ * ASSERT(ptr,"Pointer was zero");
+ * @endcode
+ * wont help anyone. If you do <br/>
+ * @code
+ * ASSERT(ptr,"Second argument of function foo should have pointed to an object of type bar, but was zero.");
+ * @endcode
+ * instead, people will almost immidiately know what to look for.
+ * </ul>
+ *
+ * <H2> Differences between ASSERT() and assert() </H2>
+ *
+ * This chapter is to explain why a custom ASSERT() macro was introduced and should be used in place
+ * of the standard assert(). Here are the main differences between ASSERT() and assert().
+ *
+ * <ul>
+ * <li> ASSERT() makes it easy to add a more verbose message about the nature of the failure. For
+ * assert() it has become customary to add messages using constructs like
+ * @code
+ * assert(c>0 && "Counter should be at least 1");
+ * @endcode in order to add descriptions. However both the syntax and the final output for this are
+ * a bit awkward. The custom ASSERT() handles messages in a much better way, as well as making them
+ * mandatory instead of optional.
+ * <li> ASSERT() leaves the user and the programmer a choice how to handle an assertion. While the
+ * assert() macro will always abort the program, the ASSERT() macro normally gives the user a choice on
+ * what to do. For debugging it might also be interesting how a broken assumption influences the rest
+ * of the program, so the assertion can also be ignored. Also the Exception mechanism allows
+ * assertions to be part of unittests, whereas they would always fail if the assert() macro was used.
+ * <li> ASSERT() does not unwind the stack (at least when compiled using gcc). The normal assert()
+ * exits the program, which unwinds the stack and destroys any hope for recovering a stack trace.
+ * ASSERT() on the other hand aborts the program using a special trap function, that leaves the
+ * stack intact. This way, when the program is run inside a debugger the stack is still available
+ * and can be inspected. This is the main reason, why it is safe to use ASSERT() to check function
+ * parameters, whereas assert() would give problems in such cases.
+ * <li> ASSERT() allows for hooks to be installed when the program exits. As mentioned above this
+ * makes it possible to produce coredumps, make sure all files are in a usable state or other tasks
+ * that have to be performed before killing the program.
+ * </ul>
+ *
+ * <H2> Tips and tricks and FAQ </H2>
+ *
+ * <ul>
+ * <li> <H4> ASSERT() is broken. When I abort the program it says something about an
+ * "Illegal instruction"</H4>
+ * The complaints about the illegal instruction after an abortion are no need to worry. This
+ * illegal instruction is part of the trap that is used to exit the program while leaving the stack
+ * intact. This illegal instruction can be detected by the debugger, which means it will give you the
+ * usual prompt once it is encountered. The illegal instruction is guaranteed not to mess up anything,
+ * so there is no need to worry about it.
+ * <li> <H4> When compiling the program with $NON_GCC_COMPILER and then debugging it, it will
+ * unwind the stack. I need the backtrace however to find the bug </H4>
+ * The mechanism to preserve the stack is compiler specific. For now only a mechanism that is supported
+ * by gcc is implemented, because this compiler is widely used. For other compilers the program
+ * is simply exited, and the stack is destroyed. If you need a backtrace and you cannot use gcc you
+ * have to figure out a way to have your compiler produce a trap instruction in the program. You might
+ * want to use google to find out how to get your compiler to do that. For many compilers a
+ * _asm {int 3} is said to work. Also for VC++ the instruction __debugbreak() might produce a trap.
+ * Also dividing by zero is a hack that could be used as a last hope if you don't find a way to produce
+ * traps with your compiler even after a longer search. If you found a way to handle the traps you can
+ * then add the macro DEBUG_BREAK for your compiler and the stack will be preserved.
+ * <li> <H4> I have a portion of the program that should never be executed. How can I assure this
+ * using assert.</H4>
+ * This is a common task for assertions. For example you might have an exhaustive switch/case where
+ * the default value indicates that something went wrong. Simply use the following construct:
+ * @code
+ * switch(foo){
+ *   case Bar:
+ *     ...
+ *     break;
+ *   case Baz:
+ *     ...
+ *     break;
+ *   ...
+ *   default:
+ *     ASSERT(0,"This switch should always be exhaustive.\nDid somebody add values to the enum?");
+ * }
+ * @endcode
+  * </ul>
+ */
+
+#ifndef NDEBUG
+  #ifndef STRINGIFY
+    #define STRINGIFY(x) #x
+  #endif
+
+  #ifdef __GNUC__
+    // on gcc we know how to exit to the Debugger
+    #define DEBUG_BREAK __builtin_trap()
+  #else
+    #define DEBUG_BREAK exit(1)
+  #endif
+
+  #define ASSERT(condition,message) \
+    do{\
+      static bool ignore = false;\
+      if(!ignore){\
+        if(Assert::_my_assert::check((condition),STRINGIFY(condition),(message),\
+                                     __FILE__,__LINE__,ignore)){\
+          Assert::_my_assert::doHooks();\
+          DEBUG_BREAK;\
+        }\
+      } \
+    }while(0)
+
+  #define ASSERT_NOCATCH(message) \
+		catch(Assert::AssertionFailure&){throw;}\
+		catch(...){\
+		  static bool ignore = false; \
+		  if(!ignore){\
+			  if(Assert::_my_assert::check(false,"Exception caught",(message),__FILE__,__LINE__,ignore)){\
+			    Assert::_my_assert::doHooks();\
+          DEBUG_BREAK;\
+			  }\
+		  }\
+		} do{(void)(0);}while(0)
+
+  #define assert_cast Assert::_wrapper(__LINE__,__FILE__)._convert
+
+  #define ASSERT_DO(action)    do{Assert::_my_assert::setDefault(action);}while(0)
+  #define ASSERT_HOOK(hook)    do{Assert::_my_assert::addHook(hook);}while(0)
+  #define ASSERT_UNHOOK(hook)  do{Assert::_my_assert::removeHook(hook);}while(0)
+  #define ASSERT_DEFAULT       (Assert::_myAssert::printDefault())
+#else
+  // we need to do something, so this is the usual solution (e.g. assert.h)
+  #define ASSERT(condition,message) (void)(0)
+  #define ASSERT_NOCATCH(message)   catch(...) {throw;} do{(void)(0);}while(0)
+  #define assert_cast static_cast
+  #define ASSERT_DO(action)         (void)(0)
+  #define ASSERT_HOOK(hook)         (void)(0)
+  #define ASSERT_UNHOOK(hook)       (void)(0)
+  #define ASSERT_DEFAULT            std::string("Deactivated")
+#endif
+
+namespace Assert{
+
+  typedef void (*hook_t)(void);
+
+
+  enum Action {Ask,Abort,Throw,Ignore,MAX_ACTION};
+  extern const char  ActionKeys[MAX_ACTION];
+  extern const char* ActionNames[MAX_ACTION];
+
+  class AssertionFailure{
+  public:
+    AssertionFailure(std::string _condition, std::string _file, int _line, std::string _message);
+    std::string getFile();
+    int getLine();
+    std::string getMessage();
+
+    std::ostream& operator<<(std::ostream&);
+  private:
+    std::string condition;
+    std::string file;
+    int line;
+    std::string message;
+  };
+
+  //! @cond
+#ifndef NDEBUG
+    class _my_assert{
+    public:
+      static bool check(const bool res,
+                        const char* condition,
+                        const char* message,
+                        const char* filename,
+                        const int line,
+                        bool& ignore);
+      static void addHook(Assert::hook_t hook);
+      static void removeHook(Assert::hook_t hook);
+      static void doHooks();
+      static void setDefault(Assert::Action);
+      static Assert::Action getDefault();
+      static std::string printDefault();
+    private:
+      static Assert::Action defaultAction;
+      static std::vector<Assert::hook_t> hooks;
+    };
+
+
+  class _wrapper{
+  public:
+    _wrapper(int _line,const char* _file) :
+      line(_line),
+      file(_file)
+      {}
+
+    // Overloaded template for pointers
+    template<typename target,typename source>
+    target _convert(source *src){
+      std::stringstream sstr;
+      sstr << file << ":" << line;
+      bool &ignore = ignores[sstr.str()];
+
+      if(!ignore){
+        if(_my_assert::check(dynamic_cast<target>(src)==static_cast<target>(src),"type-safe typecast",
+                                       message_ptr,file,line,ignore)){
+          _my_assert::doHooks();
+          DEBUG_BREAK;
+        }
+      }
+      return static_cast<target>(src);
+    }
+
+    // Overloaded template for references
+    template<typename target, typename source>
+    target _convert(source &src){
+            std::stringstream sstr;
+      sstr << file << ":" << line;
+      bool &ignore = ignores[sstr.str()];
+
+      try{
+        target res =dynamic_cast<target>(src);
+        return res;
+      }
+      catch(...){
+        if(!ignore){
+          if(_my_assert::check(0,"type-safe typecast",message_ref,file,line,ignore)){
+            _my_assert::doHooks();
+            DEBUG_BREAK;
+          }
+        }
+      }
+      // The error was ignored. Just return whatever a static_cast would do
+      return static_cast<target>(src);
+    }
+  private:
+    int line;
+    const char *file;
+    static std::map<std::string,bool> ignores;
+    // this avoids duplication of the strings when templates are instantiated
+    static const char* message_ptr;
+    static const char* message_ref;
+  };
+#endif
+  //! @endcond
+}
+
+
+
+
+#endif /* ASSERT_HPP_ */
Index: src/Helpers/MemDebug.cpp
===================================================================
--- src/Helpers/MemDebug.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Helpers/MemDebug.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,241 @@
+/*
+ * MemDebug.cpp
+ *
+ *  Created on: Apr 28, 2010
+ *      Author: crueger
+ */
+
+#include <iostream>
+#include <cstdlib>
+#include <cstring>
+
+using namespace std;
+
+namespace Memory {
+
+  // This struct is added before each memory chunk
+  // and contains tracking information. Anything used
+  // to track memory cannot use any dynamic memory, so
+  // we have to resort to classic C-idioms here.
+  // This struct also contains pointers to the next
+  // an previous chunks to allow fast traversion of
+  // all allocated memory blocks
+  struct entry_t {
+    // we seperate the tracking info from the rest
+    // A checksum will be calculated for this part of
+    // the struct, so the information in here should
+    // not change during the lifetime of the memory
+    struct info_t {
+      enum {length = 64};
+      char file[length+1];
+      int line;
+      size_t nbytes;
+      bool isUsed;
+      void *location;
+    } info;
+    bool isIgnored;
+    char checksum;
+    entry_t *prev;
+    entry_t *next;
+  };
+
+  // start and end of the doubly-linked list
+  entry_t *begin=0;
+  entry_t *end=0;
+
+  // current amount of allocated memory
+  size_t state = 0;
+  // maximum amount of allocated memory
+  size_t max = 0;
+  // number of allocations that have been done so far
+  unsigned int allocs = 0;
+
+
+  // this sets the alignment of the returned memory block
+  // malloc guarantees an alignment at the 8 byte border,
+  // so we just do the same
+  const int alignment = 8;
+
+  // calculates a simple checksum for the info block
+  // the checksum is used to find memory corruptions
+  inline char calcChecksum(entry_t::info_t *info){
+    char *buffer = (char*)info;
+    char checksum =0;
+    for(size_t i=0;i<sizeof(entry_t::info_t);i++){
+      checksum+=buffer[i];
+    }
+    return checksum;
+  }
+
+  // gets the next alignet point which is greater than nbytes
+  // this function is only called a fixed number of times, so
+  // there is no need to optimize
+  inline size_t doAlign(size_t nbytes){
+    int nonaligned = nbytes % alignment;
+    if(nonaligned) {
+     return(nbytes - nonaligned + alignment);
+    }
+    else{
+      return nbytes;
+    }
+  }
+
+  // Output some state information
+  void getState(){
+    cout << "Maximum allocated Memory: " << max << " bytes" << endl;
+    cout << "Currently allocated Memory: " << state <<" bytes" << endl;
+    cout << allocs << " allocated chunks total" << endl;
+
+    // simple traversal of the chunk list
+    for(entry_t *pos=begin;pos;pos=pos->next){
+      cout << "\nChunk of " << pos->info.nbytes << " bytes" << " still available" << endl;
+      cout << "Chunk reserved at: " << pos->info.file << ":" << pos->info.line << endl;
+    }
+  }
+
+  // Deletes an entry from the linked list
+  void deleteEntry(entry_t *entry){
+    if(entry->isIgnored)
+      return;
+
+    if(entry->prev){
+      entry->prev->next = entry->next;
+    }
+    else{
+      // this node was the beginning of the list
+      begin = entry->next;
+    }
+
+    if(entry->next){
+      entry->next->prev = entry->prev;
+    }
+    else{
+      // this node was the end of the list
+      end = entry->prev;
+    }
+    entry->isIgnored = true;
+    Memory::state  -= entry->info.nbytes;
+  }
+
+  void _ignore(void *ptr){
+    // just deletes the node from the list, but leaves the info intact
+    static const size_t entrySpace = Memory::doAlign(sizeof(Memory::entry_t));
+    entry_t *entry = (Memory::entry_t*)((char*)ptr-entrySpace);
+    deleteEntry(entry);
+  }
+}
+
+void *operator new(size_t nbytes,const char* file, int line) throw(std::bad_alloc) {
+
+  // to avoid allocations of 0 bytes if someone screws up
+  // allocation with 0 byte size are undefined behavior, so we are
+  // free to handle it this way
+  if(!nbytes) {
+    nbytes = 1;
+  }
+
+  // get the size of the entry, including alignment
+  static const size_t entrySpace = Memory::doAlign(sizeof(Memory::entry_t));
+
+  void *res;
+  if(!(res=malloc(entrySpace + nbytes))){
+    // new must throw, when space is low
+    throw std::bad_alloc();
+  }
+
+  // we got the space, so update the global info
+  Memory::state += nbytes;
+  if(Memory::state>Memory::max){
+    Memory::max = Memory::state;
+  }
+  Memory::allocs++;
+
+  // build the entry in front of the space
+  Memory::entry_t *entry = (Memory::entry_t*) res;
+  entry->info.nbytes = nbytes;
+  entry->info.isUsed = true;
+  strncpy(entry->info.file,file,Memory::entry_t::info_t::length);
+  entry->info.file[Memory::entry_t::info_t::length] = '\0';
+  entry->info.line=line;
+  // the space starts behind the info
+  entry->info.location = (char*)res + entrySpace;
+
+  // add the entry at the end of the list
+  entry->next=0;            // the created block is last in the list
+  entry->prev=Memory::end;  // the created block is last in the list
+  if(!Memory::begin){
+    // the list was empty... start a new one
+    Memory::begin=entry;
+  }
+  else {
+    // other blocks present... we can add to the last one
+    Memory::end->next=entry;
+  }
+  Memory::end=entry;
+
+  // get the checksum...
+  entry->checksum = Memory::calcChecksum(&entry->info);
+  // this will be set to true, when the block is removed from
+  // the list for any reason
+  entry->isIgnored = false;
+
+  // ok, space is prepared... the user can have it.
+  // the rest (constructor, deleting when something is thrown etc)
+  // is handled automatically
+  return entry->info.location;
+}
+
+void *operator new(size_t nbytes) throw(std::bad_alloc) {
+  // Just forward to the other operator, when we do not know from
+  // where the allocation came
+  return operator new(nbytes,"Unknown",0);
+}
+
+void *operator new[] (size_t nbytes,const char* file, int line) throw(std::bad_alloc) {
+  // The difference between new and new[] is just for compiler bookkeeping.
+  return operator new(nbytes,file,line);
+}
+
+void *operator new[] (size_t nbytes) throw(std::bad_alloc) {
+  // Forward again
+  return operator new[] (nbytes,"Unknown",0);
+}
+
+void operator delete(void *ptr) throw() {
+  // get the size for the entry, including alignment
+  static const size_t entrySpace = Memory::doAlign(sizeof(Memory::entry_t));
+
+  // get the position for the entry from the pointer the user gave us
+  Memory::entry_t *entry = (Memory::entry_t*)((char*)ptr-entrySpace);
+
+  // let's see if the checksum is still matching
+  if(Memory::calcChecksum(&entry->info)!=entry->checksum){
+    cout << "Possible memory corruption detected!" << endl;
+    cout << "Trying to recover allocation information..." << endl;
+    cout << "Memory was allocated at " << entry->info.file << ":" << entry->info.line << endl;
+    terminate();
+  }
+
+  // this will destroy the checksum, so double deletes are caught
+  entry->info.isUsed = false;
+  Memory::deleteEntry(entry);
+
+  // delete the space reserved by malloc
+  free((char*)ptr-entrySpace);
+}
+
+// operator that is called when the constructor throws
+// do not call manually
+void operator delete(void *ptr,const char*, int) throw() {
+  operator delete(ptr);
+}
+
+void operator delete[](void *ptr){
+  // again difference between delete and delete[] is just in compiler bookkeeping
+  operator delete(ptr);
+}
+
+// and another operator that can be called when a constructor throws
+void operator delete[](void *ptr,const char*, int) throw(){
+  operator delete(ptr);
+}
Index: src/Helpers/MemDebug.hpp
===================================================================
--- src/Helpers/MemDebug.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Helpers/MemDebug.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,58 @@
+/*
+ * MemDebug.hpp
+ *
+ *  Created on: Apr 28, 2010
+ *      Author: crueger
+ */
+
+#ifndef MEMDEBUG_HPP_
+#define MEMDEBUG_HPP_
+
+/**
+ * @file
+ * This module allows easy automatic memory tracking. Link this module to replace the
+ * operators new, new[], delete and delete[] with custom versions that add tracking
+ * information to allocated blocks.
+ *
+ * All tracking is done in O(1) for new and delete operators. Summaries for the
+ * used memory take O(N), where N is the number of currently allocated memory chunks.
+ *
+ * To use full tracking including file name and line number include this file in
+ * your sourcefiles.
+ */
+
+namespace Memory {
+
+  /**
+   * Displays a short summary of the memory state.
+   */
+  void getState();
+
+  void _ignore(void*);
+
+  /**
+   * Use this to disable memory for a certain pointer on the heap.
+   * This is useful for pointers which should live over the run of the
+   * program, and which are deleted automatically at the end. Usually these
+   * pointers should be wrapped inside some kind of smart pointer to
+   * ensure destruction at the end.
+   */
+  template <typename T>
+  T *ignore(T* ptr){
+    _ignore((void*)ptr);
+    return ptr;
+  }
+}
+
+void *operator new   (size_t nbytes,const char* file, int line) throw(std::bad_alloc);
+void *operator new[] (size_t nbytes,const char* file, int line) throw(std::bad_alloc);
+void operator delete   (void *ptr,const char*, int) throw();
+void operator delete[] (void *ptr,const char*, int) throw();
+
+/**
+ * This macro replaces all occurences of the keyword new with a replaced
+ * version that allows tracking.
+ */
+#define new new(__FILE__,__LINE__)
+
+#endif /* MEMDEBUG_HPP_ */
Index: src/Helpers/fast_functions.hpp
===================================================================
--- src/Helpers/fast_functions.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Helpers/fast_functions.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,82 @@
+/*
+ * fast_functions.hpp
+ *
+ *  Created on: Apr 1, 2010
+ *      Author: crueger
+ */
+
+#ifndef FAST_FUNCTIONS_HPP_
+#define FAST_FUNCTIONS_HPP_
+
+#include "defs.hpp"
+
+/**
+ * !@file
+ * This file contains several functions that need to be very fast and which are inlined for this
+ * reason.
+ *
+ * Warning: do not forget inline keyword for functions in this file to avoid multiple definitions!
+ */
+
+/********************************* Functions ************************************************/
+
+/** hard-coded determinant of a 3x3 matrix.
+ * \param a[9] matrix
+ * \return \f$det(a)\f$
+ */
+inline double RDET3(const double a[NDIM*NDIM])
+{
+  return ((a)[0]*(a)[4]*(a)[8] + (a)[3]*(a)[7]*(a)[2] + (a)[6]*(a)[1]*(a)[5] - (a)[2]*(a)[4]*(a)[6] - (a)[5]*(a)[7]*(a)[0] - (a)[8]*(a)[1]*(a)[3]);
+};
+
+/** hard-coded determinant of a 2x2 matrix.
+ * \param a[4] matrix
+ * \return \f$det(a)\f$
+ */
+inline double RDET2(const double a[4])
+{
+  return ((a[0])*(a[3])-(a[1])*(a[2]));
+};
+
+/** hard-coded determinant of a 2x2 matrix.
+ * \param a0 (0,0) entry of matrix
+ * \param a1 (0,1) entry of matrix
+ * \param a2 (1,0) entry of matrix
+ * \param a3 (1,1) entry of matrix
+ * \return \f$det(a)\f$
+ */
+inline double RDET2(const double a0, const double a1, const double a2, const double a3)
+{
+  return ((a0)*(a3)-(a1)*(a2));
+};
+
+/** Returns the power of \a n with respect to \a base.
+ * \param base basis
+ * \param n power
+ * \return \f$base^n\f$
+ */
+inline int pot(int base, int n)
+{
+  int res = 1;
+  int j;
+  for (j=n;j--;)
+    res *= base;
+  return res;
+};
+
+/*************************** Templatized functions ************************************/
+
+/** Flips two values.
+ * \param x first value
+ * \param y second value
+ */
+template <typename T>
+inline void flip(T &x, T &y)
+{
+  T tmp;
+  tmp = x;
+  x = y;
+  y = tmp;
+};
+
+#endif /* FAST_FUNCTIONS_HPP_ */
Index: src/Legacy/oldmenu.cpp
===================================================================
--- src/Legacy/oldmenu.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Legacy/oldmenu.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,4 +9,5 @@
 #include "Legacy/oldmenu.hpp"
 #include "analysis_correlation.hpp"
+#include "World.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
@@ -23,4 +24,6 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
+#include "vector_ops.hpp"
+#include "Plane.hpp"
 
 #include "UIElements/UIFactory.hpp"
@@ -58,4 +61,5 @@
   char choice;  // menu choice char
   bool valid;
+  bool aborted;
 
   Log() << Verbose(0) << "===========ADD ATOM============================" << endl;
@@ -76,45 +80,62 @@
       break;
       case 'a': // absolute coordinates of atom
-        Log() << Verbose(0) << "Enter absolute coordinates." << endl;
-        first = new atom;
-        first->x.AskPosition(mol->cell_size, false);
-        first->type = periode->AskElement();  // give type
-        mol->AddAtom(first);  // add to molecule
+      {
+        Dialog *dialog = UIFactory::getInstance().makeDialog();
+        first = World::getInstance().createAtom();
+        dialog->queryVector("Please enter coordinates: ",&first->x,World::getInstance().getDomain(), false);
+        dialog->queryElement("Please choose element: ",&first->type);
+        if(dialog->display()){
+          mol->AddAtom(first);  // add to molecule
+        }
+        else{
+          World::getInstance().destroyAtom(first);
+        }
+      }
+      break;
+
+      case 'b': // relative coordinates of atom wrt to reference point
+        first = World::getInstance().createAtom();
+        valid = true;
+        aborted = false;
+        do {
+          if (!valid) eLog() << Verbose(2) << "Resulting position out of cell." << endl;
+          auto_ptr<Dialog> dialog(UIFactory::getInstance().makeDialog());
+          dialog->queryVector("Enter reference coordinates.",&x,World::getInstance().getDomain(), true);
+          dialog->queryVector("Enter relative coordinates.",&first->x,World::getInstance().getDomain(), false);
+          if((aborted = !dialog->display())){
+            continue;
+          }
+          first->x += x;
+        } while (!aborted && !(valid = mol->CheckBounds((const Vector *)&first->x)));
+        if(!aborted){
+          first->type = periode->AskElement();  // give type
+          mol->AddAtom(first);  // add to molecule
+        }
+        else{
+          World::getInstance().destroyAtom(first);
+        }
         break;
 
-      case 'b': // relative coordinates of atom wrt to reference point
-        first = new atom;
+      case 'c': // relative coordinates of atom wrt to already placed atom
+      {
+        first = World::getInstance().createAtom();
         valid = true;
         do {
           if (!valid) eLog() << Verbose(2) << "Resulting position out of cell." << endl;
-          Log() << Verbose(0) << "Enter reference coordinates." << endl;
-          x.AskPosition(mol->cell_size, true);
-          Log() << Verbose(0) << "Enter relative coordinates." << endl;
-          first->x.AskPosition(mol->cell_size, false);
-          first->x.AddVector((const Vector *)&x);
-          Log() << Verbose(0) << "\n";
-        } while (!(valid = mol->CheckBounds((const Vector *)&first->x)));
-        first->type = periode->AskElement();  // give type
-        mol->AddAtom(first);  // add to molecule
-        break;
-
-      case 'c': // relative coordinates of atom wrt to already placed atom
-        first = new atom;
-        valid = true;
-        do {
-          if (!valid) eLog() << Verbose(2) << "Resulting position out of cell." << endl;
+          auto_ptr<Dialog> dialog(UIFactory::getInstance().makeDialog());
           second = mol->AskAtom("Enter atom number: ");
-          Log() << Verbose(0) << "Enter relative coordinates." << endl;
-          first->x.AskPosition(mol->cell_size, false);
+          dialog->queryVector("Enter relative coordinates.",&first->x,World::getInstance().getDomain(), false);
+          dialog->display();
           for (int i=NDIM;i--;) {
-            first->x.x[i] += second->x.x[i];
+            first->x[i] += second->x[i];
           }
         } while (!(valid = mol->CheckBounds((const Vector *)&first->x)));
         first->type = periode->AskElement();  // give type
         mol->AddAtom(first);  // add to molecule
-        break;
+      }
+      break;
 
     case 'd': // two atoms, two angles and a distance
-        first = new atom;
+        first = World::getInstance().createAtom();
         valid = true;
         do {
@@ -153,61 +174,40 @@
           */
           // calc axis vector
-          x.CopyVector(&second->x);
-          x.SubtractVector(&third->x);
+          x= second->x - third->x;
           x.Normalize();
-          Log() << Verbose(0) << "x: ",
-          x.Output();
-          Log() << Verbose(0) << endl;
-          z.MakeNormalVector(&second->x,&third->x,&fourth->x);
-          Log() << Verbose(0) << "z: ",
-          z.Output();
-          Log() << Verbose(0) << endl;
-          y.MakeNormalVector(&x,&z);
-          Log() << Verbose(0) << "y: ",
-          y.Output();
-          Log() << Verbose(0) << endl;
+          Log() << Verbose(0) << "x: " << x << endl;
+          z = Plane(second->x,third->x,fourth->x).getNormal();
+          Log() << Verbose(0) << "z: " << z << endl;
+          y = Plane(x,z,0).getNormal();
+          Log() << Verbose(0) << "y: " << y << endl;
 
           // rotate vector around first angle
-          first->x.CopyVector(&x);
-          first->x.RotateVector(&z,b - M_PI);
-          Log() << Verbose(0) << "Rotated vector: ",
-          first->x.Output();
-          Log() << Verbose(0) << endl;
+          first->x = x;
+          first->x = RotateVector(first->x,z,b - M_PI);
+          Log() << Verbose(0) << "Rotated vector: " << first->x << endl,
           // remove the projection onto the rotation plane of the second angle
-          n.CopyVector(&y);
-          n.Scale(first->x.ScalarProduct(&y));
-          Log() << Verbose(0) << "N1: ",
-          n.Output();
-          Log() << Verbose(0) << endl;
-          first->x.SubtractVector(&n);
-          Log() << Verbose(0) << "Subtracted vector: ",
-          first->x.Output();
-          Log() << Verbose(0) << endl;
-          n.CopyVector(&z);
-          n.Scale(first->x.ScalarProduct(&z));
-          Log() << Verbose(0) << "N2: ",
-          n.Output();
-          Log() << Verbose(0) << endl;
-          first->x.SubtractVector(&n);
-          Log() << Verbose(0) << "2nd subtracted vector: ",
-          first->x.Output();
-          Log() << Verbose(0) << endl;
+          n = y;
+          n.Scale(first->x.ScalarProduct(y));
+          Log() << Verbose(0) << "N1: " << n << endl;
+          first->x -= n;
+          Log() << Verbose(0) << "Subtracted vector: " << first->x << endl;
+          n = z;
+          n.Scale(first->x.ScalarProduct(z));
+          Log() << Verbose(0) << "N2: " << n << endl;
+          first->x -= n;
+          Log() << Verbose(0) << "2nd subtracted vector: " << first->x << endl;
 
           // rotate another vector around second angle
-          n.CopyVector(&y);
-          n.RotateVector(&x,c - M_PI);
-          Log() << Verbose(0) << "2nd Rotated vector: ",
-          n.Output();
-          Log() << Verbose(0) << endl;
+          n = y;
+          n = RotateVector(n,x,c - M_PI);
+          Log() << Verbose(0) << "2nd Rotated vector: " << n << endl;
 
           // add the two linear independent vectors
-          first->x.AddVector(&n);
+          first->x += n;
           first->x.Normalize();
           first->x.Scale(a);
-          first->x.AddVector(&second->x);
-
-          Log() << Verbose(0) << "resulting coordinates: ";
-          first->x.Output();
-          Log() << Verbose(0) << endl;
+          first->x += second->x;
+
+          Log() << Verbose(0) << "resulting coordinates: " << first->x << endl;
         } while (!(valid = mol->CheckBounds((const Vector *)&first->x)));
         first->type = periode->AskElement();  // give type
@@ -216,5 +216,5 @@
 
       case 'e': // least square distance position to a set of atoms
-        first = new atom;
+        first = World::getInstance().createAtom();
         atoms = new (Vector*[128]);
         valid = true;
@@ -232,11 +232,11 @@
         } while ((j != -1) && (i<128));
         if (i >= 2) {
-          first->x.LSQdistance((const Vector **)atoms, i);
-
-          first->x.Output();
+          LSQdistance(first->x,(const Vector **)atoms, i);
+
+          Log() << Verbose(0) << first->x;
           first->type = periode->AskElement();  // give type
           mol->AddAtom(first);  // add to molecule
         } else {
-          delete first;
+          World::getInstance().destroyAtom(first);
           Log() << Verbose(0) << "Please enter at least two vectors!\n";
         }
@@ -279,11 +279,9 @@
       for (int i=0;i<NDIM;i++) {
         Log() << Verbose(0) << "Enter axis " << i << " boundary: ";
-        cin >> y.x[i];
+        cin >> y[i];
       }
       mol->CenterEdge(&x);  // make every coordinate positive
-      mol->Center.AddVector(&y); // translate by boundary
-      helper.CopyVector(&y);
-      helper.Scale(2.);
-      helper.AddVector(&x);
+      mol->Center += y; // translate by boundary
+      helper = (2*y)+x;
       mol->SetBoxDimension(&helper);  // update Box of atoms by boundary
       break;
@@ -292,5 +290,5 @@
       for (int i=0;i<NDIM;i++) {
         Log() << Verbose(0) << "Enter axis " << i << " boundary: ";
-        cin >> x.x[i];
+        cin >> x[i];
       }
       // update Box of atoms by boundary
@@ -329,17 +327,21 @@
       third = mol->AskAtom("Enter third atom: ");
 
-      n.MakeNormalVector((const Vector *)&first->x,(const Vector *)&second->x,(const Vector *)&third->x);
+      n = Plane(first->x,second->x,third->x).getNormal();
       break;
     case 'b': // normal vector of mirror plane
-      Log() << Verbose(0) << "Enter normal vector of mirror plane." << endl;
-      n.AskPosition(mol->cell_size,0);
+    {
+      Dialog *dialog = UIFactory::getInstance().makeDialog();
+      dialog->queryVector("Enter normal vector of mirror plane.",&n,World::getInstance().getDomain(),false);
+      dialog->display();
+      delete dialog;
       n.Normalize();
-      break;
+    }
+    break;
+
     case 'c': // three atoms defining mirror plane
       first = mol->AskAtom("Enter first atom: ");
       second = mol->AskAtom("Enter second atom: ");
 
-      n.CopyVector((const Vector *)&first->x);
-      n.SubtractVector((const Vector *)&second->x);
+      n = first->x - second->x;
       n.Normalize();
       break;
@@ -355,17 +357,13 @@
       mol->GetAlignvector(&param);
       for (int i=NDIM;i--;) {
-        x.x[i] = gsl_vector_get(param.x,i);
-        n.x[i] = gsl_vector_get(param.x,i+NDIM);
+        x[i] = gsl_vector_get(param.x,i);
+        n[i] = gsl_vector_get(param.x,i+NDIM);
       }
       gsl_vector_free(param.x);
-      Log() << Verbose(0) << "Offset vector: ";
-      x.Output();
-      Log() << Verbose(0) << endl;
+      Log() << Verbose(0) << "Offset vector: " << x << endl;
       n.Normalize();
       break;
   };
-  Log() << Verbose(0) << "Alignment vector: ";
-  n.Output();
-  Log() << Verbose(0) << endl;
+  Log() << Verbose(0) << "Alignment vector: " << n << endl;
   mol->Align(&n);
 };
@@ -396,23 +394,25 @@
       third = mol->AskAtom("Enter third atom: ");
 
-      n.MakeNormalVector((const Vector *)&first->x,(const Vector *)&second->x,(const Vector *)&third->x);
+      n = Plane(first->x,second->x,third->x).getNormal();
       break;
     case 'b': // normal vector of mirror plane
-      Log() << Verbose(0) << "Enter normal vector of mirror plane." << endl;
-      n.AskPosition(mol->cell_size,0);
+    {
+      Dialog *dialog = UIFactory::getInstance().makeDialog();
+      dialog->queryVector("Enter normal vector of mirror plane.",&n,World::getInstance().getDomain(),false);
+      dialog->display();
+      delete dialog;
       n.Normalize();
-      break;
+    }
+    break;
+
     case 'c': // three atoms defining mirror plane
       first = mol->AskAtom("Enter first atom: ");
       second = mol->AskAtom("Enter second atom: ");
 
-      n.CopyVector((const Vector *)&first->x);
-      n.SubtractVector((const Vector *)&second->x);
+      n = first->x - second->x;
       n.Normalize();
       break;
   };
-  Log() << Verbose(0) << "Normal vector: ";
-  n.Output();
-  Log() << Verbose(0) << endl;
+  Log() << Verbose(0) << "Normal vector: " << n << endl;
   mol->Mirror((const Vector *)&n);
 };
@@ -454,5 +454,5 @@
         first = second;
         second = first->next;
-        if (first->x.DistanceSquared((const Vector *)&second->x) > tmp1*tmp1) // distance to first above radius ...
+        if (first->x.DistanceSquared(second->x) > tmp1*tmp1) // distance to first above radius ...
           mol->RemoveAtom(first);
       }
@@ -470,5 +470,5 @@
         first = second;
         second = first->next;
-        if ((first->x.x[axis] < tmp1) || (first->x.x[axis] > tmp2)) {// out of boundary ...
+        if ((first->x[axis] < tmp1) || (first->x[axis] > tmp2)) {// out of boundary ...
           //Log() << Verbose(0) << "Atom " << *first << " with " << first->x.x[axis] << " on axis " << axis << " is out of bounds [" << tmp1 << "," << tmp2 << "]." << endl;
           mol->RemoveAtom(first);
@@ -521,6 +521,5 @@
         tmp1 = 0.;
         if (first != second) {
-          x.CopyVector((const Vector *)&first->x);
-          x.SubtractVector((const Vector *)&second->x);
+          x = first->x - second->x;
           tmp1 = x.Norm();
         }
@@ -537,10 +536,8 @@
       for (int i=NDIM;i--;)
         min[i] = 0.;
-      x.CopyVector((const Vector *)&first->x);
-      x.SubtractVector((const Vector *)&second->x);
+      x = first->x - second->x;
       tmp1 = x.Norm();
-      Log() << Verbose(1) << "Distance vector is ";
-      x.Output();
-      Log() << Verbose(0) << "." << endl << "Norm of distance is " << tmp1 << "." << endl;
+      Log() << Verbose(1) << "Distance vector is " << x << "." << "/n"
+            << "Norm of distance is " << tmp1 << "." << endl;
       break;
 
@@ -551,10 +548,8 @@
       third  = mol->AskAtom("Enter last atom: ");
       tmp1 = tmp2 = tmp3 = 0.;
-      x.CopyVector((const Vector *)&first->x);
-      x.SubtractVector((const Vector *)&second->x);
-      y.CopyVector((const Vector *)&third->x);
-      y.SubtractVector((const Vector *)&second->x);
+      x = first->x - second->x;
+      y = third->x - second->x;
       Log() << Verbose(0) << "Bond angle between first atom Nr." << first->nr << ", central atom Nr." << second->nr << " and last atom Nr." << third->nr << ": ";
-      Log() << Verbose(0) << (acos(x.ScalarProduct((const Vector *)&y)/(y.Norm()*x.Norm()))/M_PI*180.) << " degrees" << endl;
+      Log() << Verbose(0) << (acos(x.ScalarProduct(y)/(y.Norm()*x.Norm()))/M_PI*180.) << " degrees" << endl;
       break;
     case 'd':
@@ -675,5 +670,5 @@
         minBond = 0.;
         for (int i=NDIM;i--;)
-          minBond += (first->x.x[i]-second->x.x[i])*(first->x.x[i] - second->x.x[i]);
+          minBond += (first->x[i]-second->x[i])*(first->x[i] - second->x[i]);
         minBond = sqrt(minBond);
         Log() << Verbose(0) << "Current Bond length between " << first->type->name << " Atom " << first->nr << " and " << second->type->name << " Atom " << second->nr << ": " << minBond << " a.u." << endl;
@@ -681,5 +676,5 @@
         cin >> bond;
         for (int i=NDIM;i--;) {
-          second->x.x[i] -= (second->x.x[i]-first->x.x[i])/minBond*(minBond-bond);
+          second->x[i] -= (second->x[i]-first->x[i])/minBond*(minBond-bond);
         }
         //Log() << Verbose(0) << "New coordinates of Atom " << second->nr << " are: ";
@@ -736,5 +731,5 @@
         Log() << Verbose(0) << "New element by atomic number Z: ";
         cin >> Z;
-        first->type = periode->FindElement(Z);
+        first->setType(Z);
         Log() << Verbose(0) << "Atom " << first->nr << "'s element is " << first->type->name << "." << endl;
       }
@@ -747,5 +742,5 @@
   int axis,faktor,count,j;
   atom *first = NULL;
-  element **Elements;
+  const element **Elements;
   Vector x,y;
   Vector **vectors;
@@ -763,5 +758,5 @@
     if (mol->AtomCount != 0) {  // if there is more than none
       count = mol->AtomCount;  // is changed becausing of adding, thus has to be stored away beforehand
-      Elements = new element *[count];
+      Elements = new const element *[count];
       vectors = new Vector *[count];
       j = 0;
@@ -777,11 +772,10 @@
       x.Zero();
       y.Zero();
-      y.x[abs(axis)-1] = mol->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] * abs(axis)/axis; // last term is for sign, first is for magnitude
+      y[abs(axis)-1] = World::getInstance().getDomain()[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] * abs(axis)/axis; // last term is for sign, first is for magnitude
       for (int i=1;i<faktor;i++) {  // then add this list with respective translation factor times
-        x.AddVector(&y); // per factor one cell width further
+        x += y; // per factor one cell width further
         for (int k=count;k--;) { // go through every atom of the original cell
-          first = new atom(); // create a new body
-          first->x.CopyVector(vectors[k]);  // use coordinate of original atom
-          first->x.AddVector(&x);     // translate the coordinates
+          first = World::getInstance().createAtom(); // create a new body
+          first->x = (*vectors[k]) + x;  // use coordinate of original atom
           first->type = Elements[k];  // insert original element
           mol->AddAtom(first);        // and add to the molecule (which increments ElementsInMolecule, AtomCount, ...)
@@ -795,10 +789,9 @@
       // correct cell size
       if (axis < 0) { // if sign was negative, we have to translate everything
-        x.Zero();
-        x.AddVector(&y);
+        x = y;
         x.Scale(-(faktor-1));
         mol->Translate(&x);
       }
-      mol->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor;
+      World::getInstance().getDomain()[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor;
     }
   }
@@ -811,11 +804,7 @@
 void oldmenu::ManipulateMolecules(periodentafel *periode, MoleculeListClass *molecules, config *configuration)
 {
-  atom *first = NULL;
   Vector x,y,z,n; // coordinates for absolute point in cell volume
-  int j, axis, count, faktor;
   char choice;  // menu choice char
   molecule *mol = NULL;
-  element **Elements;
-  Vector **vectors;
   MoleculeLeafClass *Subgraphs = NULL;
 
@@ -896,7 +885,10 @@
         mol = *ListRunner;
         Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
-        Log() << Verbose(0) << "Enter translation vector." << endl;
-        x.AskPosition(mol->cell_size,0);
-        mol->Center.AddVector((const Vector *)&x);
+        Dialog *dialog = UIFactory::getInstance().makeDialog();
+        dialog->queryVector("Enter translation vector.",&x,World::getInstance().getDomain(),false);
+        if(dialog->display()){
+          mol->Center += x;
+        }
+        delete dialog;
      }
      break;
@@ -915,5 +907,5 @@
 void oldmenu::SimpleAddMolecules(MoleculeListClass *molecules) {
   molecule *srcmol = NULL, *destmol = NULL;
-  Dialog *dialog = UIFactory::get()->makeDialog();
+  Dialog *dialog = UIFactory::getInstance().makeDialog();
   dialog->queryMolecule("Enter index of destination molecule: ",&destmol, molecules);
   dialog->queryMolecule("Enter index of source molecule to add from: ",&srcmol, molecules);
@@ -929,5 +921,5 @@
 void oldmenu::embeddMolecules(MoleculeListClass *molecules) {
   molecule *srcmol = NULL, *destmol = NULL;
-  Dialog *dialog = UIFactory::get()->makeDialog();
+  Dialog *dialog = UIFactory::getInstance().makeDialog();
   dialog->queryMolecule("Enter index of matrix molecule (the variable one): ",&srcmol,molecules);
   dialog->queryMolecule("Enter index of molecule to merge into (the fixed one): ",&destmol,molecules);
@@ -1092,5 +1084,5 @@
     A++;
   }
-  delete(mol);
+  World::getInstance().destroyMolecule(mol);
 };
 
Index: src/Line.cpp
===================================================================
--- src/Line.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Line.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,32 @@
+/*
+ * Line.cpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#include "Line.hpp"
+
+#include <cmath>
+
+#include "vector.hpp"
+
+Line::Line(Vector &_origin, Vector &_direction) :
+  origin(new Vector(_origin)),
+  direction(new Vector(_direction))
+{
+  direction->Normalize();
+}
+
+Line::~Line()
+{}
+
+
+double Line::distance(const Vector &point) const{
+  return fabs(point.ScalarProduct(*direction) - origin->ScalarProduct(*direction));
+}
+
+Vector Line::getClosestPoint(const Vector &point) const{
+  double factor = point.ScalarProduct(*direction) - origin->ScalarProduct(*direction);
+  return (point - (factor * (*direction)));
+}
Index: src/Line.hpp
===================================================================
--- src/Line.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Line.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,31 @@
+/*
+ * Line.hpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#ifndef LINE_HPP_
+#define LINE_HPP_
+
+#include "Space.hpp"
+
+#include <memory>
+
+class Vector;
+
+class Line : public Space
+{
+public:
+  Line(Vector &_origin, Vector &_direction);
+  virtual ~Line();
+
+  virtual double distance(const Vector &point) const=0;
+  virtual Vector getClosestPoint(const Vector &point) const=0;
+
+private:
+  std::auto_ptr<Vector> origin;
+  std::auto_ptr<Vector> direction;
+};
+
+#endif /* LINE_HPP_ */
Index: src/Makefile.am
===================================================================
--- src/Makefile.am	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Makefile.am	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -1,25 +1,210 @@
-ATOMSOURCE = atom.cpp atom_atominfo.cpp atom_bondedparticle.cpp atom_bondedparticleinfo.cpp atom_graphnode.cpp atom_graphnodeinfo.cpp atom_particleinfo.cpp atom_trajectoryparticle.cpp atom_trajectoryparticleinfo.cpp
-ATOMHEADER = atom.hpp atom_atominfo.hpp atom_bondedparticle.hpp atom_bondedparticleinfo.hpp atom_graphnode.hpp atom_graphnodeinfo.hpp atom_particleinfo.hpp atom_trajectoryparticle.hpp atom_trajectoryparticleinfo.hpp
-
-LINALGSOURCE = gslmatrix.cpp gslvector.cpp linearsystemofequations.cpp
-LINALGHEADER = gslmatrix.hpp gslvector.hpp linearsystemofequations.hpp
-
-ANALYSISSOURCE = analysis_bonds.cpp analysis_correlation.cpp
-ANALYSISHEADER = analysis_bonds.hpp analysis_correlation.hpp
-
-ACTIONSSOURCE = Actions/Action.cpp Actions/Process.cpp Actions/MethodAction.cpp Actions/ActionSequence.cpp Actions/MakroAction.cpp Actions/ErrorAction.cpp Actions/small_actions.cpp Actions/ActionRegistry.cpp 
-ACTIONSHEADER = Actions/Action.hpp Actions/Process.hpp Actions/MethodAction.hpp Actions/ActionSequence.hpp Actions/MakroAction.hpp Actions/ErrorAction.hpp Actions/small_actions.hpp Actions/ActionRegistry.hpp
-
-PATTERNSOURCE = Patterns/Observer.cpp
-PATTERNHEADER = Patterns/Observer.hpp Patterns/Cacheable.hpp
-
-VIEWSOURCE = Views/View.cpp Views/StringView.cpp Views/MethodStringView.cpp Views/StreamStringView.cpp
-VIEWHEADER = Views/View.hpp Views/StringView.hpp Views/MethodStringView.hpp Views/StreamStringView.hpp
-
-MENUSOURCE = Menu/Menu.cpp Menu/TextMenu.cpp Menu/MenuItem.cpp Menu/SubMenuItem.cpp Menu/ActionMenuItem.cpp Menu/SeperatorItem.cpp Menu/DisplayMenuItem.cpp
-MENUHEADER = Menu/Menu.hpp Menu/TextMenu.hpp Menu/MenuItem.hpp Menu/SubMenuItem.hpp Menu/ActionMenuItem.hpp Menu/SeperatorItem.hpp Menu/DisplayMenuItem.hpp
-
-UISOURCE = ${ACTIONSSOURCE} ${VIEWSOURCE} ${MENUSOURCE} UIElements/UIFactory.cpp UIElements/TextUIFactory.cpp UIElements/MainWindow.cpp UIElements/TextWindow.cpp UIElements/TextStatusIndicator.cpp UIElements/Dialog.cpp UIElements/TextDialog.cpp
-UIHEADER = ${ACTIONSHEADER} ${VIEWHEADER} ${MENUHEADER} UIElements/UIFactory.hpp UIElements/TextUIFactory.hpp UIElements/MainWindow.hpp UIElements/TextWindow.hpp UIElements/TextStatusIndicator.hpp UIElements/Dialog.hpp UIElements/TextDialog.hpp
+# PLEASE adhere to the alphabetical ordering in this Makefile!
+# Also indentation by a single tab
+
+# this includes source files that need to be present at multiple points
+HELPERSOURCE =  \
+  Helpers/Assert.cpp \
+  Helpers/MemDebug.cpp
+		        
+ATOMSOURCE = \
+  atom.cpp \
+  atom_atominfo.cpp \
+  atom_bondedparticle.cpp \
+  atom_bondedparticleinfo.cpp \
+  atom_graphnode.cpp \
+  atom_graphnodeinfo.cpp \
+  atom_particleinfo.cpp \
+  atom_trajectoryparticle.cpp \
+  atom_trajectoryparticleinfo.cpp
+ATOMHEADER = \
+  atom.hpp \
+  atom_atominfo.hpp \
+  atom_bondedparticle.hpp \
+  atom_bondedparticleinfo.hpp \
+  atom_graphnode.hpp \
+  atom_graphnodeinfo.hpp \
+  atom_particleinfo.hpp \
+  atom_trajectoryparticle.hpp \
+  atom_trajectoryparticleinfo.hpp
+
+LINALGSOURCE = \
+  ${HELPERSOURCE} \
+  gslmatrix.cpp \
+  gslvector.cpp \
+  linearsystemofequations.cpp \
+  Space.cpp \
+  vector.cpp
+			   
+LINALGHEADER = gslmatrix.hpp \
+  gslvector.hpp \
+  linearsystemofequations.hpp \
+  Space.hpp \
+  vector.hpp
+			   
+ANALYSISSOURCE = \
+  analysis_bonds.cpp \
+  analysis_correlation.cpp
+ANALYSISHEADER = \
+  analysis_bonds.hpp \
+  analysis_correlation.hpp
+
+ACTIONSSOURCE = Actions/Action.cpp \
+  ${ATOMACTIONSOURCE} \
+  ${CMDACTIONSOURCE} \
+  ${FRAGMENTATIONACTIONSOURCE} \
+  ${MOLECULEACTIONSOURCE} \
+  ${PARSERACTIONSOURCE} \
+  ${TESSELATIONACTIONSOURCE} \
+  Actions/ActionHistory.cpp \
+  Actions/ActionRegistry.cpp \
+  Actions/ActionSequence.cpp \
+  Actions/ErrorAction.cpp \
+  Actions/MakroAction.cpp \
+  Actions/ManipulateAtomsProcess.cpp \
+  Actions/MethodAction.cpp \
+  Actions/Process.cpp
+
+ACTIONSHEADER = Actions/Action.hpp \
+  ${ATOMACTIONHEADER} \
+  ${CMDACTIONHEADER} \
+  ${FRAGMENTATIONACTIONHEADER} \
+  ${MOLECULEACTIONHEADER} \
+  ${PARSERACTIONHEADER} \
+  ${TESSELATIONACTIONHEADER} \
+  Actions/ActionHistory.hpp \
+  Actions/ActionRegistry.hpp \
+  Actions/ActionSequence.hpp \
+  Actions/Calculation.hpp \
+  Actions/Calculation_impl.hpp \
+  Actions/ErrorAction.hpp \
+  Actions/MakroAction.hpp \
+  Actions/ManipulateAtomsProcess.hpp \
+  Actions/MethodAction.hpp \
+  Actions/Process.hpp
+  
+ATOMACTIONSOURCE =
+#  Actions/AtomAction/SomeAction.cpp               
+ATOMACTIONHEADER =
+#  Actions/AtomAction/SomeAction.hpp
+
+CMDACTIONSOURCE = \
+  Actions/CmdAction/HelpAction.cpp \
+  Actions/CmdAction/VersionAction.cpp
+CMDACTIONHEADER = \
+  Actions/CmdAction/HelpAction.hpp \
+  Actions/CmdAction/VersionAction.hpp
+
+FRAGMENTATIONACTIONSOURCE = 
+#  Actions/FragmentationAction/SomeAction.cpp               
+FRAGMENTATIONACTIONHEADER =
+#  Actions/FragmentationAction/SomeAction.hpp
+
+MOLECULEACTIONSOURCE = \
+  Actions/MoleculeAction/ChangeNameAction.cpp
+MOLECULEACTIONHEADER = \
+  Actions/MoleculeAction/ChangeNameAction.hpp
+                 
+PARSERACTIONSOURCE = \
+  Actions/ParserAction/LoadXyzAction.cpp \
+  Actions/ParserAction/SaveXyzAction.cpp       
+PARSERACTIONHEADER = \
+  Actions/ParserAction/LoadXyzAction.hpp \
+  Actions/ParserAction/SaveXyzAction.hpp
+
+TESSELATIONACTIONSOURCE =
+#  Actions/TesselationAction/SomeAction.cpp               
+TESSELATIONACTIONHEADER =
+#  Actions/TesselationAction/SomeAction.hpp
+
+PARSERSOURCE = \
+  Parser/ChangeTracker.cpp \
+  Parser/FormatParser.cpp \
+  Parser/TremoloParser.cpp \
+  Parser/XyzParser.cpp
+PARSERHEADER = \
+  Parser/ChangeTracker.hpp \
+  Parser/FormatParser.hpp \
+  Parser/TremoloParser.hpp \
+  Parser/XyzParser.hpp
+
+PATTERNSOURCE = \
+  Patterns/Observer.cpp
+PATTERNHEADER = \
+  Patterns/Cacheable.hpp \
+  Patterns/Observer.hpp \
+  Patterns/Singleton.hpp
+
+# Below is all for the User Interface
+
+VIEWSOURCE = \
+  Views/View.cpp \
+  Views/StringView.cpp \
+  Views/MethodStringView.cpp \
+  Views/StreamStringView.cpp
+VIEWHEADER = \
+  Views/View.hpp \
+  Views/StringView.hpp \
+  Views/MethodStringView.hpp \
+  Views/StreamStringView.hpp
+
+MENUSOURCE = \
+  Menu/Menu.cpp \
+  Menu/TextMenu.cpp \
+  Menu/MenuItem.cpp \
+  Menu/SubMenuItem.cpp \
+  Menu/ActionMenuItem.cpp \
+  Menu/SeperatorItem.cpp \
+  Menu/DisplayMenuItem.cpp
+  
+MENUHEADER = \
+  Menu/Menu.hpp \
+  Menu/TextMenu.hpp \
+  Menu/MenuItem.hpp \
+  Menu/SubMenuItem.hpp \
+  Menu/ActionMenuItem.hpp \
+  Menu/SeperatorItem.hpp \
+  Menu/DisplayMenuItem.hpp
+
+UISOURCE = \
+  ${ACTIONSSOURCE} \
+  ${COMMANDLINEUISOURCE} \
+  ${MENUSOURCE} \
+  ${TEXTUISOURCE} \
+  ${VIEWSOURCE} \
+  UIElements/Dialog.cpp \
+  UIElements/MainWindow.cpp \
+  UIElements/UIFactory.cpp
+  
+UIHEADER = \
+  ${ACTIONSHEADER} \
+  ${COMMANDLINEUIHEADER} \
+  ${MENUHEADER} \
+  ${TEXTUIHEADER} \
+  ${VIEWHEADER} \
+  UIElements/Dialog.hpp \
+  UIElements/MainWindow.hpp \
+  UIElements/UIFactory.hpp
+
+TEXTUISOURCE = \
+  UIElements/TextDialog.cpp \
+  UIElements/TextStatusIndicator.cpp \
+  UIElements/TextUIFactory.cpp \
+  UIElements/TextWindow.cpp
+TEXTUIHEADER = \
+  UIElements/TextDialog.hpp \
+  UIElements/TextStatusIndicator.hpp \
+  UIElements/TextUIFactory.hpp \
+  UIElements/TextWindow.hpp
+
+COMMANDLINEUISOURCE = \
+  UIElements/CommandLineDialog.cpp \
+  UIElements/CommandLineStatusIndicator.cpp \
+  UIElements/CommandLineUIFactory.cpp \
+  UIElements/CommandLineWindow.cpp
+COMMANDLINEUIHEADER = \
+  UIElements/CommandLineDialog.hpp \
+  UIElements/CommandLineStatusIndicator.hpp \
+  UIElements/CommandLineUIFactory.hpp \
+  UIElements/CommandLineWindow.hpp
 
 # all these files are only used for legacy reasons while the transition is in progress
@@ -29,9 +214,113 @@
 LEGACYHEADER = Legacy/oldmenu.hpp
 
-DESCRIPTORSOURCE = Descriptors/AtomDescriptor.cpp Descriptors/AtomIdDescriptor.cpp
-DESCRIPTORHEADER = Descriptors/AtomDescriptor.hpp Descriptors/AtomIdDescriptor.hpp
-
-SOURCE = ${ANALYSISSOURCE} ${ATOMSOURCE} ${PATTERNSOURCE} ${UISOURCE} ${DESCRIPTORSOURCE} ${LEGACYSOURCE} bond.cpp bondgraph.cpp boundary.cpp config.cpp element.cpp ellipsoid.cpp errorlogger.cpp graph.cpp helpers.cpp info.cpp leastsquaremin.cpp linkedcell.cpp log.cpp logger.cpp memoryusageobserver.cpp moleculelist.cpp molecule.cpp molecule_dynamics.cpp molecule_fragmentation.cpp molecule_geometry.cpp molecule_graph.cpp molecule_pointcloud.cpp parser.cpp periodentafel.cpp tesselation.cpp tesselationhelpers.cpp vector.cpp verbose.cpp World.cpp 
-HEADER = ${ANALYSISHEADER} ${ATOMHEADER} ${PATTERNHEADER} ${UIHEADER} ${DESCRIPTORHEADER} ${LEGACYHEADER} bond.hpp bondgraph.hpp boundary.hpp config.hpp defs.hpp element.hpp ellipsoid.hpp errorlogger.hpp graph.hpp helpers.hpp info.hpp leastsquaremin.hpp linkedcell.hpp lists.hpp log.hpp logger.hpp memoryallocator.hpp memoryusageobserver.hpp molecule.hpp molecule_template.hpp parser.hpp periodentafel.hpp stackclass.hpp tesselation.hpp tesselationhelpers.hpp vector.hpp verbose.hpp World.hpp 
+DESCRIPTORSOURCE = Descriptors/AtomDescriptor.cpp \
+  Descriptors/AtomIdDescriptor.cpp \
+  Descriptors/AtomTypeDescriptor.cpp \
+  Descriptors/MoleculeDescriptor.cpp \
+  Descriptors/MoleculeIdDescriptor.cpp 
+				   
+				   
+DESCRIPTORHEADER = Descriptors/AtomDescriptor.hpp \
+  Descriptors/AtomIdDescriptor.hpp \
+  Descriptors/AtomTypeDescriptor.hpp \
+  Descriptors/MoleculeDescriptor.hpp \
+  Descriptors/MoleculeIdDescriptor.hpp
+				   
+EXCEPTIONSOURCE = Exceptions/CustomException.cpp \
+  Exceptions/LinearDependenceException.cpp \
+  Exceptions/MathException.cpp \
+  Exceptions/ZeroVectorException.cpp
+				  
+EXCEPTIONHEADER = Exceptions/CustomException.hpp \
+  Exceptions/LinearDependenceException.hpp \
+  Exceptions/MathException.hpp \
+  Exceptions/ZeroVectorException.hpp
+
+SOURCE = \
+  ${ANALYSISSOURCE} \
+  ${ATOMSOURCE} \
+  ${PATTERNSOURCE} \
+  ${PARSERSOURCE} \
+  ${UISOURCE} \
+  ${DESCRIPTORSOURCE} \
+  ${HELPERSOURCE} \
+  ${LEGACYSOURCE} \
+  ${EXCEPTIONSOURCE} \
+  bond.cpp \
+  bondgraph.cpp \
+  boundary.cpp \
+  CommandLineParser.cpp \
+  config.cpp \
+  element.cpp \
+  ellipsoid.cpp \
+  errorlogger.cpp \
+  graph.cpp \
+  helpers.cpp \
+  info.cpp \
+  leastsquaremin.cpp \
+  Line.cpp \
+  linkedcell.cpp \
+  lists.cpp \
+  log.cpp \
+  logger.cpp \
+  memoryusageobserver.cpp \
+  moleculelist.cpp \
+  molecule.cpp \
+  molecule_dynamics.cpp \
+  molecule_fragmentation.cpp \
+  molecule_geometry.cpp \
+  molecule_graph.cpp \
+  molecule_pointcloud.cpp \
+  parser.cpp \
+  periodentafel.cpp \
+  Plane.cpp \
+  tesselation.cpp \
+  tesselationhelpers.cpp \
+  triangleintersectionlist.cpp \
+  verbose.cpp \
+  vector_ops.cpp \
+  World.cpp
+
+HEADER = \
+  ${ANALYSISHEADER} \
+  ${ATOMHEADER} \
+  ${PARSERHEADER} \
+  ${PATTERNHEADER} \
+  ${UIHEADER} \
+  ${DESCRIPTORHEADER} \
+  ${EXCEPTIONHEADER} \
+  ${LEGACYHEADER} \
+  bond.hpp \
+  bondgraph.hpp \
+  boundary.hpp \
+  CommandLineParser.hpp \
+  config.hpp \
+  defs.hpp \
+  element.hpp \
+  ellipsoid.hpp \
+  errorlogger.hpp \
+  graph.hpp \
+  helpers.hpp \
+  info.hpp \
+  leastsquaremin.hpp \
+  Line.hpp \
+  linkedcell.hpp \
+  lists.hpp \
+  log.hpp \
+  logger.hpp \
+  memoryallocator.hpp \
+  memoryusageobserver.hpp \
+  molecule.hpp \
+  molecule_template.hpp \
+  parser.hpp \
+  periodentafel.hpp \
+  Plane.hpp \
+  stackclass.hpp \
+  tesselation.hpp \
+  tesselationhelpers.hpp \
+  triangleintersectionlist.hpp \
+  verbose.hpp \
+  vector_ops.hpp \
+  World.hpp 
 
 BOOST_LIB = $(BOOST_LDFLAGS) $(BOOST_MPL_LIB)
@@ -41,19 +330,14 @@
 bin_PROGRAMS = molecuilder joiner analyzer
 molecuilderdir = ${bindir}
-#libmolecuilder_a_CXXFLAGS = -DNO_CACHING
 libmolecuilder_a_SOURCES = ${SOURCE} ${HEADER}
 libgslwrapper_a_SOURCES = ${LINALGSOURCE} ${LINALGHEADER}
 molecuilder_DATA = elements.db valence.db orbitals.db Hbonddistance.db Hbondangle.db
 molecuilder_LDFLAGS = $(BOOST_LDFLAGS)
-molecuilder_CXXFLAGS = $(BOOST_CPPFLAGS)
-#molecuilder_CXXFLAGS += -DNO_CACHING
 molecuilder_SOURCES = builder.cpp
-molecuilder_LDADD = libmolecuilder.a libgslwrapper.a $(BOOST_LIB) ${BOOST_THREAD_LIB}
+molecuilder_LDADD = libmolecuilder.a libgslwrapper.a $(BOOST_LIB) ${BOOST_THREAD_LIB} ${BOOST_PROGRAM_OPTIONS_LIB}
 joiner_SOURCES = joiner.cpp datacreator.cpp parser.cpp datacreator.hpp helpers.hpp parser.hpp periodentafel.hpp
 joiner_LDADD = libmolecuilder.a $(BOOST_LIB) ${BOOST_THREAD_LIB}
 analyzer_SOURCES = analyzer.cpp datacreator.cpp parser.cpp helpers.hpp periodentafel.hpp parser.hpp datacreator.hpp 
 analyzer_LDADD = libmolecuilder.a $(BOOST_LIB) ${BOOST_THREAD_LIB}
-
-#EXTRA_DIST = ${molecuilder_DATA}
 
 FORCE:
Index: src/Menu/ActionMenuItem.cpp
===================================================================
--- src/Menu/ActionMenuItem.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Menu/ActionMenuItem.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -20,9 +20,11 @@
 
 ActionMenuItem::~ActionMenuItem()
-{
-  // TODO Auto-generated destructor stub
-}
+{}
 
 void ActionMenuItem::doTrigger() {
   action->call();
 }
+
+bool ActionMenuItem::isActive() {
+  return action->isActive();
+}
Index: src/Menu/ActionMenuItem.hpp
===================================================================
--- src/Menu/ActionMenuItem.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Menu/ActionMenuItem.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -26,4 +26,6 @@
   virtual void doTrigger();
 
+  virtual bool isActive();
+
 private:
   Action* action; //!< this action will be called when the trigger matches
Index: src/Menu/DisplayMenuItem.cpp
===================================================================
--- src/Menu/DisplayMenuItem.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Menu/DisplayMenuItem.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -21,16 +21,14 @@
 
 DisplayMenuItem::DisplayMenuItem(Menu* _menu, StringView *_view, string _title, char _spacer, int _length ):
-MenuItem('\0',"",_menu),
-view(_view),
-title(_title),
-spacer(_spacer),
-length(_length)
+  MenuItem('\0',"",_menu),
+  view(_view),
+  title(_title),
+  length(_length),
+  spacer(_spacer)
 {
 }
 
 DisplayMenuItem::~DisplayMenuItem()
-{
-  // TODO Auto-generated destructor stub
-}
+{}
 
 
Index: src/Menu/MenuItem.cpp
===================================================================
--- src/Menu/MenuItem.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Menu/MenuItem.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -78,2 +78,6 @@
   return added;
 }
+
+bool MenuItem::isActive(){
+  return true;
+}
Index: src/Menu/MenuItem.hpp
===================================================================
--- src/Menu/MenuItem.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Menu/MenuItem.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -21,9 +21,4 @@
  */
 class MenuItem {
-private:
-  char trigger;
-  string *description;
-  bool added;
-
 public:
   MenuItem(char,const char*,Menu*);
@@ -41,6 +36,13 @@
   bool wasAdded();
 
+  virtual bool isActive();
+
 protected:
   void setDescription(string);
+
+private:
+  char trigger;
+  string *description;
+  bool added;
 };
 
Index: src/Menu/TextMenu.cpp
===================================================================
--- src/Menu/TextMenu.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Menu/TextMenu.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -11,4 +11,5 @@
 #include "Menu/TextMenu.hpp"
 #include "Menu/MenuItem.hpp"
+#include "Helpers/Assert.hpp"
 
 
@@ -18,10 +19,10 @@
  */
 TextMenu::TextMenu(ostream& _outputter, string _title, char _spacer,int _length) :
-outputter(_outputter),
-title(_title),
-spacer(_spacer),
-length(_length),
-quit(false),
-defaultItem(0)
+  defaultItem(0),
+  outputter(_outputter),
+  title(_title),
+  spacer(_spacer),
+  length(_length),
+  quit(false)
 {
 }
@@ -51,5 +52,12 @@
 
 void TextMenu::showEntry(MenuItem* entry){
-  outputter << entry->formatEntry() << "\n";
+  if(entry->isActive()==false){
+    outputter << "(";
+  }
+  outputter << entry->formatEntry();
+  if(entry->isActive()==false){
+    outputter << ")";
+  }
+  outputter << "\n";
 }
 
@@ -74,5 +82,7 @@
     list<MenuItem*>::iterator iter;
     for(iter = items.begin(); iter!=items.end();iter++){
-      somethingChosen |= (*iter)->checkTrigger(choice);
+      if((*iter)->isActive()){
+        somethingChosen |= (*iter)->checkTrigger(choice);
+      }
     }
     // see if something was chosen and call default Item if not
@@ -88,5 +98,44 @@
 }
 
+string TextMenu::getTitle(){
+  return title;
+}
+
 void TextMenu::addDefault(MenuItem* _defaultItem) {
   defaultItem = _defaultItem;
 }
+
+/****************************** Contained Actions ****************/
+
+const string TextMenu::LeaveAction::nameBase = "Leave menu: ";
+
+TextMenu::LeaveAction::LeaveAction(TextMenu* _menu) :
+Action(nameBase+_menu->getTitle()),
+menu(_menu)
+{}
+
+TextMenu::LeaveAction::~LeaveAction(){}
+
+bool TextMenu::LeaveAction::canUndo(){
+  return false;
+}
+
+bool TextMenu::LeaveAction::shouldUndo(){
+  return false;
+}
+
+Action::state_ptr TextMenu::LeaveAction::performCall(){
+  menu->doQuit();
+  return Action::success;
+}
+
+
+Action::state_ptr TextMenu::LeaveAction::performUndo(Action::state_ptr){
+  ASSERT(0,"Cannot undo leaving a menu");
+  return Action::success;
+}
+
+Action::state_ptr TextMenu::LeaveAction::performRedo(Action::state_ptr){
+  ASSERT(0,"Cannot redo leaving a menu");
+  return Action::success;
+}
Index: src/Menu/TextMenu.hpp
===================================================================
--- src/Menu/TextMenu.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Menu/TextMenu.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -14,4 +14,5 @@
 
 #include "Menu/Menu.hpp"
+#include "Actions/Action.hpp"
 #include "defs.hpp"
 
@@ -26,4 +27,22 @@
 {
 public:
+  class LeaveAction : public Action {
+  public:
+    LeaveAction(TextMenu*);
+    virtual ~LeaveAction();
+
+    bool canUndo();
+    bool shouldUndo();
+
+  private:
+    virtual Action::state_ptr performCall();
+    virtual Action::state_ptr performUndo(Action::state_ptr);
+    virtual Action::state_ptr performRedo(Action::state_ptr);
+
+    TextMenu* menu;
+
+    static const string nameBase;
+  };
+
   TextMenu(ostream& _outputter, string _title, char _spacer=STD_MENU_TITLE_SPACER,int _length=STD_MENU_LENGTH);
   virtual ~TextMenu();
@@ -32,4 +51,5 @@
   virtual void removeItem(MenuItem*);
   virtual void display();
+  virtual string getTitle();
 
   /**
Index: src/Parser/ChangeTracker.cpp
===================================================================
--- src/Parser/ChangeTracker.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Parser/ChangeTracker.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,73 @@
+/*
+ * ChangeTracker.cpp
+ *
+ *  Created on: Mar 1, 2010
+ *      Author: metzler
+ */
+
+#include "ChangeTracker.hpp"
+
+ChangeTracker* ChangeTracker::instance = NULL;
+
+/**
+ * Constructor. Signs on as an observer for the World.
+ */
+ChangeTracker::ChangeTracker() {
+  isConsistent = true;
+  World::getInstance().signOn(this);
+}
+
+/**
+ * Destructor. Signs off from the World.
+ */
+ChangeTracker::~ChangeTracker() {
+  World::getInstance().signOff(this);
+}
+
+/**
+ * Returns the change tracker instance.
+ *
+ * \return this
+ */
+ChangeTracker* ChangeTracker::get() {
+  if (instance == NULL) {
+    instance = new ChangeTracker();
+  }
+
+  return instance;
+}
+
+/**
+ * Destroys the change tracker instance. Be careful, the change tracker is a
+ * singleton and destruction might lead to a loss of consistency.
+ */
+void ChangeTracker::destroy() {
+  delete instance;
+  instance = NULL;
+}
+
+/**
+ * With this, the World can update the change tracker's state.
+ */
+void ChangeTracker::update(Observable *publisher) {
+  isConsistent = false;
+}
+
+/**
+ * Gets whether there are non-saved changes.
+ *
+ * \param true if there are any changes, false otherwise
+ */
+bool ChangeTracker::hasChanged() {
+  return !isConsistent;
+}
+
+/**
+ * Tells all observers (which are the different parsers) that they are supposed
+ * to save the current state.
+ */
+void ChangeTracker::saveStatus() {
+  if (hasChanged()) {
+    notifyAll();
+  }
+}
Index: src/Parser/ChangeTracker.hpp
===================================================================
--- src/Parser/ChangeTracker.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Parser/ChangeTracker.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,37 @@
+/*
+ * ChangeTracker.hpp
+ *
+ *  Created on: Mar 1, 2010
+ *      Author: metzler
+ */
+
+#ifndef CHANGETRACKER_HPP_
+#define CHANGETRACKER_HPP_
+
+#include "Patterns/Observer.hpp"
+#include "World.hpp"
+
+using namespace std;
+
+/**
+ * Observes the world and notifies subscribers via saveStatus if there are
+ * changes to it.
+ */
+class ChangeTracker : public Observable {
+public:
+  void saveStatus();
+  static ChangeTracker* get();
+  static void destroy();
+
+protected:
+  void update(Observable *publisher);
+  bool hasChanged();
+
+private:
+  bool isConsistent;
+  static ChangeTracker* instance;
+  ChangeTracker();
+  ~ChangeTracker();
+};
+
+#endif /* CHANGETRACKER_HPP_ */
Index: src/Parser/FormatParser.cpp
===================================================================
--- src/Parser/FormatParser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Parser/FormatParser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,55 @@
+/*
+ * FormatParser.cpp
+ *
+ *  Created on: Mar 1, 2010
+ *      Author: metzler
+ */
+
+#include "FormatParser.hpp"
+#include <iostream>
+
+using namespace std;
+
+/**
+ * Constructor.
+ */
+FormatParser::FormatParser() {
+  ChangeTracker::get()->signOn(this);
+  saveStream = NULL;
+}
+
+/**
+ * Destructor.
+ */
+FormatParser::~FormatParser() {
+  ChangeTracker::get()->signOff(this);
+}
+
+/**
+ * Update operation which can be invoked by the observable (which should be the
+ * change tracker here).
+ */
+void FormatParser::update(Observable *publisher) {
+  if (!saveStream) {
+    cerr << "Please invoke setOstream() so the parser knows where to save the World's data." << endl;
+    return;
+  }
+
+  save(saveStream);
+}
+
+/**
+ * The observable can tell when it dies.
+ */
+void FormatParser::subjectKilled(Observable *publisher) {}
+
+
+/**
+ * Sets the output stream for save, so the save() method can be invoked on update
+ * automatically.
+ *
+ * \param ostream where to save the World's state
+ */
+void FormatParser::setOstream(ostream* output) {
+  saveStream = output;
+}
Index: src/Parser/FormatParser.hpp
===================================================================
--- src/Parser/FormatParser.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Parser/FormatParser.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,32 @@
+/*
+ * FormatParser.hpp
+ *
+ *  Created on: Mar 1, 2010
+ *      Author: metzler
+ */
+
+#ifndef FORMATPARSER_HPP_
+#define FORMATPARSER_HPP_
+
+#include "Patterns/Observer.hpp"
+#include "ChangeTracker.hpp"
+#include "parser.hpp"
+
+/**
+ * General parser which observes the change tracker.
+ */
+class FormatParser : public Observer {
+public:
+  FormatParser();
+  virtual ~FormatParser();
+  virtual void save(std::ostream* file)=0;
+  virtual void load(std::istream* file)=0;
+  void setOstream(std::ostream* file);
+  void update(Observable *publisher);
+  void subjectKilled(Observable *publisher);
+
+private:
+  std::ostream* saveStream;
+};
+
+#endif /* FORMATPARSER_HPP_ */
Index: src/Parser/TremoloParser.cpp
===================================================================
--- src/Parser/TremoloParser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Parser/TremoloParser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,495 @@
+/*
+ * TremoloParser.cpp
+ *
+ *  Created on: Mar 2, 2010
+ *      Author: metzler
+ */
+
+#include "Helpers/Assert.hpp"
+#include "TremoloParser.hpp"
+#include "World.hpp"
+#include "atom.hpp"
+#include "element.hpp"
+#include "bond.hpp"
+#include "periodentafel.hpp"
+#include "Descriptors/AtomIdDescriptor.hpp"
+#include <map>
+#include <vector>
+
+
+using namespace std;
+using namespace boost;
+
+/**
+ * Constructor.
+ */
+TremoloParser::TremoloParser() {
+  knownKeys[" "] = TremoloKey::noKey; // with this we can detect invalid keys
+  knownKeys["x"] = TremoloKey::x;
+  knownKeys["u"] = TremoloKey::u;
+  knownKeys["F"] = TremoloKey::F;
+  knownKeys["stress"] = TremoloKey::stress;
+  knownKeys["Id"] = TremoloKey::Id;
+  knownKeys["neighbors"] = TremoloKey::neighbors;
+  knownKeys["imprData"] = TremoloKey::imprData;
+  knownKeys["GroupMeasureTypeNo"] = TremoloKey::GroupMeasureTypeNo;
+  knownKeys["Type"] = TremoloKey::Type;
+  knownKeys["extType"] = TremoloKey::extType;
+  knownKeys["name"] = TremoloKey::name;
+  knownKeys["resName"] = TremoloKey::resName;
+  knownKeys["chainID"] = TremoloKey::chainID;
+  knownKeys["resSeq"] = TremoloKey::resSeq;
+  knownKeys["occupancy"] = TremoloKey::occupancy;
+  knownKeys["tempFactor"] = TremoloKey::tempFactor;
+  knownKeys["segID"] = TremoloKey::segID;
+  knownKeys["Charge"] = TremoloKey::Charge;
+  knownKeys["charge"] = TremoloKey::charge;
+  knownKeys["GrpTypeNo"] = TremoloKey::GrpTypeNo;
+  knownKeys["torsion"] = TremoloKey::torsion;
+}
+
+/**
+ * Destructor.
+ */
+TremoloParser::~TremoloParser() {
+  usedFields.clear();
+  additionalAtomData.clear();
+  atomIdMap.clear();
+  knownKeys.clear();
+}
+
+/**
+ * Loads atoms from a tremolo-formatted file.
+ *
+ * \param tremolo file
+ */
+void TremoloParser::load(istream* file) {
+  string line;
+  string::size_type location;
+
+  usedFields.clear();
+  while (file->good()) {
+    std::getline(*file, line, '\n');
+    if (usedFields.empty()) {
+      location = line.find("ATOMDATA", 0);
+      if (location != string::npos) {
+       parseAtomDataKeysLine(line, location + 8);
+      }
+    }
+    if (line.length() > 0 && line.at(0) != '#') {
+      readAtomDataLine(line);
+    }
+  }
+
+  processNeighborInformation();
+  adaptImprData();
+  adaptTorsion();
+}
+
+/**
+ * Saves the World's current state into as a tremolo file.
+ *
+ * \param file where to save the state
+ */
+void TremoloParser::save(ostream* file) {
+  vector<atom*>::iterator atomIt;
+  vector<string>::iterator it;
+
+  *file << "# ATOMDATA";
+  for (it=usedFields.begin(); it < usedFields.end(); it++) {
+    *file << "\t" << *it;
+  }
+  *file << endl;
+  vector<atom *> AtomList = World::getInstance().getAllAtoms();
+  for (atomIt = AtomList.begin(); atomIt != AtomList.end(); atomIt++) {
+    saveLine(file, *atomIt);
+  }
+}
+
+/**
+ * Sets the keys for which data should be written to the stream when save is
+ * called.
+ *
+ * \param string of field names with the same syntax as for an ATOMDATA line
+ *        but without the prexix "ATOMDATA"
+ */
+void TremoloParser::setFieldsForSave(std::string atomDataLine) {
+  parseAtomDataKeysLine(atomDataLine, 0);
+}
+
+
+/**
+ * Writes one line of tremolo-formatted data to the provided stream.
+ *
+ * \param stream where to write the line to
+ * \param reference to the atom of which information should be written
+ */
+void TremoloParser::saveLine(ostream* file, atom* currentAtom) {
+  vector<string>::iterator it;
+  TremoloKey::atomDataKey currentField;
+
+  for (it = usedFields.begin(); it != usedFields.end(); it++) {
+    currentField = knownKeys[it->substr(0, it->find("="))];
+    switch (currentField) {
+      case TremoloKey::x :
+        // for the moment, assume there are always three dimensions
+        *file << currentAtom->x[0] << "\t";
+        *file << currentAtom->x[1] << "\t";
+        *file << currentAtom->x[2] << "\t";
+        break;
+      case TremoloKey::u :
+        // for the moment, assume there are always three dimensions
+        *file << currentAtom->v[0] << "\t";
+        *file << currentAtom->v[1] << "\t";
+        *file << currentAtom->v[2] << "\t";
+        break;
+      case TremoloKey::Type :
+        *file << currentAtom->getType()->getSymbol() << "\t";
+        break;
+      case TremoloKey::Id :
+        *file << currentAtom->getId() << "\t";
+        break;
+      case TremoloKey::neighbors :
+        writeNeighbors(file, atoi(it->substr(it->find("=") + 1, 1).c_str()), currentAtom);
+        break;
+      default :
+        *file << (additionalAtomData.find(currentAtom->getId()) != additionalAtomData.end()
+          ? additionalAtomData[currentAtom->getId()].get(currentField)
+          : defaultAdditionalData.get(currentField));
+        *file << "\t";
+        break;
+    }
+  }
+
+  *file << endl;
+}
+
+/**
+ * Writes the neighbor information of one atom to the provided stream.
+ *
+ * \param stream where to write neighbor information to
+ * \param number of neighbors
+ * \param reference to the atom of which to take the neighbor information
+ */
+void TremoloParser::writeNeighbors(ostream* file, int numberOfNeighbors, atom* currentAtom) {
+  BondList::iterator currentBond = currentAtom->ListOfBonds.begin();
+  for (int i = 0; i < numberOfNeighbors; i++) {
+    *file << (currentBond != currentAtom->ListOfBonds.end()
+        ? (*currentBond)->GetOtherAtom(currentAtom)->getId() : 0) << "\t";
+  }
+}
+
+/**
+ * Stores keys from the ATOMDATA line.
+ *
+ * \param line to parse the keys from
+ * \param with which offset the keys begin within the line
+ */
+void TremoloParser::parseAtomDataKeysLine(string line, int offset) {
+  string keyword;
+  stringstream lineStream;
+
+  lineStream << line.substr(offset);
+  while (lineStream.good()) {
+    lineStream >> keyword;
+    if (knownKeys[keyword.substr(0, keyword.find("="))] == TremoloKey::noKey) {
+      // TODO: throw exception about unknown key
+      cout << "Unknown key: " << keyword << " is not part of the tremolo format specification." << endl;
+      break;
+    }
+    usedFields.push_back(keyword);
+  }
+}
+
+/**
+ * Reads one data line of a tremolo file and interprets it according to the keys
+ * obtained from the ATOMDATA line.
+ *
+ * \param line to parse as an atom
+ */
+void TremoloParser::readAtomDataLine(string line) {
+  vector<string>::iterator it;
+  stringstream lineStream;
+  atom* newAtom = World::getInstance().createAtom();
+  TremoloAtomInfoContainer *atomInfo = NULL;
+  additionalAtomData[newAtom->getId()] = *(new TremoloAtomInfoContainer);
+  atomInfo = &additionalAtomData[newAtom->getId()];
+  TremoloKey::atomDataKey currentField;
+  string word;
+  int oldId;
+
+  lineStream << line;
+  for (it = usedFields.begin(); it < usedFields.end(); it++) {
+    currentField = knownKeys[it->substr(0, it->find("="))];
+    switch (currentField) {
+      case TremoloKey::x :
+        // for the moment, assume there are always three dimensions
+        lineStream >> newAtom->x[0];
+        lineStream >> newAtom->x[1];
+        lineStream >> newAtom->x[2];
+        break;
+      case TremoloKey::u :
+        // for the moment, assume there are always three dimensions
+        lineStream >> newAtom->v[0];
+        lineStream >> newAtom->v[1];
+        lineStream >> newAtom->v[2];
+        break;
+      case TremoloKey::Type :
+        char type[3];
+        lineStream >> type;
+        newAtom->setType(World::getInstance().getPeriode()->FindElement(type));
+        ASSERT(newAtom->getType(), "Type was not set for this atom");
+        break;
+      case TremoloKey::Id :
+        lineStream >> oldId;
+        atomIdMap[oldId] = newAtom->getId();
+        break;
+      case TremoloKey::neighbors :
+        readNeighbors(&lineStream,
+            atoi(it->substr(it->find("=") + 1, 1).c_str()), newAtom->getId());
+        break;
+      default :
+        lineStream >> word;
+        atomInfo->set(currentField, word);
+        break;
+    }
+  }
+}
+
+/**
+ * Reads neighbor information for one atom from the input.
+ *
+ * \param stream where to read the information from
+ * \param number of neighbors to read
+ * \param world id of the atom the information belongs to
+ */
+void TremoloParser::readNeighbors(stringstream* line, int numberOfNeighbors, int atomId) {
+  int neighborId = 0;
+  for (int i = 0; i < numberOfNeighbors; i++) {
+    *line >> neighborId;
+    // 0 is used to fill empty neighbor positions in the tremolo file.
+    if (neighborId > 0) {
+      additionalAtomData[atomId].neighbors.push_back(neighborId);
+    }
+  }
+}
+
+/**
+ * Checks whether the provided name is within the list of used fields.
+ *
+ * \param field name to check
+ *
+ * \return true if the field name is used
+ */
+bool TremoloParser::isUsedField(string fieldName) {
+  bool fieldNameExists = false;
+  for (vector<string>::iterator usedField = usedFields.begin(); usedField != usedFields.end(); usedField++) {
+    if (usedField->substr(0, usedField->find("=")) == fieldName)
+      fieldNameExists = true;
+  }
+
+  return fieldNameExists;
+}
+
+
+/**
+ * Adds the collected neighbor information to the atoms in the world. The atoms
+ * are found by their current ID and mapped to the corresponding atoms with the
+ * Id found in the parsed file.
+ */
+void TremoloParser::processNeighborInformation() {
+  if (!isUsedField("neighbors")) {
+    return;
+  }
+
+  for(map<int, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
+    currentInfo != additionalAtomData.end(); currentInfo++
+  ) {
+    for(vector<int>::iterator neighbor = currentInfo->second.neighbors.begin();
+      neighbor != currentInfo->second.neighbors.end(); neighbor++
+    ) {
+      World::getInstance().getAtom(AtomById(currentInfo->first))
+          ->addBond(World::getInstance().getAtom(AtomById(atomIdMap[*neighbor])));
+    }
+  }
+}
+
+/**
+ * Replaces atom IDs read from the file by the corresponding world IDs. All IDs
+ * IDs of the input string will be replaced; expected separating characters are
+ * "-" and ",".
+ *
+ * \param string in which atom IDs should be adapted
+ *
+ * \return input string with modified atom IDs
+ */
+string TremoloParser::adaptIdDependentDataString(string data) {
+  // there might be no IDs
+  if (data == "-") {
+    return "-";
+  }
+
+  char separator;
+  int id;
+  stringstream line, result;
+  line << data;
+
+  line >> id;
+  result << atomIdMap[id];
+  while (line.good()) {
+    line >> separator >> id;
+    result << separator << atomIdMap[id];
+  }
+
+  return result.str();
+}
+
+/**
+ * Corrects the atom IDs in each imprData entry to the corresponding world IDs
+ * as they might differ from the originally read IDs.
+ */
+void TremoloParser::adaptImprData() {
+  if (!isUsedField("imprData")) {
+    return;
+  }
+
+  for(map<int, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
+    currentInfo != additionalAtomData.end(); currentInfo++
+  ) {
+    currentInfo->second.imprData = adaptIdDependentDataString(currentInfo->second.imprData);
+  }
+}
+
+/**
+ * Corrects the atom IDs in each torsion entry to the corresponding world IDs
+ * as they might differ from the originally read IDs.
+ */
+void TremoloParser::adaptTorsion() {
+  if (!isUsedField("torsion")) {
+    return;
+  }
+
+  for(map<int, TremoloAtomInfoContainer>::iterator currentInfo = additionalAtomData.begin();
+    currentInfo != additionalAtomData.end(); currentInfo++
+  ) {
+    currentInfo->second.torsion = adaptIdDependentDataString(currentInfo->second.torsion);
+  }
+}
+
+
+TremoloAtomInfoContainer::TremoloAtomInfoContainer() {
+  F = "0";
+  stress = "0";
+  imprData = "-";
+  GroupMeasureTypeNo = "0";
+  extType = "-";
+  name = "-";
+  resName = "-";
+  chainID = "0";
+  resSeq = "0";
+  occupancy = "0";
+  tempFactor = "0";
+  segID = "0";
+  Charge = "0";
+  charge = "0";
+  GrpTypeNo = "0";
+  torsion = "-";
+  neighbors = vector<int>(0, 5);
+}
+
+void TremoloAtomInfoContainer::set(TremoloKey::atomDataKey key, string value) {
+  switch (key) {
+    case TremoloKey::F :
+      F = value;
+      break;
+    case TremoloKey::stress :
+      stress = value;
+     break;
+    case TremoloKey::imprData :
+      imprData = value;
+      break;
+    case TremoloKey::GroupMeasureTypeNo :
+      GroupMeasureTypeNo = value;
+      break;
+    case TremoloKey::extType :
+      extType = value;
+      break;
+    case TremoloKey::name :
+      name = value;
+      break;
+    case TremoloKey::resName :
+      resName = value;
+      break;
+    case TremoloKey::chainID :
+      chainID = value;
+      break;
+    case TremoloKey::resSeq :
+      resSeq = value;
+      break;
+    case TremoloKey::occupancy :
+      occupancy = value;
+      break;
+    case TremoloKey::tempFactor :
+      tempFactor = value;
+      break;
+    case TremoloKey::segID :
+      segID = value;
+      break;
+    case TremoloKey::Charge :
+      Charge = value;
+      break;
+    case TremoloKey::charge :
+      charge = value;
+      break;
+    case TremoloKey::GrpTypeNo :
+      GrpTypeNo = value;
+      break;
+    case TremoloKey::torsion :
+      torsion = value;
+      break;
+    default :
+      cout << "Unknown key: " << key << ", value: " << value << endl;
+      break;
+  }
+}
+
+string TremoloAtomInfoContainer::get(TremoloKey::atomDataKey key) {
+  switch (key) {
+    case TremoloKey::F :
+      return F;
+    case TremoloKey::stress :
+      return stress;
+    case TremoloKey::imprData :
+      return imprData;
+    case TremoloKey::GroupMeasureTypeNo :
+      return GroupMeasureTypeNo;
+    case TremoloKey::extType :
+      return extType;
+    case TremoloKey::name :
+      return name;
+    case TremoloKey::resName :
+      return resName;
+    case TremoloKey::chainID :
+      return chainID;
+    case TremoloKey::resSeq :
+      return resSeq;
+    case TremoloKey::occupancy :
+      return occupancy;
+    case TremoloKey::tempFactor :
+      return tempFactor;
+    case TremoloKey::segID :
+      return segID;
+    case TremoloKey::Charge :
+      return Charge;
+    case TremoloKey::charge :
+      return charge;
+    case TremoloKey::GrpTypeNo :
+      return GrpTypeNo;
+    case TremoloKey::torsion :
+      return torsion;
+    default :
+      cout << "Unknown key: " << key << endl;
+      return "";
+  }
+}
+
Index: src/Parser/TremoloParser.hpp
===================================================================
--- src/Parser/TremoloParser.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Parser/TremoloParser.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,125 @@
+/*
+ * TremoloParser.hpp
+ *
+ *  Created on: Mar 2, 2010
+ *      Author: metzler
+ */
+
+#ifndef TREMOLOPARSER_HPP_
+#define TREMOLOPARSER_HPP_
+
+#include <string>
+#include "FormatParser.hpp"
+
+/**
+ * Known keys for the ATOMDATA line.
+ */
+class TremoloKey {
+public:
+  enum atomDataKey {
+    noKey,
+    x,
+    u,
+    F,
+    stress,
+    Id,
+    neighbors,
+    imprData,
+    GroupMeasureTypeNo,
+    Type,
+    extType,
+    name,
+    resName,
+    chainID,
+    resSeq,
+    occupancy,
+    tempFactor,
+    segID,
+    Charge,
+    charge,
+    GrpTypeNo,
+    torsion
+  };
+};
+
+/**
+ * Holds tremolo-specific information which is not store in the atom class.
+ */
+class TremoloAtomInfoContainer {
+public:
+  TremoloAtomInfoContainer();
+  void set(TremoloKey::atomDataKey key, std::string value);
+  std::string get(TremoloKey::atomDataKey key);
+  std::string F;
+  std::string stress;
+  std::string imprData;
+  std::string GroupMeasureTypeNo;
+  std::string extType;
+  std::string name;
+  std::string resName;
+  std::string chainID;
+  std::string resSeq;
+  std::string occupancy;
+  std::string tempFactor;
+  std::string segID;
+  std::string Charge;
+  std::string charge;
+  std::string GrpTypeNo;
+  std::string torsion;
+  std::vector<int> neighbors;
+};
+
+/**
+ * Loads a tremolo file into the World and saves the World as a tremolo file.
+ */
+class TremoloParser : public FormatParser
+{
+public:
+  TremoloParser();
+  ~TremoloParser();
+  void load(std::istream* file);
+  void save(std::ostream* file);
+  void setFieldsForSave(std::string atomDataLine);
+
+
+private:
+  void readAtomDataLine(string line);
+  void parseAtomDataKeysLine(string line, int offset);
+  void readNeighbors(std::stringstream* line, int numberOfNeighbors, int atomId);
+  void processNeighborInformation();
+  void adaptImprData();
+  void adaptTorsion();
+  std::string adaptIdDependentDataString(std::string data);
+  bool isUsedField(std::string fieldName);
+  void writeNeighbors(std::ostream* file, int numberOfNeighbors, atom* currentAtom);
+  void saveLine(std::ostream* file, atom* currentAtom);
+
+  /**
+   * Map to associate the known keys with numbers.
+   */
+  std::map<std::string, TremoloKey::atomDataKey> knownKeys;
+
+  /**
+   * Fields used in the tremolo file.
+   */
+  std::vector<std::string> usedFields;
+
+  /**
+   * Data which is currently not stored in atoms but was provided by the input
+   * file.
+   */
+  std::map<int, TremoloAtomInfoContainer> additionalAtomData;
+
+  /**
+   * Default additional atom data.
+   */
+  TremoloAtomInfoContainer defaultAdditionalData;
+
+  /**
+   * Maps original atom IDs received from the parsed file to atom IDs in the
+   * world.
+   */
+  std::map<int, int> atomIdMap;
+};
+
+#endif /* TREMOLOPARSER_HPP_ */
Index: src/Parser/XyzParser.cpp
===================================================================
--- src/Parser/XyzParser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Parser/XyzParser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,64 @@
+/*
+ * XyzParser.cpp
+ *
+ *  Created on: Mar 2, 2010
+ *      Author: metzler
+ */
+
+#include "XyzParser.hpp"
+#include "World.hpp"
+#include "atom.hpp"
+#include "element.hpp"
+#include "periodentafel.hpp"
+
+using namespace std;
+
+/**
+ * Constructor.
+ */
+XyzParser::XyzParser() {
+  comment = "";
+}
+
+/**
+ * Destructor.
+ */
+XyzParser::~XyzParser() {
+  delete(&comment);
+}
+
+/**
+ * Loads an XYZ file into the World.
+ *
+ * \param XYZ file
+ */
+void XyzParser::load(istream* file) {
+  atom* newAtom;
+  int numberOfAtoms;
+  char commentBuffer[512], type[3];
+
+  // the first line tells number of atoms, the second line is always a comment
+  *file >> numberOfAtoms >> ws;
+  file->getline(commentBuffer, 512);
+  comment = commentBuffer;
+
+  for (int i = 0; i < numberOfAtoms; i++) {
+    newAtom = World::getInstance().createAtom();
+    *file >> type >> ws >> newAtom->x[0] >> ws >> newAtom->x[1] >> ws >> newAtom->x[2];
+    newAtom->setType(World::getInstance().getPeriode()->FindElement(type));
+  }
+}
+
+/**
+ * Saves the current state of the World into the given XYZ file.
+ *
+ * \param XYZ file
+ */
+void XyzParser::save(ostream* file) {
+  *file << World::getInstance().numAtoms() << endl << comment << endl;
+
+  vector<atom*> atoms = World::getInstance().getAllAtoms();
+  for(vector<atom*>::iterator it = atoms.begin(); it < atoms.end(); it++) {
+    *file << fixed << (*it)->getType()->symbol << "\t" << (*it)->x[0] << "\t" << (*it)->x[1] << "\t" << (*it)->x[2] << endl;
+  }
+}
Index: src/Parser/XyzParser.hpp
===================================================================
--- src/Parser/XyzParser.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Parser/XyzParser.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,28 @@
+/*
+ * XyzParser.hpp
+ *
+ *  Created on: Mar 2, 2010
+ *      Author: metzler
+ */
+
+#ifndef XYZPARSER_HPP_
+#define XYZPARSER_HPP_
+
+#include <string>
+#include "FormatParser.hpp"
+
+/**
+ * Parser for XYZ files.
+ */
+class XyzParser : public FormatParser {
+public:
+  XyzParser();
+  ~XyzParser();
+  void load(std::istream* file);
+  void save(std::ostream* file);
+
+private:
+  std::string comment;
+};
+
+#endif /* XYZPARSER_HPP_ */
Index: src/Patterns/Cacheable.hpp
===================================================================
--- src/Patterns/Cacheable.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Patterns/Cacheable.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -11,4 +11,8 @@
 #include "Patterns/Observer.hpp"
 #include <boost/function.hpp>
+#include <boost/shared_ptr.hpp>
+#include <iostream>
+
+#include "Helpers/Assert.hpp"
 
 #ifndef NO_CACHING
@@ -17,12 +21,112 @@
   class Cacheable : public Observer
   {
+    // we define the states of the cacheable so we can do very fast state-checks
+    class State{
+    public:
+      State(Cacheable *_owner) :
+        busy(false),
+        owner(_owner)
+        {}
+      virtual T getValue()=0;
+      virtual void invalidate()=0;
+      virtual bool isValid()=0;
+      virtual void enter()=0;
+      bool isBusy(){
+        return busy;
+      }
+    protected:
+      bool busy;
+      Cacheable *owner;
+    };
+
+    class InvalidState : public State{
+    public:
+      InvalidState(Cacheable *_owner):
+        State(_owner)
+        {}
+
+      virtual T getValue(){
+        // set the state to valid
+        State::owner->switchState(State::owner->validState);
+        // get the value from the now valid state
+        return State::owner->state->getValue();
+      }
+
+      virtual void invalidate(){
+        // nothing to do on this message
+      }
+
+      virtual bool isValid(){
+        return false;
+      }
+
+      virtual void enter(){
+        // nothing to do when entering this
+      }
+    };
+
+    class ValidState : public State{
+    public:
+      ValidState(Cacheable *_owner) :
+        State(_owner)
+        {}
+
+      virtual T getValue(){
+        return content;
+      }
+
+      virtual void invalidate(){
+        State::owner->switchState(State::owner->invalidState);
+      }
+
+      virtual bool isValid(){
+        return true;
+      }
+
+      virtual void enter(){
+        State::busy= true;
+        // as soon as we enter the valid state we recalculate
+        content = State::owner->recalcMethod();
+        State::busy = false;
+      }
+    private:
+      T content;
+    };
+
+    class DestroyedState : public State {
+    public:
+      DestroyedState(Cacheable *_owner) :
+        State(_owner)
+        {}
+
+      virtual T getValue(){
+        ASSERT(0,"Cannot get a value from a Cacheable after it's Observable has died");
+        // we have to return a grossly invalid reference, because no value can be produced anymore
+        return *(static_cast<T*>(0));
+      }
+
+      virtual void invalidate(){
+        ASSERT(0,"Cannot invalidate a Cacheable after it's Observable has died");
+      }
+
+      virtual bool isValid(){
+        ASSERT(0,"Cannot check validity of a Cacheable after it's Observable has died");
+        return false;
+      }
+
+      virtual void enter(){
+        // nothing to do when entering this state
+      }
+    };
+
+
+  typedef boost::shared_ptr<State> state_ptr;
+
   public:
     Cacheable(Observable *_owner, boost::function<T()> _recalcMethod);
     virtual ~Cacheable();
 
-    const bool isValid();
-    const T& operator*();
-    const bool operator==(const T&);
-    const bool operator!=(const T&);
+    const bool isValid() const;
+    const T operator*() const;
 
     // methods implemented for base-class Observer
@@ -30,11 +134,19 @@
     void subjectKilled(Observable *subject);
   private:
-    void checkValid();
-
-    T content;
+
+    void switchState(state_ptr newState);
+
+    mutable state_ptr state;
+    // pre-defined state so we don't have to construct to much
+    state_ptr invalidState;
+    state_ptr validState;
+    // destroyed state is not predefined, because we rarely enter that state and never leave
+
     Observable *owner;
-    bool valid;
-    bool canBeUsed;
+
     boost::function<T()> recalcMethod;
+
+    // de-activated copy constructor
+    Cacheable(const Cacheable&);
   };
 
@@ -43,8 +155,10 @@
   Cacheable<T>::Cacheable(Observable *_owner, boost::function<T()> _recalcMethod) :
     owner(_owner),
-    recalcMethod(_recalcMethod),
-    valid(false),
-    canBeUsed(true)
-  {
+    recalcMethod(_recalcMethod)
+  {
+    // create all states needed for this object
+    invalidState = state_ptr(new InvalidState(this));
+    validState = state_ptr(new ValidState(this));
+    state = invalidState;
     // we sign on with the best(=lowest) priority, so cached values are recalculated before
     // anybody else might ask for updated values
@@ -52,20 +166,19 @@
   }
 
-  template<typename T>
-  const T& Cacheable<T>::operator*(){
-    checkValid();
-    return content;
-  }
-
-  template<typename T>
-  const bool Cacheable<T>::operator==(const T& rval){
-    checkValid();
-    return (content == rval);
-  }
-
-  template<typename T>
-  const bool Cacheable<T>::operator!=(const T& rval){
-    checkValid();
-    return (content != rval);
+  // de-activated copy constructor
+  template<typename T>
+  Cacheable<T>::Cacheable(const Cacheable&){
+    ASSERT(0,"Cacheables should never be copied");
+  }
+
+  template<typename T>
+  const T Cacheable<T>::operator*() const{
+    // we can only use the cacheable when the owner is not changing at the moment
+    if(!owner->isBlocked()){
+      return state->getValue();
+    }
+    else{
+      return recalcMethod();
+    }
   }
 
@@ -77,26 +190,26 @@
 
   template<typename T>
-  const bool Cacheable<T>::isValid(){
-    return valid;
+  const bool Cacheable<T>::isValid() const{
+    return state->isValid();
   }
 
   template<typename T>
   void Cacheable<T>::update(Observable *subject) {
-    valid = false;
+    state->invalidate();
   }
 
   template<typename T>
   void Cacheable<T>::subjectKilled(Observable *subject) {
-    valid = false;
-    canBeUsed = false;
-  }
-
-  template<typename T>
-  void Cacheable<T>::checkValid(){
-    assert(canBeUsed && "Cacheable used after owner was deleted");
-    if(!isValid()){
-      content = recalcMethod();
-    }
-  }
+    state_ptr destroyed = state_ptr(new DestroyedState(this));
+    switchState(destroyed);
+  }
+
+  template<typename T>
+  void Cacheable<T>::switchState(state_ptr newState){
+    ASSERT(!state->isBusy(),"LOOP DETECTED: Cacheable state switched while recalculating.\nDid the recalculation trigger the Observable?");
+    state = newState;
+    state->enter();
+  }
+
 #else
   template<typename T>
@@ -107,8 +220,6 @@
     virtual ~Cacheable();
 
-    const bool isValid();
-    const T& operator*();
-    const bool operator==(const T&);
-    const bool operator!=(const T&);
+    const bool isValid() const;
+    const T operator*() const;
 
     // methods implemented for base-class Observer
@@ -126,16 +237,6 @@
 
   template<typename T>
-  const T& Cacheable<T>::operator*(){
+  const T Cacheable<T>::operator*() const{
     return recalcMethod();
-  }
-
-  template<typename T>
-  const bool Cacheable<T>::operator==(const T& rval){
-    return (recalcMethod() == rval);
-  }
-
-  template<typename T>
-  const bool Cacheable<T>::operator!=(const T& rval){
-    return (recalcMethod() != rval);
   }
 
@@ -145,5 +246,5 @@
 
   template<typename T>
-  const bool Cacheable<T>::isValid(){
+  const bool Cacheable<T>::isValid() const{
     return true;
   }
@@ -151,10 +252,10 @@
   template<typename T>
   void Cacheable<T>::update(Observable *subject) {
-    assert(0 && "Cacheable::update should never be called when caching is disabled");
-  }
-
-  template<typename T>
-  void Cacheable<T>::subjectKilled(Observable *subject) {
-    assert(0 && "Cacheable::subjectKilled should never be called when caching is disabled");
+    ASSERT(0, "Cacheable::update should never be called when caching is disabled");
+  }
+
+  template<typename T>
+  void Cacheable<T>::subjectKilled(Observable *subject){
+    ASSERT(0, "Cacheable::subjectKilled should never be called when caching is disabled");
   }
 #endif
Index: src/Patterns/Observer.cpp
===================================================================
--- src/Patterns/Observer.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Patterns/Observer.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,5 +10,6 @@
 
 #include <iostream>
-#include <cassert>
+
+#include "Helpers/Assert.hpp"
 
 using namespace std;
@@ -24,13 +25,18 @@
 // See [Gamma et al, 1995] p. 297
 
-map<Observable*, int> Observable::depth;
-map<Observable*,multimap<int,Observer*>*> Observable::callTable;
-set<Observable*> Observable::busyObservables;
-
-// The two functions start_observer_internal and finish_observer_internal
-// have to be used together at all time. Never use these functions directly
-// START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
-// thus producing compiler-errors whenever only one is used
-
+map<Observable*, int> Observable::depth;  //!< Map of Observables to the depth of the DAG of Observers
+map<Observable*,multimap<int,Observer*> > Observable::callTable; //!< Table for each Observable of all its Observers
+std::map<Observable*,std::set<Notification*> > Observable::notifications;
+set<Observable*> Observable::busyObservables; //!< Set of Observables that are currently busy notifying their sign-on'ed Observers
+
+/** Attaching Sub-observables to Observables.
+ * Increases entry in Observable::depth for this \a *publisher by one.
+ *
+ * The two functions \sa start_observer_internal() and \sa finish_observer_internal()
+ * have to be used together at all time. Never use these functions directly
+ * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
+ * thus producing compiler-errors whenever only one is used.
+ * \param *publisher reference of sub-observable
+ */
 void Observable::start_observer_internal(Observable *publisher){
   // increase the count for this observable by one
@@ -40,4 +46,14 @@
 }
 
+/** Detaching Sub-observables from Observables.
+ * Decreases entry in Observable::depth for this \a *publisher by one. If zero, we
+ * start notifying all our Observers.
+ *
+ * The two functions start_observer_internal() and finish_observer_internal()
+ * have to be used together at all time. Never use these functions directly
+ * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
+ * thus producing compiler-errors whenever only one is used.
+ * \param *publisher reference of sub-observable
+ */
 void Observable::finish_observer_internal(Observable *publisher){
   // decrease the count for this observable
@@ -53,4 +69,15 @@
 }
 
+void Observable::enque_notification_internal(Observable *publisher, Notification_ptr notification){
+  ASSERT(notification->owner==publisher,"Some object tried to send a notification it does not own");
+  notifications[publisher].insert(notification);
+}
+
+/** Constructor for Observable Protector.
+ * Basically, calls start_observer_internal(). Hence use this class instead of
+ * calling the function directly.
+ *
+ * \param *protege Observable to be protected.
+ */
 Observable::_Observable_protector::_Observable_protector(Observable *_protege) :
   protege(_protege)
@@ -59,4 +86,10 @@
 }
 
+/** Destructor for Observable Protector.
+ * Basically, calls finish_observer_internal(). Hence use this class instead of
+ * calling the function directly.
+ *
+ * \param *protege Observable to be protected.
+ */
 Observable::_Observable_protector::~_Observable_protector()
 {
@@ -66,5 +99,8 @@
 /************* Notification mechanism for observables **************/
 
-
+/** Notify all Observers of changes.
+ * Puts \a *this into Observable::busyObservables, calls Observer::update() for all in callee_t
+ * and removes from busy list.
+ */
 void Observable::notifyAll() {
   // we are busy notifying others right now
@@ -73,19 +109,38 @@
   // see if anyone has signed up for observation
   // and call all observers
-  if(callTable.count(this)) {
-    // elements are stored sorted by keys in the multimap
-    // so iterating over it gives us a the callees sorted by
-    // the priorities
-    callees_t *callees = callTable[this];
-    callees_t::iterator iter;
-    for(iter=callees->begin();iter!=callees->end();iter++){
-      (*iter).second->update(this);
-    }
-  }
-  // done with notification, we can leave the set of busy subjects
+  try {
+    if(callTable.count(this)) {
+      // elements are stored sorted by keys in the multimap
+      // so iterating over it gives us a the callees sorted by
+      // the priorities
+      callees_t callees = callTable[this];
+      callees_t::iterator iter;
+      for(iter=callees.begin();iter!=callees.end();++iter){
+        (*iter).second->update(this);
+      }
+    }
+  }
+  ASSERT_NOCATCH("Exception thrown from Observer Update");
+
+  // send out all notifications that need to be done
+
+  notificationSet currentNotifications = notifications[this];
+  for(notificationSet::iterator it = currentNotifications.begin();
+      it != currentNotifications.end();++it){
+    (*it)->notifyAll();
+  }
+
+  notifications.erase(this);
+
+   // done with notification, we can leave the set of busy subjects
   busyObservables.erase(this);
 }
 
-// this handles passing on updates from sub-Observables
+
+/** Handles passing on updates from sub-Observables.
+ * Mimicks basically the Observer::update() function.
+ *
+ * \param *publisher The \a *this we observe.
+ */
 void Observable::update(Observable *publisher) {
   // circle detection
@@ -94,7 +149,7 @@
     // observers, but still we are called by one of our sub-Observables
     // we cannot be sure observation will still work at this point
-    cerr << "Circle detected in observation-graph." << endl;
-    cerr << "Observation-graph always needs to be a DAG to work correctly!" << endl;
-    cerr << "Please check your observation code and fix this!" << endl;
+    ASSERT(0,"Circle detected in observation-graph.\n"
+             "Observation-graph always needs to be a DAG to work correctly!\n"
+             "Please check your observation code and fix this!\n");
     return;
   }
@@ -109,64 +164,127 @@
 }
 
-// methods to sign-on and off
+/** Sign on an Observer to this Observable.
+ * Puts \a *target into Observable::callTable list.
+ * \param *target Observer
+ * \param priority number in [-20,20]
+ */
 void Observable::signOn(Observer *target,int priority) {
-  assert(priority>=-20 && priority<=+20 && "Priority out of range [-20:+20]");
+  ASSERT(priority>=-20 && priority<=+20, "Priority out of range [-20:+20] when signing on Observer");
   bool res = false;
-  callees_t *callees = 0;
-  if(callTable.count(this)){
-    callees = callTable[this];
-  }
-  else {
-    callees = new multimap<int,Observer*>;
-    callTable.insert(pair<Observable*,callees_t*>(this,callees));
-  }
+  callees_t &callees = callTable[this];
 
   callees_t::iterator iter;
-  for(iter=callees->begin();iter!=callees->end();iter++){
+  for(iter=callees.begin();iter!=callees.end();++iter){
     res |= ((*iter).second == target);
   }
   if(!res)
-    callees->insert(pair<int,Observer*>(priority,target));
-}
-
+    callees.insert(pair<int,Observer*>(priority,target));
+}
+
+/** Sign off an Observer from this Observable.
+ * Removes \a *target from Observable::callTable list.
+ * \param *target Observer
+ */
 void Observable::signOff(Observer *target) {
-  assert(callTable.count(this) && "SignOff called for an Observable without Observers.");
-  callees_t *callees = callTable[this];
+  ASSERT(callTable.count(this),"SignOff called for an Observable without Observers.");
+  callees_t &callees = callTable[this];
   callees_t::iterator iter;
-  for(iter=callees->begin();iter!=callees->end();iter++) {
-    if((*iter).second == target)
-      callees->erase(iter);
-  }
-  if(callees->empty()){
+  callees_t::iterator deliter;
+  for(iter=callees.begin();iter!=callees.end();) {
+    if((*iter).second == target) {
+      callees.erase(iter++);
+    }
+    else {
+      ++iter;
+    }
+  }
+  if(callees.empty()){
     callTable.erase(this);
-    delete callees;
-  }
-}
-
-// when an sub-observerable dies we usually don't need to do anything
+  }
+}
+
+void Observable::signOn(Observer *target, Notification_ptr notification){
+  ASSERT(notification->owner==this,
+         "Trying to sign on for a notification that is not provided by this object");
+
+  notification->addObserver(target);
+}
+
+void Observable::signOff(Observer *target, Notification_ptr notification){
+  ASSERT(notification->owner==this,
+         "Trying to sign off from a notification that is not provided by this object");
+
+  notification->removeObserver(target);
+}
+
+bool Observable::isBlocked(){
+  return depth.count(this) > 0;
+}
+
+/** Handles sub-observables that just got killed
+ *  when an sub-observerable dies we usually don't need to do anything
+ *  \param *publisher Sub-Observable.
+ */
 void Observable::subjectKilled(Observable *publisher){
 }
 
+/** Constructor for class Observable.
+ */
 Observable::Observable()
 {}
 
-// when an observable is deleted, we let all our observers know
+/** Destructor for class Observable.
+ * When an observable is deleted, we let all our observers know. \sa Observable::subjectKilled().
+ */
 Observable::~Observable()
 {
   if(callTable.count(this)) {
     // delete all entries for this observable
-    callees_t *callees = callTable[this];
+    callees_t callees = callTable[this];
     callees_t::iterator iter;
-    for(iter=callees->begin();iter!=callees->end();iter++){
+    for(iter=callees.begin();iter!=callees.end();++iter){
       (*iter).second->subjectKilled(this);
     }
     callTable.erase(this);
-    delete callees;
-  }
-}
-
+  }
+}
+
+/** Constructor for class Observer.
+ */
 Observer::Observer()
 {}
 
+/** Destructor for class Observer.
+ */
 Observer::~Observer()
 {}
+
+/**
+ * Method for specialized notifications.
+ * Most Observers wont need or use this, so it is implemented
+ * empty in the base case;
+ */
+void Observer::recieveNotification(Observable *publisher, Notification_ptr notification){
+  ASSERT(0,"Notification received by object that did not sign on for it.");
+}
+
+Notification::Notification(Observable *_owner) :
+    owner(_owner)
+{}
+
+Notification::~Notification(){}
+
+void Notification::addObserver(Observer *target){
+  targets.insert(target);
+}
+
+void Notification::removeObserver(Observer *target){
+  targets.erase(target);
+}
+
+void Notification::notifyAll(){
+  for(std::set<Observer*>::iterator it=targets.begin();
+      it!=targets.end();++it){
+    (*it)->recieveNotification(owner,this);
+  }
+}
Index: src/Patterns/Observer.hpp
===================================================================
--- src/Patterns/Observer.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Patterns/Observer.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -16,5 +16,5 @@
  *
  * Observers register themselves with the observables to be notified when something changes.
- * In the Observable code that changes attributes should be started with OBSERVE;. This macro
+ * In the Observable code that changes, attributes should be started with OBSERVE;. This macro
  * locks the observer mechanism while changes are done. At the end of the scope in which the
  * macro was placed the lock is released. When the last lock is released all changes are
@@ -29,8 +29,28 @@
 
 class Observable;
+class Notification;
 
+// Pointers to notifications are used for unique identification
+// using this typedef makes it hard for others to mess up this
+// identification process
+typedef Notification *const Notification_ptr;
+
+/**
+ * An Observer is notified by all Observed objects, when anything changes.
+ *
+ * If a simple change is done to an Object the Obervable will call the update() method
+ * of all signed on observers, passing itself as a parameter for identification. The
+ * Observers should then react to the changes and update themselves accordingly.
+ *
+ * If an observed Object is destroyed it will call the subjectKilled() method
+ * of all signed on Observers, again passing itself as a parameter for identification.
+ * The Observers should handle the destruction of an observed Object gracefully, i.e.
+ * set themselves inactive, display something else, etc. There is no need
+ * to sign of from the dying object, since this will be handled by the Observable destructor.
+ */
 class Observer
 {
   friend class Observable;
+  friend class Notification;
 public:
   Observer();
@@ -38,8 +58,30 @@
 
 protected:
+  /**
+   * This method is called upon changes of the Observable
+   */
   virtual void update(Observable *publisher)=0;
+
+  /**
+   * This method is called when a special named change
+   * of the Observable occured
+   */
+  virtual void recieveNotification(Observable *publisher, Notification_ptr notification);
+
+  /**
+   * This method is called when the observed object is destroyed.
+   */
   virtual void subjectKilled(Observable *publisher)=0;
 };
 
+/**
+ * An Observable implements all neccessary method for being observed.
+ *
+ * That is, it provides methods for signing on and of from an
+ * Observable that can be used by any observer. The actual
+ * observer-mechanism is handled at a central static place
+ * to avoid memory issues when many observable are around but only few
+ * are actually observed.
+ */
 class Observable : public Observer {
 public:
@@ -47,6 +89,38 @@
   virtual ~Observable();
 
+  /**
+   * Sign an Observer on to this Observable. The Observer will be notified
+   * whenever something inside the Observable changes. The Observer can
+   * assign itself a priority for the changes in the range of -20:+20.
+   * The Observer with lower priority will be called before the others,
+   * same as with Unix nice-levels. This can be used when an Object
+   * contains other objects that observe it (derived values), and these objects have
+   * to recalculate their states before the changes should be propageted to the
+   * UI. A default priority of 0 should be fine in most cases, since there is
+   * ussually no need to order the update sequence.
+   */
   virtual void signOn(Observer *target, int priority=0);
+
+  /**
+   * Sign of a previously signed on Observer. After this no more
+   * updates will be recieved from that observer.
+   */
   virtual void signOff(Observer *target);
+
+  /**
+   * Sign on for specialized notifications
+   */
+  virtual void signOn(Observer *target, Notification_ptr notification);
+
+  /**
+   * Stop receiving a specialized notification
+   */
+  virtual void signOff(Observer *target, Notification_ptr notification);
+
+  /**
+   * Ask an Observer if it is currently in a blocked state, i.e. if
+   * Changes are in Progress, that are not yet published.
+   */
+  virtual bool isBlocked();
 
 protected:
@@ -68,12 +142,23 @@
   static void finish_observer_internal(Observable *publisher);
 
+  static void enque_notification_internal(Observable *publisher, Notification_ptr notification);
+
 private:
   typedef std::multimap<int,Observer*> callees_t;
+  typedef std::set<Notification*> notificationSet;
   static std::map<Observable*, int> depth;
-  static std::map<Observable*,callees_t*> callTable;
+  static std::map<Observable*,callees_t> callTable;
+  static std::map<Observable*,notificationSet> notifications;
   static std::set<Observable*> busyObservables;
 
+
+  //! @cond
   // Structure for RAII-Style notification
 protected:
+  /**
+   * This structure implements the Observer-mechanism RAII-Idiom.
+   * It triggers certain functions on creation and destruction so that
+   * Observer mechanisms can be linked to scope block.
+   */
   class _Observable_protector {
   public:
@@ -83,4 +168,21 @@
     Observable *protege;
   };
+  //! @endcond
+};
+
+class Notification {
+  friend class Observable;
+public:
+  Notification(Observable *_owner);
+  virtual ~Notification();
+protected:
+
+  void addObserver(Observer *target);
+  void removeObserver(Observer *target);
+
+  void notifyAll();
+private:
+  Observable * const owner;
+  std::set<Observer*> targets;
 };
 
@@ -89,7 +191,5 @@
 #define PASTE_HELPER(a,b) a ## b
 #define OBSERVE Observable::_Observable_protector PASTE(_scope_obs_protector_,__LINE__)(this)
-// deprecated macros from before RAII was used
-//#define START_OBSERVER Observable::start_observer_internal(this);do{do{}while(0)
-//#define FINISH_OBSERVER }while(0);Observable::finish_observer_internal(this)
-//#define RETURN_OBSERVER( retval ) do{Observable::finish_observer_internal(this); return (retval);}while(0)
+#define NOTIFY(notification) do{Observable::enque_notification_internal(this,notification);}while(0)
+
 #endif /* OBSERVER_HPP_ */
Index: src/Patterns/Singleton.hpp
===================================================================
--- src/Patterns/Singleton.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Patterns/Singleton.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,278 @@
+/*
+ * Singleton.hpp
+ *
+ *  Created on: Mar 10, 2010
+ *      Author: crueger
+ */
+
+#ifndef SINGLETON_HPP_
+#define SINGLETON_HPP_
+
+#include <cassert>
+#include <boost/thread.hpp>
+
+#include "defs.hpp"
+
+/**
+ * This template produces the generic singleton pattern using the CRTP idiom.
+ *
+ * <h1> Singleton Howto </h1>
+ * <h2> Introduction </h2>
+ *
+ * A Singleton is a class of which there can only be a single Object in the programm. It is
+ * described as an design-pattern in Gof:96 (the famous design-pattern book). In the
+ * molecuilder there are so far several Singletons serving a wide range of purposes:
+ *
+ * - the World, which handles all atoms, molecules and bonds
+ * - the ActionRegistry, which stores all created actions by name for later use
+ * - the UIFactory, which is an AbstractFactory (another design-pattern from Gof:96) and
+ *   handles all creation of gui elements to ensure a single type throughout the programm
+ * - the logger and errorLogger classes, that can be used to output messages on the screen
+ *   depending on certain conditions
+ *
+ * Because those classes can only be instantiated once you cannot simply call <code>new World()</code>
+ * or <code>delete</code> on them. Rather they have to be constructed and accessed using the singleton
+ * mechanism. This mechanism consists of four static functions (and a fifth that is used internally,
+ * but we will get to that later). These functions are:
+ *
+ * - <code>Singleton& Singleton::getInstance()</code> : returns the instance of the singleton as
+ *    a reference
+ * - <code>Singleton* Singleton::getPointer()</code> : returns the instance of the singleton as a
+ *    pointer
+ * - <code>void Singleton::purgeInstance()</code> : destroys the single Instance of the singleton
+ * - <code>Singleton& Singleton::resetInstance()</code> : resets the Singleton, i.e. destroys the
+ *    old instance and creates a new one
+ *
+ * If you need the instance of the singleton it is usually fine just to use one off the accessor
+ * functions (i.e. <code>getInstance()</code> or <code>getPointer()</code>. Any creation of the
+ * Singleton is then handled by these functions, so that the same object will be returned whenever
+ * one of these functions is called. This easy process is true for most singletons you will need
+ * to use. The only special singleton is the UIFactory.
+ *
+ * <h3>Special functions of the UIFactory</h3>
+ *
+ * If you simply call the <code>getInstance()</code> method of the UIFactory class the program
+ * will crash. This happens, because the UIFactory in itself is abstract and needs to know what
+ * kind of user interface it should produce later on. You need to tell the class the type of UI
+ * using the void <code>UIFactory::makeUserInterface(InterfaceTypes type)</code> method. This will
+ * also take care of creating the sole instance, so that the accessor functions will work afterwards.
+ * What this also means is, that you cannot <code>reset()</code> the UIFactory, because at that
+ * point it wont know anymore what to construct. A sequence of <code>UIFactory::purgeInstance()</code>,
+ * <code>UIFactory::makeUserInterface()</code> and <code>UIFactory::getInstance()</code> will work
+ * though.
+ *
+ * In order to make life easier and propagate changes to the singleton mechanism to all those
+ * classes, there is a simple framework class that can be used to make any other class a
+ * singleton through inheritance. This class can be found in the Pattern directory.
+ *
+ * <h2>How to make a class Singleton</h2>
+ *
+ * Most of the time you will only need singletons that don't require additional
+ * information for creation. So I will cover the basic case for constructing singletons
+ * first and then explain what has to be changed to make it accept special parameters.
+ * Singletons are created by inheriting from the <code>Singleton<class T></code> template
+ * using the Curiously recurring template pattern (CRTP). What this means is, that the
+ * class they inherit from carries the inheriting class as a template parameter. For example
+ * <code>class MySingletonExaple : public Singleton<MySingletonExample>{...}</code>. If you
+ * want to know more about this idiom have a look at the
+ * <A HREF="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern">wikipedia
+ * page for this idiom</A>, but don't worry if you don't quite get how this works for now, for
+ * the use of the singleton framework this is not important.
+ *
+ * If you want to make a class a singleton you can use the following sequence of steps.
+ *
+ * - Inherit from the singleton pattern using the CRTP as above:<br>
+ *   @code
+ *     class MySingletonExaple : public Singleton<MySingletonExample>{ ...}
+ *   @endcode
+ * - Make constructor and destructor private to avoid creation or destruction from
+ *   outside the class:<br>
+ *    @code
+ *      class MySingletonExaple : public Singleton<MySingletonExample>{
+ *        private:
+ *          MySingletonExample();
+ *          ~MySingletonExample();
+ *      ...}
+ *    @endcode
+ * - give the inherited class access to the class internals using a friend declaration:<br>
+ *    @code
+ *       class MySingletonExaple : public Singleton<MySingletonExample>{
+ *         friend class Singleton<MySingletonExample>; // don't forget the template parameters here
+ *         private:
+ *           MySingletonExample();
+ *           ~MySingletonExample();
+ *       ...}
+ *    @endcode
+ *
+ * - include the file "Patterns/Singleton_impl.hpp" that carries the implementation details of
+ *   the singleton functions in your implementation file of the class.
+ * - make the compiler construct the template instantiations. For this you can use the defined
+ *   keyword <code>CONSTRUCT_SINGLETON(name)</code> at any toplevel point in the implementation
+ *   file:<br>
+ *    @code
+ *       void MySingletonExample::foo(){...}
+ *       void MySingletonExample::bar(){...}
+ *       CONSTRUCT_SINGLETON(MySingletonExample) // no ; after this
+ *     @endcode
+ *
+ * <h3>Singleton with initialization parameters</h3>
+ *
+ * Sometimes it is necessary for a singleton to be passed some initilization parameters. For
+ * example the UIFactory mentioned above needs to know what kind of user interface it has to
+ * produce. Making a singleton that takes initialization parameters is only sligtly different
+ * from the steps lined out above. Here are all the differences:
+ *
+ * - pass an extra <code>false</code> to the template to deactivate the standard instantiation
+ *   mechanism
+ * - write a method that handles the special parameters and instantiation. In this method you
+ *   can use the <code>setInstance(T*)</code> method inherited from the singleton pattern to set
+ *   the created instance. The <code>setInstance()</code> method will only work when the
+ *   <code>false<code> template parameter has been set and produce errors otherwise.
+ *
+ */
+template <class T, bool _may_create=true>
+class Singleton
+{
+private:
+  /**
+   * simple auto_ptr that is used by Singleton template
+   *
+   * This ptr_t allows destruction of the object using a private destructor,
+   * when only the Singleton pattern is friend with the class
+   *
+   * All methods have similar sematics to auto_ptr
+   */
+  class ptr_t {
+  public:
+    ptr_t();
+    ptr_t(T* _content);
+    ~ptr_t();
+    T& operator*();
+    T* get();
+    void reset(T* _content);
+    void reset();
+    ptr_t& operator=(const ptr_t& rhs);
+  private:
+    mutable T* content;
+  };
+
+  /**
+   * This object handles the actual creation inside the singleton
+   *
+   * Using template specialization this will allways know what it can
+   * do or cannot do at compile time
+   */
+  template<class creator_T, bool creator_may_create>
+  struct creator_t {
+    inline static creator_T* make();
+    inline static void set(creator_T*&,creator_T*);
+  };
+
+  // specialization to allow fast creations
+
+  /**
+   * Specialized template that allows automatic construction only
+   */
+  template<class creator_T>
+  struct creator_t<creator_T,true>{
+    inline static creator_T* make(){
+      return new creator_T();
+    }
+
+    inline static void set(creator_T*&,creator_T*){
+      assert(0 && "Cannot set the Instance for a singleton of this type");
+    }
+  };
+
+  /**
+   * specialized template that allows setting only
+   */
+  template<class creator_T>
+  struct creator_t<creator_T,false>{
+    inline static creator_T* make(){
+      assert(0 && "Cannot create a singleton of this type directly");
+    }
+    inline static void set(ptr_t& dest,creator_T* src){
+      dest.reset(src);
+    }
+  };
+
+  // this is used for creation
+  typedef creator_t<T,_may_create> creator; //< the creator used
+
+public:
+  // make the state of this singleton accessible
+  static const bool may_create=_may_create; //!< the type of singleton that we have
+
+  /**
+   * returns the instance of this Singleton as a reference
+   *
+   * If no Singleton exists at this point and we are allowed to create one
+   * a new one is created and stored inside the singleton
+   *
+   * If no automatic creation is allowed, make sure to create an instance first
+   * using the appropriate methods of the derived class. Otherwise this method
+   * would fail.
+   */
+  static T& getInstance();
+
+  /**
+   * returns the instance of this singleton as a pointer
+   *
+   * If no Singleton exists at this point and we are allowed to create one
+   * a new one is created and stored inside the singleton.
+   *
+   * If no automatic creation is allowed, make sure to create an instance first
+   * using the appropriate methods of the derived class. Otherwise this method
+   * would fail.
+   */
+  static T* getPointer();
+
+  /**
+   * destroys the current instance of this singleton
+   */
+  static void purgeInstance();
+
+  /**
+   * destroys the current instance of the singleton and immidiately constructs
+   * a new one. Similar to using <code>purgeInstance()</code> and <code>getInstance()</code>
+   * but plays more nicely when observers are present. Especially the new instance is created
+   * before the old one is destroyed so observers can switch their targets, when they are notified
+   * of the destruction.
+   *
+   * If no automatic creation is allowed this method wont work.
+   */
+  static T&   resetInstance();
+
+protected:
+  /**
+   * Method used to set the instance, when no automatic creation is allowed.
+   *
+   * Call this after the instantiation method in the derived class has created
+   * it's instance and want's the singleton mechanism to keep it around for later
+   * use.
+   *
+   * This method will always fail when automatic creation is enabled.
+   */
+  static void setInstance(T*);
+
+
+  /**
+   * empty constructor to allow creation of subclases
+   */
+  Singleton();
+
+private:
+  /**
+   * the copy constructor is private to avoid accidental copying of Singletons, for example
+   * when passing singletons to functions by value instead of by reference. If you
+   * need copying of singletons call the default constructor in the copy constructor
+   * of the derived object. The copyied object wont be known to the singleton mechanism.
+   */
+  Singleton(const Singleton&);
+
+  static boost::recursive_mutex instanceLock; //!< a lock for the pointer of the instance
+  static ptr_t theInstance; //!< the actual instance of the singleton
+};
+
+#endif /* SINGLETON_HPP_ */
Index: src/Patterns/Singleton_impl.hpp
===================================================================
--- src/Patterns/Singleton_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Patterns/Singleton_impl.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,142 @@
+/*
+ * Singleton_impl.hpp
+ *
+ *  Created on: Mar 10, 2010
+ *      Author: crueger
+ */
+
+#ifndef SINGLETON_IMPL_HPP_
+#define SINGLETON_IMPL_HPP_
+
+#include "Patterns/Singleton.hpp"
+
+/****** Static instance Variables of the template *******/
+
+template <class T,bool _may_create>
+typename Singleton<T,_may_create>::ptr_t Singleton<T,_may_create>::theInstance(0);
+
+template <class T,bool _may_create>
+boost::recursive_mutex Singleton<T,_may_create>::instanceLock;
+
+/****** templates singleton creation and destruction functions ******/
+
+template <class T,bool _may_create>
+T& Singleton<T,_may_create>::getInstance(){
+  // boost supports RAII-Style locking, so we don't need to unlock
+  boost::recursive_mutex::scoped_lock guard(instanceLock);
+  if(!theInstance.get()) {
+    theInstance.reset(creator::make());
+  }
+  return *theInstance;
+}
+
+template <class T,bool _may_create>
+T* Singleton<T,_may_create>::getPointer(){
+  // boost supports RAII-Style locking, so we don't need to unlock
+  boost::recursive_mutex::scoped_lock guard(instanceLock);
+  if(!theInstance.get()) {
+    theInstance.reset(creator::make());
+  }
+  return theInstance.get();
+
+}
+
+template <class T,bool _may_create>
+void Singleton<T,_may_create>::purgeInstance(){
+  // boost supports RAII-Style locking, so we don't need to unlock
+  boost::recursive_mutex::scoped_lock guard(instanceLock);
+  theInstance.reset();
+}
+
+template <class T,bool _may_create>
+T& Singleton<T,_may_create>::resetInstance(){
+  ptr_t oldInstance;
+  {
+    // boost supports RAII-Style locking, so we don't need to unlock
+    boost::recursive_mutex::scoped_lock guard(instanceLock);
+
+    oldInstance = theInstance;
+    theInstance.reset(creator::make());
+    // oldworld does not need protection any more,
+    // since we should have the only reference
+
+    // worldLock handles access to the pointer,
+    // not to the object
+  } // scope-end releases the lock
+
+  // oldInstance goes out of scope at the End of this function. The carried object will then be destroyed by the auto_ptr
+  return *theInstance;
+}
+
+
+template <class T,bool _may_create>
+void Singleton<T,_may_create>::setInstance(T* newInstance){
+  assert(!theInstance.get() && "Trying to set the instance of an already created singleton");
+  boost::recursive_mutex::scoped_lock guard(instanceLock);
+  theInstance.reset(newInstance);
+}
+
+template<class T, bool _may_create>
+Singleton<T,_may_create>::Singleton(){/* empty */}
+
+// private copy constructor to avoid unintended copying
+template <class T, bool _may_create>
+Singleton<T,_may_create>::Singleton(const Singleton<T,_may_create>&){
+  assert(0 && "Copy constructor of singleton template called");
+}
+
+/**
+ * This define allows simple instantiation of the necessary singleton functions
+ * at a chosen place.
+ */
+#define CONSTRUCT_SINGLETON(name) \
+    template name& Singleton< name , name::may_create >::getInstance(); \
+    template name* Singleton< name , name::may_create >::getPointer();  \
+    template void  Singleton< name , name::may_create >::purgeInstance(); \
+    template name& Singleton< name , name::may_create >::resetInstance(); \
+    template void  Singleton< name , name::may_create >::setInstance( name* );
+
+/************ Internal Pointer Wrapper to allow automatic purging *************/
+
+template <class T,bool _may_create>
+Singleton<T,_may_create>::ptr_t::ptr_t() :
+content(0){};
+
+template <class T,bool _may_create>
+Singleton<T,_may_create>::ptr_t::ptr_t(T* _content) :
+content(_content){};
+
+template <class T,bool _may_create>
+Singleton<T,_may_create>::ptr_t:: ~ptr_t()
+{delete content;};
+
+template <class T,bool _may_create>
+T& Singleton<T,_may_create>::ptr_t::operator*()
+{return *content;};
+
+template <class T,bool _may_create>
+T* Singleton<T,_may_create>::ptr_t::get()
+{return content;};
+
+template <class T,bool _may_create>
+void Singleton<T,_may_create>::ptr_t::reset(T* _content){
+  delete content;
+  content = _content;
+}
+
+template <class T,bool _may_create>
+void Singleton<T,_may_create>::ptr_t::reset()
+{reset(0);}
+
+template <class T,bool _may_create>
+typename Singleton<T,_may_create>::ptr_t& Singleton<T,_may_create>::ptr_t::operator=(const typename Singleton<T,_may_create>::ptr_t& rhs){
+  if(&rhs!=this){
+    delete content;
+    content = rhs.content;
+    rhs.content = 0;
+  }
+  return *this;
+}
+
+
+#endif /* SINGLETON_IMPL_HPP_ */
Index: src/Plane.cpp
===================================================================
--- src/Plane.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Plane.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,198 @@
+/*
+ * Plane.cpp
+ *
+ *  Created on: Apr 7, 2010
+ *      Author: crueger
+ */
+
+#include "Plane.hpp"
+#include "vector.hpp"
+#include "defs.hpp"
+#include "info.hpp"
+#include "log.hpp"
+#include "verbose.hpp"
+#include "Helpers/Assert.hpp"
+#include <cmath>
+
+/**
+ * generates a plane from three given vectors defining three points in space
+ */
+Plane::Plane(const Vector &y1, const Vector &y2, const Vector &y3) throw(LinearDependenceException) :
+  normalVector(new Vector())
+{
+  Vector x1 = y1 -y2;
+  Vector x2 = y3 -y2;
+  if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(x2)) < MYEPSILON)) {
+    throw LinearDependenceException(__FILE__,__LINE__);
+  }
+//  Log() << Verbose(4) << "relative, first plane coordinates:";
+//  x1.Output((ofstream *)&cout);
+//  Log() << Verbose(0) << endl;
+//  Log() << Verbose(4) << "second plane coordinates:";
+//  x2.Output((ofstream *)&cout);
+//  Log() << Verbose(0) << endl;
+
+  normalVector->at(0) = (x1[1]*x2[2] - x1[2]*x2[1]);
+  normalVector->at(1) = (x1[2]*x2[0] - x1[0]*x2[2]);
+  normalVector->at(2) = (x1[0]*x2[1] - x1[1]*x2[0]);
+  normalVector->Normalize();
+
+  offset=normalVector->ScalarProduct(y1);
+}
+/**
+ * Constructs a plane from two direction vectors and a offset.
+ * If no offset is given a plane through origin is assumed
+ */
+Plane::Plane(const Vector &y1, const Vector &y2, double _offset) throw(ZeroVectorException,LinearDependenceException) :
+    normalVector(new Vector()),
+    offset(_offset)
+{
+  Vector x1 = y1;
+  Vector x2 = y2;
+  if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON)) {
+    throw ZeroVectorException(__FILE__,__LINE__);
+  }
+
+  if((fabs(x1.Angle(x2)) < MYEPSILON)) {
+    throw LinearDependenceException(__FILE__,__LINE__);
+  }
+//  Log() << Verbose(4) << "relative, first plane coordinates:";
+//  x1.Output((ofstream *)&cout);
+//  Log() << Verbose(0) << endl;
+//  Log() << Verbose(4) << "second plane coordinates:";
+//  x2.Output((ofstream *)&cout);
+//  Log() << Verbose(0) << endl;
+
+  normalVector->at(0) = (x1[1]*x2[2] - x1[2]*x2[1]);
+  normalVector->at(1) = (x1[2]*x2[0] - x1[0]*x2[2]);
+  normalVector->at(2) = (x1[0]*x2[1] - x1[1]*x2[0]);
+  normalVector->Normalize();
+}
+
+Plane::Plane(const Vector &_normalVector, double _offset) throw(ZeroVectorException):
+  normalVector(new Vector(_normalVector)),
+  offset(_offset)
+{
+  if(normalVector->IsZero())
+    throw ZeroVectorException(__FILE__,__LINE__);
+  double factor = 1/normalVector->Norm();
+  // normalize the plane parameters
+  (*normalVector)*=factor;
+  offset*=factor;
+}
+
+Plane::Plane(const Vector &_normalVector, const Vector &_offsetVector) throw(ZeroVectorException):
+    normalVector(new Vector(_normalVector))
+{
+  if(normalVector->IsZero()){
+    throw ZeroVectorException(__FILE__,__LINE__);
+  }
+  normalVector->Normalize();
+  offset = normalVector->ScalarProduct(_offsetVector);
+}
+
+Plane::~Plane()
+{}
+
+
+Vector Plane::getNormal() const{
+  return *normalVector;
+}
+
+double Plane::getOffset() const{
+  return offset;
+}
+
+Vector Plane::getOffsetVector() {
+  return getOffset()*getNormal();
+}
+
+vector<Vector> Plane::getPointsOnPlane(){
+  std::vector<Vector> res;
+  res.reserve(3);
+  // first point on the plane
+  res.push_back(getOffsetVector());
+  // get a vector that has direction of plane
+  Vector direction;
+  direction.GetOneNormalVector(getNormal());
+  res.push_back(res[0]+direction);
+  // get an orthogonal vector to direction and normal (has direction of plane)
+  direction.VectorProduct(getNormal());
+  direction.Normalize();
+  res.push_back(res[0] +direction);
+  return res;
+}
+
+
+/** Calculates the intersection point between a line defined by \a *LineVector and \a *LineVector2 and a plane defined by \a *Normal and \a *PlaneOffset.
+ * According to [Bronstein] the vectorial plane equation is:
+ *   -# \f$\stackrel{r}{\rightarrow} \cdot \stackrel{N}{\rightarrow} + D = 0\f$,
+ * where \f$\stackrel{r}{\rightarrow}\f$ is the vector to be testet, \f$\stackrel{N}{\rightarrow}\f$ is the plane's normal vector and
+ * \f$D = - \stackrel{a}{\rightarrow} \stackrel{N}{\rightarrow}\f$, the offset with respect to origin, if \f$\stackrel{a}{\rightarrow}\f$,
+ * is an offset vector onto the plane. The line is parametrized by \f$\stackrel{x}{\rightarrow} + k \stackrel{t}{\rightarrow}\f$, where
+ * \f$\stackrel{x}{\rightarrow}\f$ is the offset and \f$\stackrel{t}{\rightarrow}\f$ the directional vector (NOTE: No need to normalize
+ * the latter). Inserting the parametrized form into the plane equation and solving for \f$k\f$, which we insert then into the parametrization
+ * of the line yields the intersection point on the plane.
+ * \param *Origin first vector of line
+ * \param *LineVector second vector of line
+ * \return true -  \a this contains intersection point on return, false - line is parallel to plane (even if in-plane)
+ */
+Vector Plane::GetIntersection(const Vector &Origin, const Vector &LineVector)
+{
+  Info FunctionInfo(__func__);
+  Vector res;
+
+  // find intersection of a line defined by Offset and Direction with a  plane defined by triangle
+  Vector Direction = LineVector - Origin;
+  Direction.Normalize();
+  Log() << Verbose(1) << "INFO: Direction is " << Direction << "." << endl;
+  //Log() << Verbose(1) << "INFO: PlaneNormal is " << *PlaneNormal << " and PlaneOffset is " << *PlaneOffset << "." << endl;
+  double factor1 = Direction.ScalarProduct(*normalVector.get());
+  if (fabs(factor1) < MYEPSILON) { // Uniqueness: line parallel to plane?
+    Log() << Verbose(1) << "BAD: Line is parallel to plane, no intersection." << endl;
+    throw LinearDependenceException(__FILE__,__LINE__);
+  }
+
+  double factor2 = Origin.ScalarProduct(*normalVector.get());
+  if (fabs(factor2-offset) < MYEPSILON) { // Origin is in-plane
+    Log() << Verbose(1) << "GOOD: Origin of line is in-plane." << endl;
+    res = Origin;
+    return res;
+  }
+
+  double scaleFactor = (offset-factor2)/factor1;
+
+  //factor = Origin->ScalarProduct(PlaneNormal)*(-PlaneOffset->ScalarProduct(PlaneNormal))/(Direction.ScalarProduct(PlaneNormal));
+  Direction.Scale(scaleFactor);
+  res = Origin + Direction;
+  Log() << Verbose(1) << "INFO: Scaled direction is " << Direction << "." << endl;
+
+  // test whether resulting vector really is on plane
+  ASSERT(fabs(res.ScalarProduct(*normalVector) - offset) < MYEPSILON,
+         "Calculated line-Plane intersection does not lie on plane.");
+  return res;
+};
+
+/************ Methods inherited from Space ****************/
+
+double Plane::distance(const Vector &point) const{
+  double res = point.ScalarProduct(*normalVector)-offset;
+  return fabs(res);
+}
+
+Vector Plane::getClosestPoint(const Vector &point) const{
+  double factor = point.ScalarProduct(*normalVector)-offset;
+  if(fabs(factor) < MYEPSILON){
+    // the point itself lies on the plane
+    return point;
+  }
+  Vector difference = factor * (*normalVector);
+  return (point - difference);
+}
+
+// Operators
+
+ostream &operator << (ostream &ost,const Plane &p){
+  ost << "<" << p.getNormal() << ";x> - " << p.getOffset() << "=0";
+  return ost;
+}
Index: src/Plane.hpp
===================================================================
--- src/Plane.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Plane.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,65 @@
+/*
+ * Plane.hpp
+ *
+ *  Created on: Apr 7, 2010
+ *      Author: crueger
+ */
+
+#ifndef PLANE_HPP_
+#define PLANE_HPP_
+
+#include <memory>
+#include <vector>
+#include <iostream>
+#include "Space.hpp"
+#include "Exceptions/LinearDependenceException.hpp"
+#include "Exceptions/ZeroVectorException.hpp"
+
+class Vector;
+
+class Plane : public Space
+{
+  typedef std::auto_ptr<Vector> vec_ptr;
+public:
+  Plane(const Vector &y1, const Vector &y2, const Vector &y3) throw(LinearDependenceException);
+  Plane(const Vector &y1, const Vector &y2, double _offset) throw(ZeroVectorException,LinearDependenceException);
+  Plane(const Vector &_normalVector, double _offset)  throw(ZeroVectorException);
+  Plane(const Vector &_normalVector, const Vector &_offsetVector) throw(ZeroVectorException);
+  virtual ~Plane();
+
+  // Accessor Functions
+  /**
+   * returns normal Vector for a plane
+   */
+  Vector getNormal() const;
+  /**
+   * returns the distance of the plane from the origin
+   */
+  double getOffset() const;
+  /**
+   * returns a vector that points on the plane.
+   * Same as getOffset()*getNormal();
+   */
+  Vector getOffsetVector();
+
+  /**
+   * returns three seperate points on this plane
+   */
+  std::vector<Vector> getPointsOnPlane();
+
+  // some calculations
+  Vector GetIntersection(const Vector &Origin, const Vector &LineVector);
+
+  /****** Methods inherited from Space ***********/
+
+  virtual double distance(const Vector &point) const;
+  virtual Vector getClosestPoint(const Vector &point) const;
+
+private:
+  vec_ptr normalVector;
+  double offset;
+};
+
+std::ostream &operator<< (std::ostream &ost,const Plane& p);
+
+#endif /* PLANE_HPP_ */
Index: src/Space.cpp
===================================================================
--- src/Space.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Space.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,23 @@
+/*
+ * Space.cpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#include "Space.hpp"
+#include "vector.hpp"
+
+Space::Space()
+{}
+
+Space::~Space()
+{}
+
+bool Space::hasZero() const{
+  return isContained(zeroVec);
+}
+
+bool Space::isContained(const Vector &point) const{
+  return (distance(point)) < MYEPSILON;
+}
Index: src/Space.hpp
===================================================================
--- src/Space.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/Space.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,26 @@
+/*
+ * Space.hpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#ifndef SPACE_HPP_
+#define SPACE_HPP_
+
+class Vector;
+
+class Space
+{
+public:
+  Space();
+  virtual ~Space();
+
+  virtual double distance(const Vector &point) const=0;
+  virtual Vector getClosestPoint(const Vector &point) const=0;
+  virtual bool isContained(const Vector &point) const;
+  virtual bool hasZero() const;
+
+};
+
+#endif /* SPACE_HPP_ */
Index: src/UIElements/CommandLineDialog.cpp
===================================================================
--- src/UIElements/CommandLineDialog.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/UIElements/CommandLineDialog.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,172 @@
+/*
+ * CommandLineDialog.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+
+#include <cassert>
+#include <iostream>
+
+#include <Descriptors/MoleculeDescriptor.hpp>
+#include <Descriptors/MoleculeIdDescriptor.hpp>
+#include "UIElements/CommandLineDialog.hpp"
+
+#include "periodentafel.hpp"
+#include "atom.hpp"
+#include "CommandLineParser.hpp"
+#include "defs.hpp"
+#include "molecule.hpp"
+#include "log.hpp"
+#include "verbose.hpp"
+#include "World.hpp"
+
+using namespace std;
+
+
+CommandLineDialog::CommandLineDialog()
+{
+}
+
+CommandLineDialog::~CommandLineDialog()
+{
+}
+
+
+void CommandLineDialog::queryEmpty(const char* title, string _description){
+  registerQuery(new EmptyCommandLineQuery(title, _description));
+}
+
+void CommandLineDialog::queryInt(const char* title, int* target, string _description){
+  registerQuery(new IntCommandLineQuery(title,target, _description));
+}
+
+void CommandLineDialog::queryDouble(const char* title, double* target, string _description){
+  registerQuery(new DoubleCommandLineQuery(title,target, _description));
+}
+
+void CommandLineDialog::queryString(const char* title, string* target, string _description){
+  registerQuery(new StringCommandLineQuery(title,target, _description));
+}
+
+void CommandLineDialog::queryMolecule(const char* title, molecule **target, MoleculeListClass *molecules, string _description) {
+  registerQuery(new MoleculeCommandLineQuery(title,target,molecules, _description));
+}
+
+void CommandLineDialog::queryVector(const char* title, Vector *target,const double *const cellSize, bool check, string _description) {
+  registerQuery(new VectorCommandLineQuery(title,target,cellSize,check, _description));
+}
+
+void CommandLineDialog::queryElement(const char* title, const element **target, string _description){
+  registerQuery(new ElementCommandLineQuery(title,target, _description));
+}
+
+/************************** Query Infrastructure ************************/
+
+CommandLineDialog::EmptyCommandLineQuery::EmptyCommandLineQuery(string title, string _description) :
+    Dialog::EmptyQuery(title, _description)
+{}
+
+CommandLineDialog::EmptyCommandLineQuery::~EmptyCommandLineQuery() {}
+
+bool CommandLineDialog::EmptyCommandLineQuery::handle() {
+  cout << "Message of " << getTitle() << ":\n" << getDescription() << "\n";
+  return true;
+}
+
+CommandLineDialog::IntCommandLineQuery::IntCommandLineQuery(string title,int *_target, string _description) :
+    Dialog::IntQuery(title,_target, _description)
+{}
+
+CommandLineDialog::IntCommandLineQuery::~IntCommandLineQuery() {}
+
+bool CommandLineDialog::IntCommandLineQuery::handle() {
+  if (CommandLineParser::getInstance().vm.count(getTitle())) {
+    tmp = CommandLineParser::getInstance().vm[getTitle()].as<int>();
+    return true;
+  } else
+    return false;
+}
+
+CommandLineDialog::StringCommandLineQuery::StringCommandLineQuery(string title,string *_target, string _description) :
+    Dialog::StringQuery(title,_target, _description)
+{}
+
+CommandLineDialog::StringCommandLineQuery::~StringCommandLineQuery() {}
+
+bool CommandLineDialog::StringCommandLineQuery::handle() {
+  if (CommandLineParser::getInstance().vm.count(getTitle())) {
+    tmp = CommandLineParser::getInstance().vm[getTitle()].as<string>();
+    return true;
+  } else
+    return false;
+}
+
+CommandLineDialog::DoubleCommandLineQuery::DoubleCommandLineQuery(string title,double *_target, string _description) :
+    Dialog::DoubleQuery(title,_target, _description)
+{}
+
+CommandLineDialog::DoubleCommandLineQuery::~DoubleCommandLineQuery() {}
+
+bool CommandLineDialog::DoubleCommandLineQuery::handle() {
+  if (CommandLineParser::getInstance().vm.count(getTitle())) {
+    tmp = CommandLineParser::getInstance().vm[getTitle()].as<double>();
+    return true;
+  } else
+    return false;
+}
+
+CommandLineDialog::MoleculeCommandLineQuery::MoleculeCommandLineQuery(string title, molecule **_target, MoleculeListClass *_molecules, string _description) :
+    Dialog::MoleculeQuery(title,_target,_molecules, _description)
+{}
+
+CommandLineDialog::MoleculeCommandLineQuery::~MoleculeCommandLineQuery() {}
+
+bool CommandLineDialog::MoleculeCommandLineQuery::handle() {
+  int IdxOfMol = -1;
+  if (CommandLineParser::getInstance().vm.count(getTitle())) {
+    IdxOfMol = CommandLineParser::getInstance().vm[getTitle()].as<int>();
+    tmp = World::getInstance().getMolecule(MoleculeById(IdxOfMol));
+    return true;
+  } else
+    return false;
+}
+
+CommandLineDialog::VectorCommandLineQuery::VectorCommandLineQuery(string title, Vector *_target, const double *const _cellSize, bool _check, string _description) :
+    Dialog::VectorQuery(title,_target,_cellSize,_check, _description)
+{}
+
+CommandLineDialog::VectorCommandLineQuery::~VectorCommandLineQuery()
+{}
+
+bool CommandLineDialog::VectorCommandLineQuery::handle() {
+  vector<double> temp;
+  if (CommandLineParser::getInstance().vm.count(getTitle())) {
+    temp = CommandLineParser::getInstance().vm[getTitle()].as<vector<double> >();
+    assert((temp.size() == 3) && "Vector from command line does not have three components.");
+    tmp = new Vector;
+    for (int i=0;i<NDIM;i++)
+      tmp->at(i) = temp[i];
+    return true;
+  } else
+    return false;
+}
+
+
+CommandLineDialog::ElementCommandLineQuery::ElementCommandLineQuery(string title, const element **target, string _description) :
+    Dialog::ElementQuery(title,target, _description)
+{}
+
+CommandLineDialog::ElementCommandLineQuery::~ElementCommandLineQuery()
+{}
+
+bool CommandLineDialog::ElementCommandLineQuery::handle() {
+  int Z = -1;
+  if (CommandLineParser::getInstance().vm.count(getTitle())) {
+    Z = CommandLineParser::getInstance().vm[getTitle()].as<int>();
+    tmp = World::getInstance().getPeriode()->FindElement(Z);
+    return true;
+  } else
+    return false;
+}
Index: src/UIElements/CommandLineDialog.hpp
===================================================================
--- src/UIElements/CommandLineDialog.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/UIElements/CommandLineDialog.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,84 @@
+/*
+ * CommandLineDialog.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef COMMANDLINEDIALOG_HPP_
+#define COMMANDLINEDIALOG_HPP_
+
+#include <string>
+
+#include "UIElements/Dialog.hpp"
+
+/** CommandLineUIFactory implementation of the Dialog.
+ * The idea here is that for each query the parsed command line options are used instead.
+ */
+class CommandLineDialog : public Dialog
+{
+public:
+  CommandLineDialog();
+  virtual ~CommandLineDialog();
+
+  virtual void queryEmpty(const char *, std::string = "");
+  virtual void queryInt(const char *, int *, std::string = "");
+  virtual void queryString(const char*, std::string *, std::string = "");
+  virtual void queryDouble(const char*, double*, std::string = "");
+  virtual void queryMolecule(const char*,molecule**,MoleculeListClass*, std::string = "");
+  virtual void queryVector(const char*,Vector *,const double * const,bool, std::string = "");
+  virtual void queryElement(const char*,const element **, std::string = "");
+
+protected:
+  // specialized stuff for text queries
+  class EmptyCommandLineQuery : public Dialog::EmptyQuery {
+  public:
+    EmptyCommandLineQuery(std::string title, std::string _description = "");
+    virtual ~EmptyCommandLineQuery();
+    virtual bool handle();
+  };
+
+  class IntCommandLineQuery : public Dialog::IntQuery {
+  public:
+    IntCommandLineQuery(std::string title, int *_target, std::string _description = "");
+    virtual ~IntCommandLineQuery();
+    virtual bool handle();
+  };
+
+  class DoubleCommandLineQuery : public Dialog::DoubleQuery {
+  public:
+    DoubleCommandLineQuery(std::string title, double *_target, std::string _description = "");
+    virtual ~DoubleCommandLineQuery();
+    virtual bool handle();
+  };
+
+  class StringCommandLineQuery : public Dialog::StringQuery {
+  public:
+    StringCommandLineQuery(std::string title, std::string *_target, std::string _description = "");
+    virtual ~StringCommandLineQuery();
+    virtual bool handle();
+  };
+
+  class MoleculeCommandLineQuery : public Dialog::MoleculeQuery {
+  public:
+    MoleculeCommandLineQuery(std::string title, molecule **_target, MoleculeListClass *_molecules, std::string _description = "");
+    virtual ~MoleculeCommandLineQuery();
+    virtual bool handle();
+  };
+
+  class VectorCommandLineQuery : public Dialog::VectorQuery {
+  public:
+    VectorCommandLineQuery(std::string title,Vector *_target,const double *const _cellSize,bool _check, std::string _description = "");
+    virtual ~VectorCommandLineQuery();
+    virtual bool handle();
+  };
+
+  class ElementCommandLineQuery : public Dialog::ElementQuery {
+  public:
+    ElementCommandLineQuery(std::string title, const element **_target, std::string _description = "");
+    virtual ~ElementCommandLineQuery();
+    virtual bool handle();
+  };
+};
+
+#endif /* COMMANDLINEDIALOG_HPP_ */
Index: src/UIElements/CommandLineStatusIndicator.cpp
===================================================================
--- src/UIElements/CommandLineStatusIndicator.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/UIElements/CommandLineStatusIndicator.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,57 @@
+/*
+ * CommandLineStatusIndicator.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+
+#include "CommandLineStatusIndicator.hpp"
+
+#include <iostream>
+
+#include "Actions/Process.hpp"
+
+using namespace std;
+
+CommandLineStatusIndicator::CommandLineStatusIndicator()
+{
+  Process::AddObserver(this);
+}
+
+CommandLineStatusIndicator::~CommandLineStatusIndicator()
+{
+  Process::RemoveObserver(this);
+}
+
+void CommandLineStatusIndicator::update(Observable *subject){
+  Process *proc;
+  // we are only observing Processes
+  if((proc=dynamic_cast<Process*>(subject))){
+    // see what kind of progress we have to display
+    if(proc->getMaxSteps()>0){
+      if(!proc->doesStop()){
+        cout << "Busy (" << proc->getName() << ") ";
+        // we can show a percentage done
+        cout << (int)proc->getDoneRatio() << "% done" << endl;
+      }
+    }
+    else{
+      // we only show some kind of busy animation
+      if(proc->doesStart()){
+        cout << "Busy (" << proc->getName() << ")";
+      }
+      if(!proc->doesStop()){
+        cout << ".";
+      }
+      else {
+        cout << endl;
+      }
+    }
+  }
+}
+
+void CommandLineStatusIndicator::subjectKilled(Observable *subject){
+
+}
+
Index: src/UIElements/CommandLineStatusIndicator.hpp
===================================================================
--- src/UIElements/CommandLineStatusIndicator.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/UIElements/CommandLineStatusIndicator.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,26 @@
+/*
+ * CommandLineStatusIndicator.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef COMMANDLINESTATUSINDICATOR_HPP_
+#define COMMANDLINESTATUSINDICATOR_HPP_
+
+#include "Patterns/Observer.hpp"
+
+class CommandLineStatusIndicator : public Observer
+{
+public:
+  CommandLineStatusIndicator();
+  virtual ~CommandLineStatusIndicator();
+
+  void update(Observable *subject);
+  void subjectKilled(Observable *subject);
+
+private:
+
+};
+
+#endif /* COMMANDLINESTATUSINDICATOR_HPP_ */
Index: src/UIElements/CommandLineUIFactory.cpp
===================================================================
--- src/UIElements/CommandLineUIFactory.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/UIElements/CommandLineUIFactory.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,32 @@
+/*
+ * CommandLineUIFactory.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+
+#include "UIElements/CommandLineUIFactory.hpp"
+#include "UIElements/CommandLineWindow.hpp"
+#include "UIElements/CommandLineDialog.hpp"
+
+
+CommandLineUIFactory::CommandLineUIFactory()
+{
+  // TODO Auto-generated constructor stub
+
+}
+
+CommandLineUIFactory::~CommandLineUIFactory()
+{
+  // TODO Auto-generated destructor stub
+}
+
+
+Dialog* CommandLineUIFactory::makeDialog() {
+  return new CommandLineDialog();
+}
+
+MainWindow* CommandLineUIFactory::makeMainWindow() {
+  return new CommandLineWindow();
+}
Index: src/UIElements/CommandLineUIFactory.hpp
===================================================================
--- src/UIElements/CommandLineUIFactory.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/UIElements/CommandLineUIFactory.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,28 @@
+/*
+ * CommandLineUIFactory.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef COMMANDLINEUIFACTORY_HPP_
+#define COMMANDLINEUIFACTORY_HPP_
+
+#include "UIElements/UIFactory.hpp"
+
+class CommandLineUIFactory : public UIFactory
+{
+friend class UIFactory;
+
+public:
+  virtual ~CommandLineUIFactory();
+
+  virtual Dialog* makeDialog();
+  virtual MainWindow* makeMainWindow();
+
+protected:
+  CommandLineUIFactory();
+};
+
+
+#endif /* COMMANDLINEUIFACTORY_HPP_ */
Index: src/UIElements/CommandLineWindow.cpp
===================================================================
--- src/UIElements/CommandLineWindow.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/UIElements/CommandLineWindow.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,81 @@
+/*
+ * CommandLineWindow.cpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#include <boost/bind.hpp>
+
+#include "UIElements/CommandLineWindow.hpp"
+#include "UIElements/CommandLineStatusIndicator.hpp"
+
+#include "Actions/ActionRegistry.hpp"
+#include "Actions/CmdAction/HelpAction.hpp"
+#include "Actions/CmdAction/VersionAction.hpp"
+#include "Actions/ParserAction/LoadXyzAction.hpp"
+#include "Actions/ParserAction/SaveXyzAction.hpp"
+#include "CommandLineParser.hpp"
+
+#include <iostream>
+
+using namespace std;
+
+// TODO: see what code can be moved to a base class for Graphic and CommandLine Windows
+CommandLineWindow::CommandLineWindow()
+{
+  // create and register all command line callable actions
+  populateAtomActions();
+  populateCmdActions();
+  populateFragmentationActions();
+  populateMoleculeActions();
+  populateParserActions();
+  populateTesselationActions();
+
+  // Add status indicators etc...
+  statusIndicator = new CommandLineStatusIndicator();
+}
+
+CommandLineWindow::~CommandLineWindow()
+{
+  delete statusIndicator;
+}
+
+void CommandLineWindow::display() {
+  // go through all possible actions
+  for(std::map<const std::string,Action*>::iterator ActionRunner = ActionRegistry::getInstance().getBeginIter(); ActionRunner != ActionRegistry::getInstance().getEndIter(); ActionRunner++) {
+    // check whether action is present in command line
+    if (CommandLineParser::getInstance().vm.count(ActionRunner->first)) {
+      ActionRunner->second->call();
+    }
+  }
+}
+
+void CommandLineWindow::populateAtomActions()
+{
+}
+
+void CommandLineWindow::populateCmdActions()
+{
+  new CommandLineHelpAction();
+  new CommandLineVersionAction();
+}
+
+void CommandLineWindow::populateFragmentationActions()
+{
+}
+
+void CommandLineWindow::populateMoleculeActions()
+{
+}
+
+void CommandLineWindow::populateParserActions()
+{
+  new ParserLoadXyzAction();
+  new ParserSaveXyzAction();
+}
+
+void CommandLineWindow::populateTesselationActions()
+{
+}
+
Index: src/UIElements/CommandLineWindow.hpp
===================================================================
--- src/UIElements/CommandLineWindow.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/UIElements/CommandLineWindow.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,36 @@
+/*
+ * CommandLineWindow.hpp
+ *
+ *  Created on: May 8, 2010
+ *      Author: heber
+ */
+
+#ifndef COMMANDLINEWINDOW_HPP_
+#define COMMANDLINEWINDOW_HPP_
+
+#include "UIElements/MainWindow.hpp"
+
+class CommandLineStatusIndicator;
+
+class CommandLineWindow : public MainWindow
+{
+public:
+  CommandLineWindow();
+  virtual ~CommandLineWindow();
+
+  virtual void display();
+
+private:
+  // populaters
+  void populateAtomActions();
+  void populateCmdActions();
+  void populateFragmentationActions();
+  void populateMoleculeActions();
+  void populateParserActions();
+  void populateTesselationActions();
+
+  CommandLineStatusIndicator *statusIndicator;
+
+};
+
+#endif /* COMMANDLINEWINDOW_HPP_ */
Index: src/UIElements/Dialog.cpp
===================================================================
--- src/UIElements/Dialog.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/Dialog.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -51,6 +51,7 @@
 
 // Base class
-Dialog::Query::Query(string _title) :
-    title(_title)
+Dialog::Query::Query(string _title, string _description) :
+    title(_title),
+    description(_description)
 {}
 
@@ -61,8 +62,22 @@
 }
 
+const std::string Dialog::Query::getDescription() const{
+  return description;
+}
+// empty Queries
+
+Dialog::EmptyQuery::EmptyQuery(string title, std::string description) :
+    Query(title, description)
+{}
+
+Dialog::EmptyQuery::~EmptyQuery() {}
+
+void Dialog::EmptyQuery::setResult() {
+}
+
 // Int Queries
 
-Dialog::IntQuery::IntQuery(string title,int *_target) :
-    Query(title), target(_target)
+Dialog::IntQuery::IntQuery(string title,int *_target, std::string description) :
+    Query(title, description), target(_target)
 {}
 
@@ -75,6 +90,6 @@
 // String Queries
 
-Dialog::StringQuery::StringQuery(string title,string *_target) :
-    Query(title), target(_target)
+Dialog::StringQuery::StringQuery(string title,string *_target, std::string _description) :
+    Query(title, _description), target(_target)
 {}
 
@@ -87,6 +102,6 @@
 // Double Queries
 
-Dialog::DoubleQuery::DoubleQuery(string title,double *_target) :
-    Query(title), target(_target)
+Dialog::DoubleQuery::DoubleQuery(string title,double *_target, std::string _description) :
+    Query(title, _description), target(_target)
 {}
 
@@ -100,9 +115,10 @@
 // Molecule Queries
 
-Dialog::MoleculeQuery::MoleculeQuery(string title, molecule **_target, MoleculeListClass *_molecules) :
-    Query(title),
-    target(_target),
+Dialog::MoleculeQuery::MoleculeQuery(string title, molecule **_target, MoleculeListClass *_molecules, std::string _description) :
+    Query(title, _description),
+    tmp(0),
     molecules(_molecules),
-    tmp(0)
+    target(_target)
+
 {}
 
@@ -115,6 +131,9 @@
 // Vector Queries
 
-Dialog::VectorQuery::VectorQuery(std::string title,Vector *_target,const double *const _cellSize,bool _check) :
-  Query(title), target(_target), cellSize(_cellSize), check(_check)
+Dialog::VectorQuery::VectorQuery(std::string title,Vector *_target,const double *const _cellSize,bool _check, std::string _description) :
+  Query(title, _description),
+  cellSize(_cellSize),
+  check(_check),
+  target(_target)
 {
 tmp = new Vector();
@@ -129,2 +148,15 @@
   *target = *tmp;
 }
+
+// Element Queries
+Dialog::ElementQuery::ElementQuery(std::string title, const element **_target, std::string _description) :
+  Query(title, _description),
+  tmp(0),
+  target(_target)
+  {}
+
+Dialog::ElementQuery::~ElementQuery(){}
+
+void Dialog::ElementQuery::setResult(){
+  *target=tmp;
+}
Index: src/UIElements/Dialog.hpp
===================================================================
--- src/UIElements/Dialog.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/Dialog.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -15,4 +15,5 @@
 class molecule;
 class Vector;
+class element;
 
 class Dialog
@@ -22,9 +23,11 @@
   virtual ~Dialog();
 
-  virtual void queryInt(const char *, int *)=0;
-  virtual void queryDouble(const char*,double *)=0;
-  virtual void queryString(const char*, std::string *)=0;
-  virtual void queryMolecule(const char*,molecule**,MoleculeListClass*)=0;
-  virtual void queryVector(const char*,Vector *,const double *const,bool)=0;
+  virtual void queryEmpty(const char *, std::string = "")=0;
+  virtual void queryInt(const char *, int *, std::string = "")=0;
+  virtual void queryDouble(const char*,double *, std::string = "")=0;
+  virtual void queryString(const char*, std::string *, std::string = "")=0;
+  virtual void queryMolecule(const char*,molecule**,MoleculeListClass*, std::string = "")=0;
+  virtual void queryVector(const char*,Vector *,const double *const,bool, std::string = "")=0;
+  virtual void queryElement(const char*,const element **, std::string = "")=0;
 
   virtual bool display();
@@ -44,12 +47,23 @@
   class Query {
   public:
-    Query(std::string _title);
-    ~Query();
+    Query(std::string _title, std::string _description = "");
+    virtual ~Query();
     virtual bool handle()=0;
     virtual void setResult()=0;
   protected:
     const std::string getTitle() const;
+    const std::string getDescription() const;
   private:
-    std::string title;
+    std::string title;  //!< short title of the query
+    std::string description; //!< longer description for tooltips or for help
+  };
+
+  // Empty Query is just meant for showing text, such as version, help, initial message or alike
+  class EmptyQuery : public Query {
+  public:
+    EmptyQuery(std::string title, std::string _description = "");
+    virtual ~EmptyQuery();
+    virtual bool handle()=0;
+    virtual void setResult();
   };
 
@@ -57,6 +71,6 @@
   class IntQuery : public Query {
   public:
-    IntQuery(std::string title,int *_target);
-    ~IntQuery();
+    IntQuery(std::string title,int *_target, std::string _description = "");
+    virtual ~IntQuery();
     virtual bool handle()=0;
     virtual void setResult();
@@ -69,6 +83,6 @@
   class DoubleQuery : public Query {
   public:
-    DoubleQuery(std::string title,double *_target);
-    ~DoubleQuery();
+    DoubleQuery(std::string title,double *_target, std::string _description = "");
+    virtual ~DoubleQuery();
     virtual bool handle()=0;
     virtual void setResult();
@@ -81,6 +95,6 @@
   class StringQuery : public Query {
   public:
-    StringQuery(std::string title,std::string *_target);
-    ~StringQuery();
+    StringQuery(std::string title,std::string *_target, std::string _description = "");
+    virtual ~StringQuery();
     virtual bool handle()=0;
     virtual void setResult();
@@ -94,6 +108,6 @@
   class MoleculeQuery : public Query {
   public:
-    MoleculeQuery(std::string title, molecule **_target, MoleculeListClass *_molecules);
-    ~MoleculeQuery();
+    MoleculeQuery(std::string title, molecule **_target, MoleculeListClass *_molecules, std::string _description = "");
+    virtual ~MoleculeQuery();
     virtual bool handle()=0;
     virtual void setResult();
@@ -107,6 +121,6 @@
   class VectorQuery : public Query {
   public:
-      VectorQuery(std::string title,Vector *_target,const double *const _cellSize,bool _check);
-      ~VectorQuery();
+      VectorQuery(std::string title,Vector *_target,const double *const _cellSize,bool _check, std::string _description = "");
+      virtual ~VectorQuery();
       virtual bool handle()=0;
       virtual void setResult();
@@ -119,4 +133,16 @@
   };
 
+  class ElementQuery : public Query {
+  public:
+    ElementQuery(std::string title, const element**_target, std::string _description = "");
+    virtual ~ElementQuery();
+    virtual bool handle()=0;
+    virtual void setResult();
+  protected:
+    const element *tmp;
+  private:
+    const element **target;
+  };
+
 void registerQuery(Query* query);
 
@@ -126,3 +152,4 @@
 };
 
+
 #endif /* DIALOG_HPP_ */
Index: src/UIElements/MainWindow.hpp
===================================================================
--- src/UIElements/MainWindow.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/MainWindow.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -25,9 +25,4 @@
 };
 
-typedef void (*MenuMaker)(Menu*,MoleculeListClass*, config*, periodentafel*);
-
-struct menuPopulaters{
-  MenuMaker MakeEditMoleculesMenu;
-};
 
 #endif /* MAINWINDOW_HPP_ */
Index: src/UIElements/TextDialog.cpp
===================================================================
--- src/UIElements/TextDialog.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/TextDialog.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,4 +10,6 @@
 #include "UIElements/TextDialog.hpp"
 
+#include "World.hpp"
+#include "periodentafel.hpp"
 #include "atom.hpp"
 #include "molecule.hpp"
@@ -27,28 +29,47 @@
 
 
-void TextDialog::queryInt(const char* title, int* target){
-  registerQuery(new IntTextQuery(title,target));
-}
-
-void TextDialog::queryDouble(const char* title, double* target){
-  registerQuery(new DoubleTextQuery(title,target));
-}
-
-void TextDialog::queryString(const char* title, string* target){
-  registerQuery(new StringTextQuery(title,target));
-}
-
-void TextDialog::queryMolecule(const char* title, molecule **target, MoleculeListClass *molecules) {
-  registerQuery(new MoleculeTextQuery(title,target,molecules));
-}
-
-void TextDialog::queryVector(const char* title, Vector *target,const double *const cellSize, bool check) {
-  registerQuery(new VectorTextQuery(title,target,cellSize,check));
+void TextDialog::queryEmpty(const char* title, string description){
+  registerQuery(new EmptyTextQuery(title,description));
+}
+
+void TextDialog::queryInt(const char* title, int* target, string description){
+  registerQuery(new IntTextQuery(title,target,description));
+}
+
+void TextDialog::queryDouble(const char* title, double* target, string description){
+  registerQuery(new DoubleTextQuery(title,target,description));
+}
+
+void TextDialog::queryString(const char* title, string* target, string description){
+  registerQuery(new StringTextQuery(title,target,description));
+}
+
+void TextDialog::queryMolecule(const char* title, molecule **target, MoleculeListClass *molecules, string description) {
+  registerQuery(new MoleculeTextQuery(title,target,molecules,description));
+}
+
+void TextDialog::queryVector(const char* title, Vector *target,const double *const cellSize, bool check, string description) {
+  registerQuery(new VectorTextQuery(title,target,cellSize,check,description));
+}
+
+void TextDialog::queryElement(const char* title, const element **target, string description){
+  registerQuery(new ElementTextQuery(title,target,description));
 }
 
 /************************** Query Infrastructure ************************/
 
-TextDialog::IntTextQuery::IntTextQuery(string title,int *_target) :
-    Dialog::IntQuery(title,_target)
+TextDialog::EmptyTextQuery::EmptyTextQuery(string title, std::string _description) :
+    Dialog::EmptyQuery(title,_description)
+{}
+
+TextDialog::EmptyTextQuery::~EmptyTextQuery() {}
+
+bool TextDialog::EmptyTextQuery::handle() {
+  cout << "Message of " << getTitle() << ":\n" << getDescription() << "\n";
+  return true;
+}
+
+TextDialog::IntTextQuery::IntTextQuery(string title, int * _target, std::string _description) :
+    Dialog::IntQuery(title,_target,_description)
 {}
 
@@ -56,11 +77,23 @@
 
 bool TextDialog::IntTextQuery::handle() {
-  Log() << Verbose(0) << getTitle();
-  cin >> tmp;
-  return true;
-}
-
-TextDialog::StringTextQuery::StringTextQuery(string title,string *_target) :
-    Dialog::StringQuery(title,_target)
+  bool badInput = false;
+  do{
+    badInput = false;
+    Log() << Verbose(0) << getTitle();
+    cin >> tmp;
+    if(cin.fail()){
+      badInput=true;
+      cin.clear();
+      cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+      Log() << Verbose(0) << "Input was not a number!" << endl;
+    }
+  } while(badInput);
+  // clear the input buffer of anything still in the line
+  cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+  return true;
+}
+
+TextDialog::StringTextQuery::StringTextQuery(string title,string *_target, std::string _description) :
+    Dialog::StringQuery(title,_target,_description)
 {}
 
@@ -69,10 +102,10 @@
 bool TextDialog::StringTextQuery::handle() {
   Log() << Verbose(0) << getTitle();
-  cin >> tmp;
-  return true;
-}
-
-TextDialog::DoubleTextQuery::DoubleTextQuery(string title,double *_target) :
-    Dialog::DoubleQuery(title,_target)
+  getline(cin,tmp);
+  return true;
+}
+
+TextDialog::DoubleTextQuery::DoubleTextQuery(string title,double *_target, std::string _description) :
+    Dialog::DoubleQuery(title,_target,_description)
 {}
 
@@ -80,37 +113,135 @@
 
 bool TextDialog::DoubleTextQuery::handle() {
+  bool badInput = false;
+  do{
+    badInput = false;
+    Log() << Verbose(0) << getTitle();
+    cin >> tmp;
+    if(cin.fail()){
+      badInput = true;
+      cin.clear();
+      cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+      Log() << Verbose(0) << "Input was not a number!" << endl;
+    }
+  }while(badInput);
+  cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+  return true;
+}
+
+TextDialog::MoleculeTextQuery::MoleculeTextQuery(string title, molecule **_target, MoleculeListClass *_molecules, std::string _description) :
+    Dialog::MoleculeQuery(title,_target,_molecules,_description)
+{}
+
+TextDialog::MoleculeTextQuery::~MoleculeTextQuery() {}
+
+bool TextDialog::MoleculeTextQuery::handle() {
+  int idxOfMol=0;
+  bool badInput = false;
+  do{
+    badInput = false;
+    Log() << Verbose(0) << getTitle();
+    cin >> idxOfMol;
+    if(cin.fail()){
+      badInput = true;
+      cin.clear();
+      cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+      Log() << Verbose(0) << "Input was not a number!" << endl;
+      continue;
+    }
+
+    tmp = molecules->ReturnIndex(idxOfMol);
+    if(!tmp && idxOfMol!=-1){
+      Log() << Verbose(0) << "Invalid Molecule Index" << endl;
+      badInput = true;
+    }
+
+  } while(badInput);
+  cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+  return (idxOfMol!=-1);
+}
+
+TextDialog::VectorTextQuery::VectorTextQuery(std::string title, Vector *_target, const double *const _cellSize, bool _check, std::string _description) :
+    Dialog::VectorQuery(title,_target,_cellSize,_check,_description)
+{}
+
+TextDialog::VectorTextQuery::~VectorTextQuery()
+{}
+
+bool TextDialog::VectorTextQuery::handle() {
   Log() << Verbose(0) << getTitle();
-  cin >> tmp;
-  return true;
-}
-
-TextDialog::MoleculeTextQuery::MoleculeTextQuery(string title, molecule **_target, MoleculeListClass *_molecules) :
-    Dialog::MoleculeQuery(title,_target,_molecules)
-{}
-
-TextDialog::MoleculeTextQuery::~MoleculeTextQuery() {}
-
-bool TextDialog::MoleculeTextQuery::handle() {
-  int idxOfMol;
-  Log() << Verbose(0) << getTitle();
-  cin >> idxOfMol;
-  tmp = molecules->ReturnIndex(idxOfMol);
-  while(!tmp && (idxOfMol !=-1)) {
-    Log() << Verbose(0) << "Invalid Molecule Index" << endl;
-    Log() << Verbose(0) << getTitle();
-    cin >> idxOfMol;
-    tmp = molecules->ReturnIndex(idxOfMol);
+
+  char coords[3] = {'x','y','z'};
+  int j = -1;
+  for (int i=0;i<3;i++) {
+    j += i+1;
+    do {
+      Log() << Verbose(0) << coords[i] << "[0.." << cellSize[j] << "]: ";
+      cin >> (*tmp)[i];
+    } while ((((*tmp)[i] < 0) || ((*tmp)[i] >= cellSize[j])) && (check));
   }
-  return (idxOfMol!=-1);
-}
-
-TextDialog::VectorTextQuery::VectorTextQuery(std::string title, Vector *_target, const double *const _cellSize, bool _check) :
-    Dialog::VectorQuery(title,_target,_cellSize,_check)
-{}
-
-TextDialog::VectorTextQuery::~VectorTextQuery()
-{}
-
-bool TextDialog::VectorTextQuery::handle() {
- tmp->AskPosition(cellSize,check);
-}
+  return true;
+}
+
+
+TextDialog::ElementTextQuery::ElementTextQuery(std::string title, const element **target, std::string _description) :
+    Dialog::ElementQuery(title,target,_description)
+{}
+
+TextDialog::ElementTextQuery::~ElementTextQuery()
+{}
+
+bool TextDialog::ElementTextQuery::handle() {
+  bool badInput=false;
+  bool aborted = false;
+  do{
+    badInput = false;
+    Log() << Verbose(0) << getTitle();
+
+    // try to read as Atomic number
+    int Z;
+    cin >> Z;
+    if(!cin.fail()){
+      if(Z==-1){
+        aborted = true;
+      }
+      else{
+        tmp = World::getInstance().getPeriode()->FindElement(Z);
+        if(!tmp){
+          Log() << Verbose(0) << "No element with this atomic number!" << endl;
+          badInput = true;
+        }
+      }
+      continue;
+    }
+    else{
+      cin.clear();
+    }
+
+    // Try to read as shorthand
+    // the last buffer content was not removed, so we read the
+    // same thing again, this time as a string
+    string shorthand;
+    cin >> shorthand;
+    if(!cin.fail()){
+      if(shorthand.empty()){
+        aborted = true;
+      }
+      else{
+        tmp = World::getInstance().getPeriode()->FindElement(shorthand.c_str());
+        if(!tmp){
+          Log() << Verbose(0) << "No element with this shorthand!" << endl;
+          badInput = true;
+        }
+      }
+    }
+    else{
+      Log() << Verbose(0) << "Could not read input. Try Again." << endl;
+      cin.clear();
+      cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+      badInput = true;
+    }
+
+  }while(badInput);
+  cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
+  return !aborted;
+}
Index: src/UIElements/TextDialog.hpp
===================================================================
--- src/UIElements/TextDialog.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/TextDialog.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -19,16 +19,25 @@
   virtual ~TextDialog();
 
-  virtual void queryInt(const char *, int *);
-  virtual void queryString(const char*, std::string *);
-  virtual void queryDouble(const char*, double*);
-  virtual void queryMolecule(const char*,molecule**,MoleculeListClass*);
-  virtual void queryVector(const char*,Vector *,const double * const,bool);
+  virtual void queryEmpty(const char *, std::string = "");
+  virtual void queryInt(const char *, int *, std::string = "");
+  virtual void queryString(const char*, std::string *, std::string = "");
+  virtual void queryDouble(const char*, double*, std::string = "");
+  virtual void queryMolecule(const char*,molecule**,MoleculeListClass*, std::string = "");
+  virtual void queryVector(const char*,Vector *,const double * const,bool, std::string = "");
+  virtual void queryElement(const char*,const element **, std::string = "");
 
 protected:
   // specialized stuff for text queries
+  class EmptyTextQuery : public Dialog::EmptyQuery {
+  public:
+    EmptyTextQuery(std::string title, std::string _description = NULL);
+    virtual ~EmptyTextQuery();
+    virtual bool handle();
+  };
+
   class IntTextQuery : public Dialog::IntQuery {
   public:
-    IntTextQuery(std::string title, int *_target);
-    ~IntTextQuery();
+    IntTextQuery(std::string title, int *_target, std::string _description = NULL);
+    virtual ~IntTextQuery();
     virtual bool handle();
   };
@@ -36,6 +45,6 @@
   class DoubleTextQuery : public Dialog::DoubleQuery {
   public:
-    DoubleTextQuery(std::string title, double *_target);
-    ~DoubleTextQuery();
+    DoubleTextQuery(std::string title, double *_target, std::string _description = NULL);
+    virtual ~DoubleTextQuery();
     virtual bool handle();
   };
@@ -43,6 +52,6 @@
   class StringTextQuery : public Dialog::StringQuery {
   public:
-    StringTextQuery(std::string title, std::string *_target);
-    ~StringTextQuery();
+    StringTextQuery(std::string title, std::string *_target, std::string _description = NULL);
+    virtual ~StringTextQuery();
     virtual bool handle();
   };
@@ -50,6 +59,6 @@
   class MoleculeTextQuery : public Dialog::MoleculeQuery {
   public:
-    MoleculeTextQuery(std::string title, molecule **_target, MoleculeListClass *_molecules);
-    ~MoleculeTextQuery();
+    MoleculeTextQuery(std::string title, molecule **_target, MoleculeListClass *_molecules, std::string _description = NULL);
+    virtual ~MoleculeTextQuery();
     virtual bool handle();
   };
@@ -57,6 +66,13 @@
   class VectorTextQuery : public Dialog::VectorQuery {
   public:
-    VectorTextQuery(std::string title,Vector *_target,const double *const _cellSize,bool _check);
-    ~VectorTextQuery();
+    VectorTextQuery(std::string title,Vector *_target,const double *const _cellSize,bool _check, std::string _description = NULL);
+    virtual ~VectorTextQuery();
+    virtual bool handle();
+  };
+
+  class ElementTextQuery : public Dialog::ElementQuery {
+  public:
+    ElementTextQuery(std::string title, const element **_target, std::string _description = NULL);
+    virtual ~ElementTextQuery();
     virtual bool handle();
   };
Index: src/UIElements/TextStatusIndicator.cpp
===================================================================
--- src/UIElements/TextStatusIndicator.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/TextStatusIndicator.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -27,5 +27,5 @@
   Process *proc;
   // we are only observing Processes
-  if(proc=dynamic_cast<Process*>(subject)){
+  if((proc=dynamic_cast<Process*>(subject))){
     // see what kind of progress we have to display
     if(proc->getMaxSteps()>0){
Index: src/UIElements/TextUIFactory.cpp
===================================================================
--- src/UIElements/TextUIFactory.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/TextUIFactory.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -27,6 +27,6 @@
 }
 
-MainWindow* TextUIFactory::makeMainWindow(menuPopulaters populaters,MoleculeListClass *molecules, config *configuration, periodentafel *periode, char *ConfigFileName) {
-  return new TextWindow(populaters,molecules,configuration,periode,ConfigFileName);
+MainWindow* TextUIFactory::makeMainWindow() {
+  return new TextWindow();
 }
 
Index: src/UIElements/TextUIFactory.hpp
===================================================================
--- src/UIElements/TextUIFactory.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/TextUIFactory.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -19,5 +19,5 @@
 
   virtual Dialog* makeDialog();
-  virtual MainWindow* makeMainWindow(menuPopulaters,MoleculeListClass *, config *, periodentafel *, char *);
+  virtual MainWindow* makeMainWindow();
 
 protected:
Index: src/UIElements/TextWindow.cpp
===================================================================
--- src/UIElements/TextWindow.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/TextWindow.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -27,4 +27,5 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
+#include "World.hpp"
 
 #include "Legacy/oldmenu.hpp"
@@ -38,5 +39,7 @@
 #include "UIElements/TextStatusIndicator.hpp"
 #include "Actions/MethodAction.hpp"
+#include "Actions/MoleculeAction/ChangeNameAction.hpp"
 #include "Actions/ErrorAction.hpp"
+#include "Actions/ActionRegistry.hpp"
 #include "Views/StreamStringView.hpp"
 #include "Views/MethodStringView.hpp"
@@ -47,6 +50,10 @@
 
 // TODO: see what code can be moved to a base class for Graphic and Text Windows
-TextWindow::TextWindow(menuPopulaters populaters,MoleculeListClass *molecules, config *configuration, periodentafel *periode, char *ConfigFileName)
+TextWindow::TextWindow()
 {
+  MoleculeListClass *molecules = World::getInstance().getMolecules();
+  config *configuration = World::getInstance().getConfig();
+  periodentafel *periode = World::getInstance().getPeriode();
+  char *ConfigFileName = NULL;
   old_menu = new oldmenu;
 
@@ -56,4 +63,12 @@
   moleculeView = new StreamStringView(boost::bind(&MoleculeListClass::Enumerate,molecules,_1));
   new DisplayMenuItem(main_menu,moleculeView,"Molecule List");
+
+  new SeperatorItem(main_menu);
+
+  Action* undoAction = ActionRegistry::getInstance().getActionByName("Undo");
+  new ActionMenuItem('u',"Undo last operation",main_menu,undoAction);
+
+  Action* redoAction = ActionRegistry::getInstance().getActionByName("Redo");
+  new ActionMenuItem('r',"Redo last operation",main_menu,redoAction);
 
   new SeperatorItem(main_menu);
@@ -92,7 +107,7 @@
   // call all functions used to build the submenus
 
-  populaters.MakeEditMoleculesMenu(editMoleculesMenu,molecules,configuration,periode);
+  populateEditMoleculesMenu(editMoleculesMenu);
 
-  returnFromEditMoleculeAction = new MethodAction("returnAction",boost::bind(&TextMenu::doQuit,editMoleculesMenu),false);
+  Action *returnFromEditMoleculeAction = new TextMenu::LeaveAction(editMoleculesMenu);
   MenuItem *returnItem = new ActionMenuItem('q',"return to Main menu",editMoleculesMenu,returnFromEditMoleculeAction);
 
@@ -108,5 +123,4 @@
   delete old_menu;
   delete quitAction;
-  delete returnFromEditMoleculeAction;
   delete moleculeView;
   delete statusIndicator;
@@ -117,2 +131,28 @@
   main_menu->display();
 }
+
+void TextWindow::populateEditMoleculesMenu(Menu* editMoleculesMenu)
+{
+  MoleculeListClass *molecules = World::getInstance().getMolecules();
+  periodentafel *periode = World::getInstance().getPeriode();
+
+  // build the EditMoleculesMenu
+  Action *createMoleculeAction = new MethodAction("createMoleculeAction",boost::bind(&MoleculeListClass::createNewMolecule,molecules,periode));
+  new ActionMenuItem('c',"create new molecule",editMoleculesMenu,createMoleculeAction);
+
+  Action *loadMoleculeAction = new MethodAction("loadMoleculeAction",boost::bind(&MoleculeListClass::loadFromXYZ,molecules,periode));
+  new ActionMenuItem('l',"load molecule from xyz file",editMoleculesMenu,loadMoleculeAction);
+
+  Action *changeFilenameAction = new MoleculeChangeNameAction(molecules);
+  new ActionMenuItem('n',"change molecule's name",editMoleculesMenu,changeFilenameAction);
+
+  Action *giveFilenameAction = new MethodAction("giveFilenameAction",boost::bind(&MoleculeListClass::setMoleculeFilename,molecules));
+  new ActionMenuItem('N',"give molecules filename",editMoleculesMenu,giveFilenameAction);
+
+  Action *parseAtomsAction = new MethodAction("parseAtomsAction",boost::bind(&MoleculeListClass::parseXYZIntoMolecule,molecules));
+  new ActionMenuItem('p',"parse atoms in xyz file into molecule",editMoleculesMenu,parseAtomsAction);
+
+  Action *eraseMoleculeAction = new MethodAction("eraseMoleculeAction",boost::bind(&MoleculeListClass::eraseMolecule,molecules));
+  new ActionMenuItem('r',"remove a molecule",editMoleculesMenu,eraseMoleculeAction);
+
+}
Index: src/UIElements/TextWindow.hpp
===================================================================
--- src/UIElements/TextWindow.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/TextWindow.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -17,17 +17,20 @@
 class TextStatusIndicator;
 
+
 class TextWindow : public MainWindow
 {
 public:
-  TextWindow(menuPopulaters,MoleculeListClass *, config *, periodentafel *, char *);
+  TextWindow();
   virtual ~TextWindow();
 
   virtual void display();
 private:
+  // populaters
+  void populateEditMoleculesMenu(Menu* editMoleculesMenu);
+
   TextMenu *main_menu;
 
   // some actions only needed in textMenus
   Action *quitAction;
-  Action *returnFromEditMoleculeAction;
   // all views that are contained in the main Menu
   StringView *moleculeView;
Index: src/UIElements/UIFactory.cpp
===================================================================
--- src/UIElements/UIFactory.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/UIFactory.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -8,10 +8,10 @@
 
 #include <cassert>
+#include "Patterns/Singleton_impl.hpp"
 #include "UIElements/UIFactory.hpp"
 
 // all factories that can be used:
 #include "UIElements/TextUIFactory.hpp"
-
-UIFactory *UIFactory::theFactory = 0;
+#include "UIElements/CommandLineUIFactory.hpp"
 
 UIFactory::UIFactory()
@@ -27,8 +27,10 @@
 
 void UIFactory::makeUserInterface(InterfaceTypes type) {
-  assert(theFactory == 0 && "makeUserInterface should only be called once");
   switch(type) {
     case Text :
-      theFactory = new TextUIFactory();
+      setInstance(new TextUIFactory());
+      break;
+    case CommandLine:
+      setInstance(new CommandLineUIFactory());
       break;
 
@@ -39,14 +41,3 @@
 }
 
-UIFactory* UIFactory::get(){
-  assert(theFactory != 0 && "No UserInterface created prior to factory access");
-  return theFactory;
-}
-
-
-void UIFactory::purgeInstance(){
-  if(theFactory) {
-    delete theFactory;
-    theFactory = 0;
-  }
-}
+CONSTRUCT_SINGLETON(UIFactory)
Index: src/UIElements/UIFactory.hpp
===================================================================
--- src/UIElements/UIFactory.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/UIElements/UIFactory.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -11,20 +11,31 @@
 class MainWindow;
 class Dialog;
+class DialogDescription;
 
-class MoleculeListClass;
-class config;
-class periodentafel;
+#include "Patterns/Singleton.hpp"
 
-struct menuPopulaters;
-
-class UIFactory
+/**
+ * Abstract Factory to create any kind of User interface object needed by the programm.
+ *
+ * The factory can be created and has to be set to a certain type upon creation. It will then
+ * only create UIelements of that certain type, so that all UIElements match. This way different
+ * UIs can be handled in a concise abstract way.
+ */
+class UIFactory : public Singleton<UIFactory,false>
 {
 
 public:
-  enum InterfaceTypes {Text};
+  enum InterfaceTypes {Text, CommandLine};
   virtual ~UIFactory();
 
-  // methods for creating UIElements
-  virtual MainWindow* makeMainWindow(menuPopulaters,MoleculeListClass *, config *, periodentafel *, char *)=0;
+  /**
+   * Produce some kind of main window, of whichever type was chosen when the factory was created
+   */
+  virtual MainWindow* makeMainWindow()=0;
+
+  /**
+   * Produce a User Interaction Dialog, that can query values from the User.
+   * Again the type is determined upon factory creation.
+   */
   virtual Dialog* makeDialog()=0;
 
@@ -32,12 +43,10 @@
   UIFactory();
 
-// singleton stuff
-private:
-  static UIFactory *theFactory;
+public:
+  /**
+   * create a Factory of a certain type. From that moment on only those UIElements can be produced by the factory
+   */
+  static void makeUserInterface(InterfaceTypes type);
 
-public:
-  static void makeUserInterface(InterfaceTypes type);
-  static UIFactory* get();
-  static void purgeInstance();
 };
 
Index: src/Views/MethodStringView.cpp
===================================================================
--- src/Views/MethodStringView.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Views/MethodStringView.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -7,4 +7,6 @@
 
 #include "MethodStringView.hpp"
+
+using namespace std;
 
 MethodStringView::MethodStringView(boost::function<string()> _displayMethod) :
Index: src/Views/MethodStringView.hpp
===================================================================
--- src/Views/MethodStringView.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Views/MethodStringView.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -19,11 +19,11 @@
 {
 public:
-  MethodStringView(boost::function<string()>);
+  MethodStringView(boost::function<std::string()>);
   virtual ~MethodStringView();
 
-  virtual const string toString();
+  virtual const std::string toString();
 
 private:
-  boost::function<string()> displayMethod;
+  boost::function<std::string()> displayMethod;
 };
 
Index: src/Views/StreamStringView.cpp
===================================================================
--- src/Views/StreamStringView.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Views/StreamStringView.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -7,23 +7,21 @@
 
 #include <sstream>
+#include <iostream>
 
 #include "StreamStringView.hpp"
 
-StreamStringView::StreamStringView(boost::function<void(ofstream *)> _displayMethod) :
+using namespace std;
+
+StreamStringView::StreamStringView(boost::function<void(ostream *)> _displayMethod) :
 StringView(),
 displayMethod(_displayMethod)
-{
-  // TODO Auto-generated constructor stub
-
-}
+{}
 
 StreamStringView::~StreamStringView()
-{
-  // TODO Auto-generated destructor stub
-}
+{}
 
 const string StreamStringView::toString() {
   stringstream s;
-  displayMethod((ofstream *)&s);
+  displayMethod(dynamic_cast<ostream *>(&s));
   return s.str();
 }
Index: src/Views/StreamStringView.hpp
===================================================================
--- src/Views/StreamStringView.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Views/StreamStringView.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,4 +10,5 @@
 
 #include <boost/function.hpp>
+#include <iostream>
 
 #include "Views/StringView.hpp"
@@ -24,11 +25,11 @@
 {
 public:
-  StreamStringView(boost::function<void(ofstream *)>);
+  StreamStringView(boost::function<void(std::ostream *)>);
   virtual ~StreamStringView();
 
-  virtual const string toString();
+  virtual const std::string toString();
 
 private:
-  boost::function<void(ofstream *)> displayMethod;
+  boost::function<void(std::ostream *)> displayMethod;
 };
 
Index: src/Views/StringView.hpp
===================================================================
--- src/Views/StringView.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/Views/StringView.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -12,6 +12,4 @@
 #include "Views/View.hpp"
 
-using namespace std;
-
 /**
  * View to show something as a string
@@ -26,5 +24,5 @@
   virtual ~StringView();
 
-  virtual const string toString()=0;
+  virtual const std::string toString()=0;
 };
 
Index: src/World.cpp
===================================================================
--- src/World.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/World.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,7 +9,15 @@
 
 #include "atom.hpp"
+#include "config.hpp"
 #include "molecule.hpp"
 #include "periodentafel.hpp"
 #include "Descriptors/AtomDescriptor.hpp"
+#include "Descriptors/AtomDescriptor_impl.hpp"
+#include "Descriptors/MoleculeDescriptor.hpp"
+#include "Descriptors/MoleculeDescriptor_impl.hpp"
+#include "Descriptors/SelectiveIterator_impl.hpp"
+#include "Actions/ManipulateAtomsProcess.hpp"
+
+#include "Patterns/Singleton_impl.hpp"
 
 using namespace std;
@@ -20,4 +28,10 @@
 }
 
+config *&World::getConfig(){
+  return configuration;
+}
+
+// Atoms
+
 atom* World::getAtom(AtomDescriptor descriptor){
   return descriptor.find();
@@ -28,36 +42,250 @@
 }
 
+vector<atom*> World::getAllAtoms(){
+  return getAllAtoms(AllAtoms());
+}
+
 int World::numAtoms(){
   return atoms.size();
 }
 
+// Molecules
+
+molecule *World::getMolecule(MoleculeDescriptor descriptor){
+  return descriptor.find();
+}
+
+std::vector<molecule*> World::getAllMolecules(MoleculeDescriptor descriptor){
+  return descriptor.findAll();
+}
+
 int World::numMolecules(){
   return molecules_deprecated->ListOfMolecules.size();
 }
 
+// system
+
+double * World::getDomain() {
+  return cell_size;
+}
+
+void World::setDomain(double * matrix)
+{
+
+}
+
+char * World::getDefaultName() {
+  return defaultName;
+}
+
+void World::setDefaultName(char * name)
+{
+  delete[](defaultName);
+  const int length = strlen(name);
+  defaultName = new char[length+2];
+  if (length < MAXSTRINGSIZE)
+    strncpy(defaultName, name, length);
+  else
+    strcpy(defaultName, "none");
+};
+
+
+/******************** Methods to change World state *********************/
+
 molecule* World::createMolecule(){
   OBSERVE;
   molecule *mol = NULL;
-  mol = new molecule(periode);
-  molecules_deprecated->insert(mol);
-  molecules.insert(mol);
+  mol = NewMolecule();
+  assert(!molecules.count(currMoleculeId));
+  mol->setId(currMoleculeId++);
+  // store the molecule by ID
+  molecules[mol->getId()] = mol;
   mol->signOn(this);
   return mol;
 }
 
+void World::destroyMolecule(molecule* mol){
+  OBSERVE;
+  destroyMolecule(mol->getId());
+}
+
+void World::destroyMolecule(moleculeId_t id){
+  OBSERVE;
+  molecule *mol = molecules[id];
+  assert(mol);
+  DeleteMolecule(mol);
+  molecules.erase(id);
+}
+
+double *World::cell_size = NULL;
+char *World::defaultName = NULL;
+
+atom *World::createAtom(){
+  OBSERVE;
+  atomId_t id = getNextAtomId();
+  atom *res = NewAtom(id);
+  res->setWorld(this);
+  // store the atom by ID
+  atoms[res->getId()] = res;
+  return res;
+}
+
+
+int World::registerAtom(atom *atom){
+  OBSERVE;
+  atomId_t id = getNextAtomId();
+  atom->setId(id);
+  atom->setWorld(this);
+  atoms[atom->getId()] = atom;
+  return atom->getId();
+}
+
+void World::destroyAtom(atom* atom){
+  OBSERVE;
+  int id = atom->getId();
+  destroyAtom(id);
+}
+
+void World::destroyAtom(atomId_t id) {
+  OBSERVE;
+  atom *atom = atoms[id];
+  assert(atom);
+  DeleteAtom(atom);
+  atoms.erase(id);
+  releaseAtomId(id);
+}
+
+bool World::changeAtomId(atomId_t oldId, atomId_t newId, atom* target){
+  OBSERVE;
+  // in case this call did not originate from inside the atom, we redirect it,
+  // to also let it know that it has changed
+  if(!target){
+    target = atoms[oldId];
+    assert(target && "Atom with that ID not found");
+    return target->changeId(newId);
+  }
+  else{
+    if(reserveAtomId(newId)){
+      atoms.erase(oldId);
+      atoms.insert(pair<atomId_t,atom*>(newId,target));
+      return true;
+    }
+    else{
+      return false;
+    }
+  }
+}
+
+ManipulateAtomsProcess* World::manipulateAtoms(boost::function<void(atom*)> op,std::string name,AtomDescriptor descr){
+  return new ManipulateAtomsProcess(op, descr,name,true);
+}
+
+ManipulateAtomsProcess* World::manipulateAtoms(boost::function<void(atom*)> op,std::string name){
+  return manipulateAtoms(op,name,AllAtoms());
+}
+
+/********************* Internal Change methods for double Callback and Observer mechanism ********/
+
+void World::doManipulate(ManipulateAtomsProcess *proc){
+  proc->signOn(this);
+  {
+    OBSERVE;
+    proc->doManipulate(this);
+  }
+  proc->signOff(this);
+}
+/******************************* IDManagement *****************************/
+
+// Atoms
+
+atomId_t World::getNextAtomId(){
+  // see if we can reuse some Id
+  if(atomIdPool.empty()){
+    return currAtomId++;
+  }
+  else{
+    // we give out the first ID from the pool
+    atomId_t id = *(atomIdPool.begin());
+    atomIdPool.erase(id);
+    return id;
+  }
+}
+
+void World::releaseAtomId(atomId_t id){
+  atomIdPool.insert(id);
+  // defragmentation of the pool
+  set<atomId_t>::reverse_iterator iter;
+  // go through all Ids in the pool that lie immediately below the border
+  while(!atomIdPool.empty() && *(atomIdPool.rbegin())==(currAtomId-1)){
+    atomIdPool.erase(--currAtomId);
+  }
+}
+
+bool World::reserveAtomId(atomId_t id){
+  if(id>=currAtomId ){
+    // add all ids between the new one and current border as available
+    for(atomId_t pos=currAtomId; pos<id; ++pos){
+      atomIdPool.insert(pos);
+    }
+    currAtomId=id+1;
+    return true;
+  }
+  else if(atomIdPool.count(id)){
+    atomIdPool.erase(id);
+    return true;
+  }
+  else{
+    // this ID could not be reserved
+    return false;
+  }
+}
+
+// Molecules
+
+/******************************* Iterators ********************************/
+
+// Build the AtomIterator from template
+CONSTRUCT_SELECTIVE_ITERATOR(atom*,World::AtomSet,AtomDescriptor);
+
+
+World::AtomIterator World::getAtomIter(AtomDescriptor descr){
+  return AtomIterator(descr,atoms);
+}
+
+World::AtomIterator World::atomEnd(){
+  return AtomIterator(AllAtoms(),atoms,atoms.end());
+}
+
+// build the MoleculeIterator from template
+CONSTRUCT_SELECTIVE_ITERATOR(molecule*,World::MoleculeSet,MoleculeDescriptor);
+
+World::MoleculeIterator World::getMoleculeIter(MoleculeDescriptor descr){
+  return MoleculeIterator(descr,molecules);
+}
+
+World::MoleculeIterator World::moleculeEnd(){
+  return MoleculeIterator(AllMolecules(),molecules,molecules.end());
+}
 
 /******************************* Singleton Stuff **************************/
 
-// TODO: Hide boost-thread using Autotools stuff when no threads are used
-World* World::theWorld = 0;
-boost::mutex World::worldLock;
-
-
-
 World::World() :
-    dummyId(0),
     periode(new periodentafel),
-    molecules_deprecated(new MoleculeListClass)
+    configuration(new config),
+    atoms(),
+    currAtomId(0),
+    molecules(),
+    currMoleculeId(0),
+    molecules_deprecated(new MoleculeListClass(this))
 {
+  cell_size = new double[6];
+  cell_size[0] = 20.;
+  cell_size[1] = 0.;
+  cell_size[2] = 20.;
+  cell_size[3] = 0.;
+  cell_size[4] = 0.;
+  cell_size[5] = 20.;
+  defaultName = new char[MAXSTRINGSIZE];
+  strcpy(defaultName, "none");
   molecules_deprecated->signOn(this);
 }
@@ -65,52 +293,25 @@
 World::~World()
 {
+  molecules_deprecated->signOff(this);
+  delete[] cell_size;
+  delete[] defaultName;
+  delete molecules_deprecated;
   delete periode;
-}
-
-World* World::get(){
-  // boost supports RAII-Style locking, so we don't need to unlock
-  boost::mutex::scoped_lock guard(worldLock);
-  if(!theWorld) {
-    theWorld = new World();
-  }
-  return theWorld;
-}
-
-void World::destroy(){
-  // For legacy reasons all atoms have to be destroyed first, since unregistering would cause deadlocks otherwise
-  theWorld->destroyLegacy();
-  //WARNING: at this point we have a small race condition, when sombody now tries to access the world.
-
-  // boost supports RAII-Style locking, so we don't need to unlock
-  boost::mutex::scoped_lock guard(worldLock);
-  delete theWorld;
-  theWorld = 0;
-}
-
-World* World::reset(){
-  // For legacy reasons all atoms have to be destroyed first, since unregistering would cause deadlocks otherwise
-  theWorld->destroyLegacy();
-  //WARNING: at this point we have a small race condition, when sombody now tries to access the world.
-
-  World* oldWorld = 0;
-  {
-    // boost supports RAII-Style locking, so we don't need to unlock
-    boost::mutex::scoped_lock guard(worldLock);
-
-    oldWorld = theWorld;
-    theWorld = new World();
-    // oldworld does not need protection any more,
-    // since we should have the only reference
-
-    // worldLock handles access to the pointer,
-    // not to the object
-  } // scope-end releases the lock
-
-  // we have to let all the observers know that the
-  // oldWorld was destroyed. oldWorld calls subjectKilled
-  // upon destruction. Every Observer getting that signal
-  // should see that it gets the updated new world
-  delete oldWorld;
-}
+  delete configuration;
+  MoleculeSet::iterator molIter;
+  for(molIter=molecules.begin();molIter!=molecules.end();++molIter){
+    DeleteMolecule((*molIter).second);
+  }
+  molecules.clear();
+  AtomSet::iterator atIter;
+  for(atIter=atoms.begin();atIter!=atoms.end();++atIter){
+    DeleteAtom((*atIter).second);
+  }
+  atoms.clear();
+}
+
+// Explicit instantiation of the singleton mechanism at this point
+
+CONSTRUCT_SINGLETON(World)
 
 /******************************* deprecated Legacy Stuff ***********************/
@@ -119,17 +320,2 @@
   return molecules_deprecated;
 }
-
-// some legacy stuff to let the World know about items created outside
-void World::registerAtom(atom *theAtom){
-  OBSERVE;
-  atoms[dummyId++] = theAtom;
-}
-
-void World::destroyLegacy(){
-  //delete molecules_deprecated;
-}
-
-void World::unregisterAtom(atom *theAtom){
-  OBSERVE;
-  atoms.erase(theAtom->getId());
-}
Index: src/World.hpp
===================================================================
--- src/World.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/World.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,13 +9,26 @@
 #define WORLD_HPP_
 
-#include <boost/thread.hpp>
+/*********************************************** includes ***********************************/
+
+#include <string>
 #include <map>
 #include <vector>
 #include <set>
-
+#include <boost/thread.hpp>
+#include <boost/shared_ptr.hpp>
+
+#include "types.hpp"
+#include "Descriptors/SelectiveIterator.hpp"
 #include "Patterns/Observer.hpp"
 #include "Patterns/Cacheable.hpp"
+#include "Patterns/Singleton.hpp"
+
+// include config.h
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
 
 // forward declarations
+class config;
 class periodentafel;
 class MoleculeListClass;
@@ -24,41 +37,229 @@
 class AtomDescriptor;
 class AtomDescriptor_impl;
-
-class World : public Observable
+class MoleculeDescriptor;
+class MoleculeDescriptor_impl;
+class ManipulateAtomsProcess;
+template<typename T>
+class AtomsCalculation;
+
+/****************************************** forward declarations *****************************/
+
+/********************************************** Class World *******************************/
+
+class World : public Singleton<World>, public Observable
 {
+
+// Make access to constructor and destructor possible from inside the singleton
+friend class Singleton<World>;
+
+// necessary for coupling with descriptors
 friend class AtomDescriptor_impl;
+friend class AtomDescriptor;
+friend class MoleculeDescriptor_impl;
+friend class MoleculeDescriptor;
+
+// Actions, calculations etc associated with the World
+friend class ManipulateAtomsProcess;
+template<typename> friend class AtomsCalculation;
 public:
+
+  // Types for Atom and Molecule structures
+  typedef std::map<atomId_t,atom*> AtomSet;
+  typedef std::map<moleculeId_t,molecule*> MoleculeSet;
 
   /***** getter and setter *****/
   // reference to pointer is used for legacy reason... reference will be removed latter to keep encapsulation of World object
+  /**
+   * returns the periodentafel for the world.
+   */
   periodentafel *&getPeriode();
+
+  /**
+   * returns the configuration for the world.
+   */
+  config *&getConfig();
+
+  /**
+   * returns the first atom that matches a given descriptor.
+   * Do not rely on ordering for descriptors that match more than one atom.
+   */
   atom* getAtom(AtomDescriptor descriptor);
+
+  /**
+   * returns a vector containing all atoms that match a given descriptor
+   */
   std::vector<atom*> getAllAtoms(AtomDescriptor descriptor);
+  std::vector<atom*> getAllAtoms();
+
+  /**
+   * returns a calculation that calls a given function on all atoms matching a descriptor.
+   * the calculation is not called at this point and can be used as an action, i.e. be stored in
+   * menus, be kept around for later use etc.
+   */
+  template<typename T> AtomsCalculation<T>* calcOnAtoms(boost::function<T(atom*)>,std::string,AtomDescriptor);
+  template<typename T> AtomsCalculation<T>* calcOnAtoms(boost::function<T(atom*)>,std::string);
+
+  /**
+   * get the number of atoms in the World
+   */
   int numAtoms();
+
+  /**
+   * returns the first molecule that matches a given descriptor.
+   * Do not rely on ordering for descriptors that match more than one molecule.
+   */
+  molecule *getMolecule(MoleculeDescriptor descriptor);
+
+  /**
+   * returns a vector containing all molecules that match a given descriptor
+   */
+  std::vector<molecule*> getAllMolecules(MoleculeDescriptor descriptor);
+
+  /**
+   * get the number of molecules in the World
+   */
   int numMolecules();
 
+  /**
+   * get the domain size as a symmetric matrix (6 components)
+   */
+  double * getDomain();
+
+  /**
+   * set the domain size as a symmetric matrix (6 components)
+   */
+  void setDomain(double * matrix);
+
+  /**
+   * get the default name
+   */
+  char * getDefaultName();
+
+  /**
+   * set the default name
+   */
+  void setDefaultName(char * name);
+
   /***** Methods to work with the World *****/
+
+  /**
+   * create a new molecule. This method should be used whenever any kind of molecule is needed. Assigns a unique
+   * ID to the molecule and stores it in the World for later retrieval. Do not create molecules directly.
+   */
   molecule *createMolecule();
-private:
+
+  void destroyMolecule(molecule*);
+  void destroyMolecule(moleculeId_t);
+
+  /**
+   * Create a new atom. This method should be used whenever any atom is needed. Assigns a unique ID and stores
+   * the atom in the World. If the atom is not destroyed it will automatically be destroyed when the world ends.
+   */
+  atom *createAtom();
+
+  /**
+   * Registers a Atom unknown to world. Needed in some rare cases, e.g. when cloning atoms, or in some unittests.
+   * Do not re-register Atoms already known to the world since this will cause double-frees.
+   */
+  int registerAtom(atom*);
+
+  /**
+     * Delete some atom and erase it from the world. Use this whenever you need to destroy any atom. Do not call delete on
+     * atom directly since this will leave the pointer inside the world.
+   */
+  void destroyAtom(atom*);
+
+  /**
+   * Delete some atom and erase it from the world. Use this whenever you need to destroy any atom. Do not call delete on
+   * atom directly since this will leave the pointer inside the world.
+   */
+  void destroyAtom(atomId_t);
+
+  /**
+   * used when changing an atom Id.
+   * Unless you are calling this method from inside an atom don't fiddle with the third parameter.
+   *
+   * Return value indicates wether the change could be done or not.
+   */
+  bool changeAtomId(atomId_t oldId, atomId_t newId, atom* target=0);
+
+  /**
+   * Produces a process that calls a function on all Atoms matching a given descriptor. The process is not
+   * called at this time, so it can be passed around, stored inside menuItems etc.
+   */
+  ManipulateAtomsProcess* manipulateAtoms(boost::function<void(atom*)>,std::string,AtomDescriptor);
+  ManipulateAtomsProcess* manipulateAtoms(boost::function<void(atom*)>,std::string);
+
+protected:
+  /**** Iterators to use internal data structures */
+
+  // Atoms
+  typedef SelectiveIterator<atom*,AtomSet,AtomDescriptor> AtomIterator;
+
+  /**
+   * returns an iterator over all Atoms matching a given descriptor.
+   * used for internal purposes, like AtomProcesses and AtomCalculations.
+   */
+  AtomIterator getAtomIter(AtomDescriptor descr);
+
+  /**
+   * returns an iterator to the end of the AtomSet. Due to overloading this iterator
+   * can be compared to iterators produced by getAtomIter (see the mis-matching types).
+   * Thus it can be used to detect when such an iterator is at the end of the list.
+   * used for internal purposes, like AtomProcesses and AtomCalculations.
+   */
+  AtomIterator atomEnd();
+
+  // Molecules
+
+  typedef SelectiveIterator<molecule*,MoleculeSet,MoleculeDescriptor> MoleculeIterator;
+
+  /**
+   * returns an iterator over all Molecules matching a given descriptor.
+   * used for internal purposes, like MoleculeProcesses and MoleculeCalculations.
+   */
+  MoleculeIterator getMoleculeIter(MoleculeDescriptor descr);
+
+  /**
+   * returns an iterator to the end of the MoleculeSet. Due to overloading this iterator
+   * can be compared to iterators produced by getMoleculeIter (see the mis-matching types).
+   * Thus it can be used to detect when such an iterator is at the end of the list.
+   * used for internal purposes, like MoleculeProcesses and MoleculeCalculations.
+   */
+  MoleculeIterator moleculeEnd();
+
+
+  /******* Internal manipulation routines for double callback and Observer mechanism ******/
+  void doManipulate(ManipulateAtomsProcess *);
+
+private:
+
+  atomId_t getNextAtomId();
+  void releaseAtomId(atomId_t);
+  bool reserveAtomId(atomId_t);
+
   periodentafel *periode;
-  std::map<int,atom*> atoms;
-  std::set<molecule*> molecules;
-
-
-  /***** singleton Stuff *****/
+  config *configuration;
+  static double *cell_size;
+  static char *defaultName;
 public:
-  static World* get();
-  static void destroy();
-  static World* reset();
-
-private:
+  AtomSet atoms;
+private:
+  std::set<atomId_t> atomIdPool; //<!stores the pool for all available AtomIds below currAtomId
+  atomId_t currAtomId; //!< stores the next available Id for atoms
+  MoleculeSet molecules;
+  moleculeId_t currMoleculeId;
+private:
+  /**
+   * private constructor to ensure creation of the world using
+   * the singleton pattern.
+   */
   World();
+
+  /**
+   * private destructor to ensure destruction of the world using the
+   * singleton pattern.
+   */
   virtual ~World();
-
-  static World *theWorld;
-  // this mutex only saves the singleton pattern...
-  // use other mutexes to protect internal data as well
-  // this mutex handles access to the pointer, not to the object!!!
-  static boost::mutex worldLock;
 
   /*****
@@ -68,20 +269,6 @@
   MoleculeListClass *&getMolecules();
 
-  // functions used for the WorldContent template mechanism
-  void registerAtom(atom *theAtom);
-  void unregisterAtom(atom *theAtom);
-private:
-  // this function cleans up anything that cannot be cleaned while the lock is active
-  // at a later point all these cleanups have to be moved to the World Class so the deadlock and
-  // race condition can both be avoided.
-  void destroyLegacy();
-
+private:
   MoleculeListClass *molecules_deprecated;
-
-  // this is needed to assign unique IDs to atoms... so far
-  // IDs are not assigned upon Atom creation, so we cannot query the ID
-  // during construction. By using the dummy ID we can make sure all atoms
-  // are actually stored in the map and don't overwrite each other.
-  int dummyId;
 };
 
Index: src/World_calculations.hpp
===================================================================
--- src/World_calculations.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/World_calculations.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,25 @@
+/*
+ * World_calculations.hpp
+ *
+ *  Created on: Feb 19, 2010
+ *      Author: crueger
+ */
+
+#ifndef WORLD_CALCULATIONS_HPP_
+#define WORLD_CALCULATIONS_HPP_
+
+
+#include "World.hpp"
+#include "Actions/AtomsCalculation.hpp"
+
+template<typename T>
+AtomsCalculation<T>* World::calcOnAtoms(boost::function<T(atom*)> op,std::string name,AtomDescriptor descr){
+  return new AtomsCalculation<T>(op,name,descr);
+}
+
+template<typename T>
+AtomsCalculation<T>* World::calcOnAtoms(boost::function<T(atom*)> op,std::string name) {
+  return calcOnAtoms<T>(op,name,AllAtoms());
+}
+
+#endif /* WORLD_CALCULATIONS_HPP_ */
Index: src/analysis_bonds.cpp
===================================================================
--- src/analysis_bonds.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/analysis_bonds.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,4 +9,6 @@
 #include "atom.hpp"
 #include "bond.hpp"
+#include "element.hpp"
+#include "info.hpp"
 #include "log.hpp"
 #include "molecule.hpp"
@@ -37,5 +39,5 @@
   }
   if (((int)Mean % 2) != 0)
-    eLog() << Verbose(1) << "Something is wrong with the bond structure, the number of bonds is not even!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Something is wrong with the bond structure, the number of bonds is not even!" << endl);
   Mean /= (double)AtomCount;
 };
@@ -79,2 +81,193 @@
   }
 };
+
+/** Calculate the angle between \a *first and \a *origin and \a *second and \a *origin.
+ * \param *first first Vector
+ * \param *origin origin of angle taking
+ * \param *second second Vector
+ * \return angle between \a *first and \a *second, both relative to origin at \a *origin.
+ */
+double CalculateAngle(Vector *first, Vector *central, Vector *second)
+{
+  Vector OHBond;
+  Vector OOBond;
+
+  OHBond = (*first) - (*central);
+  OOBond = (*second) - (*central);
+  const double angle = OHBond.Angle(OOBond);
+  return angle;
+};
+
+/** Checks whether the angle between \a *Oxygen and \a *Hydrogen and \a *Oxygen and \a *OtherOxygen is less than 30 degrees.
+ * Note that distance criterion is not checked.
+ * \param *Oxygen first oxygen atom, bonded to \a *Hydrogen
+ * \param *Hydrogen hydrogen bonded to \a *Oxygen
+ * \param *OtherOxygen other oxygen atom
+ * \return true - angle criteria fulfilled, false - criteria not fulfilled, angle greater than 30 degrees.
+ */
+bool CheckHydrogenBridgeBondAngle(atom *Oxygen, atom *Hydrogen, atom *OtherOxygen)
+{
+  Info FunctionInfo(__func__);
+
+  // check angle
+  if (CalculateAngle(&Hydrogen->x, &Oxygen->x, &OtherOxygen->x) < M_PI*(30./180.)) {
+    return true;
+  } else {
+    return false;
+  }
+};
+
+/** Counts the number of hydrogen bridge bonds.
+ * With \a *InterfaceElement an extra element can be specified that identifies some boundary.
+ * Then, counting is for the h-bridges that connect to interface only.
+ * \param *molecules molecules to count bonds
+ * \param *InterfaceElement or NULL
+ */
+int CountHydrogenBridgeBonds(MoleculeListClass *molecules, element * InterfaceElement = NULL)
+{
+  atom *Walker = NULL;
+  atom *Runner = NULL;
+  int count = 0;
+  int OtherHydrogens = 0;
+  double Otherangle = 0.;
+  bool InterfaceFlag = false;
+  bool OtherHydrogenFlag = true;
+  for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin();MolWalker != molecules->ListOfMolecules.end(); MolWalker++) {
+    Walker = (*MolWalker)->start;
+    while (Walker->next != (*MolWalker)->end) {
+      Walker = Walker->next;
+      for (MoleculeList::const_iterator MolRunner = molecules->ListOfMolecules.begin();MolRunner != molecules->ListOfMolecules.end(); MolRunner++) {
+        Runner = (*MolRunner)->start;
+        while (Runner->next != (*MolRunner)->end) {
+          Runner = Runner->next;
+          if ((Walker->type->Z  == 8) && (Runner->type->Z  == 8)) {
+            // check distance
+            const double distance = Runner->x.DistanceSquared(Walker->x);
+            if ((distance > MYEPSILON) && (distance < HBRIDGEDISTANCE*HBRIDGEDISTANCE)) { // distance >0 means  different atoms
+              // on other atom(Runner) we check for bond to interface element and
+              // check that O-O line is not in between the shanks of the two connected hydrogens (Otherangle > 104.5)
+              OtherHydrogenFlag = true;
+              Otherangle = 0.;
+              OtherHydrogens = 0;
+              InterfaceFlag = (InterfaceElement == NULL);
+              for (BondList::const_iterator BondRunner = Runner->ListOfBonds.begin(); BondRunner != Runner->ListOfBonds.end(); BondRunner++) {
+                atom * const OtherAtom = (*BondRunner)->GetOtherAtom(Runner);
+                // if hydrogen, check angle to be greater(!) than 30 degrees
+                if (OtherAtom->type->Z == 1) {
+                  const double angle = CalculateAngle(&OtherAtom->x, &Runner->x, &Walker->x);
+                  OtherHydrogenFlag = OtherHydrogenFlag && (angle > M_PI*(30./180.) + MYEPSILON);
+                  Otherangle += angle;
+                  OtherHydrogens++;
+                }
+                InterfaceFlag = InterfaceFlag || (OtherAtom->type == InterfaceElement);
+              }
+              DoLog(1) && (Log() << Verbose(1) << "Otherangle is " << Otherangle << " for " << OtherHydrogens << " hydrogens." << endl);
+              switch (OtherHydrogens) {
+                case 0:
+                case 1:
+                  break;
+                case 2:
+                  OtherHydrogenFlag = OtherHydrogenFlag && (Otherangle > M_PI*(104.5/180.) + MYEPSILON);
+                  break;
+                default: // 3 or more hydrogens ...
+                  OtherHydrogenFlag = false;
+                  break;
+              }
+              if (InterfaceFlag && OtherHydrogenFlag) {
+                // on this element (Walker) we check for bond to hydrogen, i.e. part of water molecule
+                for (BondList::const_iterator BondRunner = Walker->ListOfBonds.begin(); BondRunner != Walker->ListOfBonds.end(); BondRunner++) {
+                  atom * const OtherAtom = (*BondRunner)->GetOtherAtom(Walker);
+                  if (OtherAtom->type->Z == 1) {
+                    // check angle
+                    if (CheckHydrogenBridgeBondAngle(Walker, OtherAtom, Runner)) {
+                      DoLog(1) && (Log() << Verbose(1) << Walker->Name << ", " << OtherAtom->Name << " and " << Runner->Name << " has a hydrogen bridge bond with distance " << sqrt(distance) << " and angle " << CalculateAngle(&OtherAtom->x, &Walker->x, &Runner->x)*(180./M_PI) << "." << endl);
+                      count++;
+                      break;
+                    }
+                  }
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+  return count;
+}
+
+/** Counts the number of bonds between two given elements.
+ * \param *molecules list of molecules with all atoms
+ * \param *first pointer to first element
+ * \param *second pointer to second element
+ * \return number of found bonds (\a *first-\a *second)
+ */
+int CountBondsOfTwo(MoleculeListClass * const molecules, const element * const first, const element * const second)
+{
+  atom *Walker = NULL;
+  int count = 0;
+
+  for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin();MolWalker != molecules->ListOfMolecules.end(); MolWalker++) {
+    Walker = (*MolWalker)->start;
+    while (Walker->next != (*MolWalker)->end) {
+      Walker = Walker->next;
+      if ((Walker->type == first) || (Walker->type == second)) {  // first element matches
+        for (BondList::const_iterator BondRunner = Walker->ListOfBonds.begin(); BondRunner != Walker->ListOfBonds.end(); BondRunner++) {
+          atom * const OtherAtom = (*BondRunner)->GetOtherAtom(Walker);
+          if (((OtherAtom->type == first) || (OtherAtom->type == second)) && (Walker->nr < OtherAtom->nr)) {
+            count++;
+            DoLog(1) && (Log() << Verbose(1) << first->name << "-" << second->name << " bond found between " << *Walker << " and " << *OtherAtom << "." << endl);
+          }
+        }
+      }
+    }
+  }
+  return count;
+};
+
+/** Counts the number of bonds between three given elements.
+ * Note that we do not look for arbitrary sequence of given bonds, but \a *second will be the central atom and we check
+ * whether it has bonds to both \a *first and \a *third.
+ * \param *molecules list of molecules with all atoms
+ * \param *first pointer to first element
+ * \param *second pointer to second element
+ * \param *third pointer to third element
+ * \return number of found bonds (\a *first-\a *second-\a *third, \a *third-\a *second-\a *first, respectively)
+ */
+int CountBondsOfThree(MoleculeListClass * const molecules, const element * const first, const element * const second, const element * const third)
+{
+  int count = 0;
+  bool MatchFlag[2];
+  bool result = false;
+  atom *Walker = NULL;
+  const element * ElementArray[2];
+  ElementArray[0] = first;
+  ElementArray[1] = third;
+
+  for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin();MolWalker != molecules->ListOfMolecules.end(); MolWalker++) {
+    Walker = (*MolWalker)->start;
+    while (Walker->next != (*MolWalker)->end) {
+      Walker = Walker->next;
+      if (Walker->type == second) {  // first element matches
+        for (int i=0;i<2;i++)
+          MatchFlag[i] = false;
+        for (BondList::const_iterator BondRunner = Walker->ListOfBonds.begin(); BondRunner != Walker->ListOfBonds.end(); BondRunner++) {
+          atom * const OtherAtom = (*BondRunner)->GetOtherAtom(Walker);
+          for (int i=0;i<2;i++)
+            if ((!MatchFlag[i]) && (OtherAtom->type == ElementArray[i])) {
+              MatchFlag[i] = true;
+              break;  // each bonding atom can match at most one element we are looking for
+            }
+        }
+        result = true;
+        for (int i=0;i<2;i++) // gather results
+          result = result && MatchFlag[i];
+        if (result) { // check results
+          count++;
+          DoLog(1) && (Log() << Verbose(1) << first->name << "-" << second->name << "-" << third->name << " bond found at " << *Walker << "." << endl);
+        }
+      }
+    }
+  }
+  return count;
+};
Index: src/analysis_bonds.hpp
===================================================================
--- src/analysis_bonds.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/analysis_bonds.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -18,8 +18,12 @@
 #endif
 
+/*********************************************** defines ***********************************/
+
+#define HBRIDGEDISTANCE 3.5   //!< HBridge distance from PCCP Vol 10. 4802-4813
 
 /****************************************** forward declarations *****************************/
 
 class element;
+class MoleculeListClass;
 class molecule;
 
@@ -29,3 +33,7 @@
 void MinMeanMaxBondDistanceBetweenElements(const molecule *mol, element *type1, element *type2, double &Min, double &Mean, double &Max);
 
+int CountHydrogenBridgeBonds(MoleculeListClass * const molecules, element * InterfaceElement);
+int CountBondsOfTwo(MoleculeListClass * const molecules, const element * const first, const element * const second);
+int CountBondsOfThree(MoleculeListClass * const molecules, const element * const first, const element * const second, const element * const third);
+
 #endif /* ANALYSIS_BONDS_HPP_ */
Index: src/analysis_correlation.cpp
===================================================================
--- src/analysis_correlation.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/analysis_correlation.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -15,6 +15,8 @@
 #include "tesselation.hpp"
 #include "tesselationhelpers.hpp"
+#include "triangleintersectionlist.hpp"
 #include "vector.hpp"
 #include "verbose.hpp"
+#include "World.hpp"
 
 
@@ -34,5 +36,5 @@
 
   if (molecules->ListOfMolecules.empty()) {
-    eLog() << Verbose(1) <<"No molecule given." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) <<"No molecule given." << endl);
     return outmap;
   }
@@ -40,20 +42,20 @@
   for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin(); MolWalker != molecules->ListOfMolecules.end(); MolWalker++)
     if ((*MolWalker)->ActiveFlag) {
-      eLog() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl;
-      atom *Walker = (*MolWalker)->start;
-      while (Walker->next != (*MolWalker)->end) {
-        Walker = Walker->next;
-        Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl;
+      DoeLog(2) && (eLog()<< Verbose(2) << "Current molecule is " << *MolWalker << "." << endl);
+      atom *Walker = (*MolWalker)->start;
+      while (Walker->next != (*MolWalker)->end) {
+        Walker = Walker->next;
+        DoLog(3) && (Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl);
         if ((type1 == NULL) || (Walker->type == type1)) {
           for (MoleculeList::const_iterator MolOtherWalker = MolWalker; MolOtherWalker != molecules->ListOfMolecules.end(); MolOtherWalker++)
             if ((*MolOtherWalker)->ActiveFlag) {
-              Log() << Verbose(2) << "Current other molecule is " << *MolOtherWalker << "." << endl;
+              DoLog(2) && (Log() << Verbose(2) << "Current other molecule is " << *MolOtherWalker << "." << endl);
               atom *OtherWalker = (*MolOtherWalker)->start;
               while (OtherWalker->next != (*MolOtherWalker)->end) { // only go up to Walker
                 OtherWalker = OtherWalker->next;
-                Log() << Verbose(3) << "Current otheratom is " << *OtherWalker << "." << endl;
+                DoLog(3) && (Log() << Verbose(3) << "Current otheratom is " << *OtherWalker << "." << endl);
                 if (Walker->nr < OtherWalker->nr)
                   if ((type2 == NULL) || (OtherWalker->type == type2)) {
-                    distance = Walker->node->PeriodicDistance(OtherWalker->node, (*MolWalker)->cell_size);
+                    distance = Walker->node->PeriodicDistance(*OtherWalker->node, World::getInstance().getDomain());
                     //Log() << Verbose(1) <<"Inserting " << *Walker << " and " << *OtherWalker << endl;
                     outmap->insert ( pair<double, pair <atom *, atom*> > (distance, pair<atom *, atom*> (Walker, OtherWalker) ) );
@@ -90,5 +92,5 @@
 
   if (molecules->ListOfMolecules.empty()) {
-    eLog() << Verbose(1) <<"No molecule given." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) <<"No molecule given." << endl);
     return outmap;
   }
@@ -96,13 +98,13 @@
   for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin(); MolWalker != molecules->ListOfMolecules.end(); MolWalker++)
     if ((*MolWalker)->ActiveFlag) {
-      double * FullMatrix = ReturnFullMatrixforSymmetric((*MolWalker)->cell_size);
+      double * FullMatrix = ReturnFullMatrixforSymmetric(World::getInstance().getDomain());
       double * FullInverseMatrix = InverseMatrix(FullMatrix);
-      eLog() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl;
-      atom *Walker = (*MolWalker)->start;
-      while (Walker->next != (*MolWalker)->end) {
-        Walker = Walker->next;
-        Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl;
+      DoeLog(2) && (eLog()<< Verbose(2) << "Current molecule is " << *MolWalker << "." << endl);
+      atom *Walker = (*MolWalker)->start;
+      while (Walker->next != (*MolWalker)->end) {
+        Walker = Walker->next;
+        DoLog(3) && (Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl);
         if ((type1 == NULL) || (Walker->type == type1)) {
-          periodicX.CopyVector(Walker->node);
+          periodicX = *(Walker->node);
           periodicX.MatrixMultiplication(FullInverseMatrix);  // x now in [0,1)^3
           // go through every range in xyz and get distance
@@ -110,17 +112,16 @@
             for (n[1]=-ranges[1]; n[1] <= ranges[1]; n[1]++)
               for (n[2]=-ranges[2]; n[2] <= ranges[2]; n[2]++) {
-                checkX.Init(n[0], n[1], n[2]);
-                checkX.AddVector(&periodicX);
+                checkX = Vector(n[0], n[1], n[2]) + periodicX;
                 checkX.MatrixMultiplication(FullMatrix);
                 for (MoleculeList::const_iterator MolOtherWalker = MolWalker; MolOtherWalker != molecules->ListOfMolecules.end(); MolOtherWalker++)
                   if ((*MolOtherWalker)->ActiveFlag) {
-                    Log() << Verbose(2) << "Current other molecule is " << *MolOtherWalker << "." << endl;
+                    DoLog(2) && (Log() << Verbose(2) << "Current other molecule is " << *MolOtherWalker << "." << endl);
                     atom *OtherWalker = (*MolOtherWalker)->start;
                     while (OtherWalker->next != (*MolOtherWalker)->end) { // only go up to Walker
                       OtherWalker = OtherWalker->next;
-                      Log() << Verbose(3) << "Current otheratom is " << *OtherWalker << "." << endl;
+                      DoLog(3) && (Log() << Verbose(3) << "Current otheratom is " << *OtherWalker << "." << endl);
                       if (Walker->nr < OtherWalker->nr)
                         if ((type2 == NULL) || (OtherWalker->type == type2)) {
-                          periodicOtherX.CopyVector(OtherWalker->node);
+                          periodicOtherX = *(OtherWalker->node);
                           periodicOtherX.MatrixMultiplication(FullInverseMatrix);  // x now in [0,1)^3
                           // go through every range in xyz and get distance
@@ -128,8 +129,7 @@
                             for (Othern[1]=-ranges[1]; Othern[1] <= ranges[1]; Othern[1]++)
                               for (Othern[2]=-ranges[2]; Othern[2] <= ranges[2]; Othern[2]++) {
-                                checkOtherX.Init(Othern[0], Othern[1], Othern[2]);
-                                checkOtherX.AddVector(&periodicOtherX);
+                                checkOtherX = Vector(Othern[0], Othern[1], Othern[2]) + periodicOtherX;
                                 checkOtherX.MatrixMultiplication(FullMatrix);
-                                distance = checkX.Distance(&checkOtherX);
+                                distance = checkX.distance(checkOtherX);
                                 //Log() << Verbose(1) <<"Inserting " << *Walker << " and " << *OtherWalker << endl;
                                 outmap->insert ( pair<double, pair <atom *, atom*> > (distance, pair<atom *, atom*> (Walker, OtherWalker) ) );
@@ -162,5 +162,5 @@
 
   if (molecules->ListOfMolecules.empty()) {
-    Log() << Verbose(1) <<"No molecule given." << endl;
+    DoLog(1) && (Log() << Verbose(1) <<"No molecule given." << endl);
     return outmap;
   }
@@ -168,12 +168,12 @@
   for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin(); MolWalker != molecules->ListOfMolecules.end(); MolWalker++)
     if ((*MolWalker)->ActiveFlag) {
-      Log() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl;
-      atom *Walker = (*MolWalker)->start;
-      while (Walker->next != (*MolWalker)->end) {
-        Walker = Walker->next;
-        Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl);
+      atom *Walker = (*MolWalker)->start;
+      while (Walker->next != (*MolWalker)->end) {
+        Walker = Walker->next;
+        DoLog(3) && (Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl);
         if ((type == NULL) || (Walker->type == type)) {
-          distance = Walker->node->PeriodicDistance(point, (*MolWalker)->cell_size);
-          Log() << Verbose(4) << "Current distance is " << distance << "." << endl;
+          distance = Walker->node->PeriodicDistance(*point, World::getInstance().getDomain());
+          DoLog(4) && (Log() << Verbose(4) << "Current distance is " << distance << "." << endl);
           outmap->insert ( pair<double, pair<atom *, const Vector*> >(distance, pair<atom *, const Vector*> (Walker, point) ) );
         }
@@ -202,5 +202,5 @@
 
   if (molecules->ListOfMolecules.empty()) {
-    Log() << Verbose(1) <<"No molecule given." << endl;
+    DoLog(1) && (Log() << Verbose(1) <<"No molecule given." << endl);
     return outmap;
   }
@@ -208,13 +208,13 @@
   for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin(); MolWalker != molecules->ListOfMolecules.end(); MolWalker++)
     if ((*MolWalker)->ActiveFlag) {
-      double * FullMatrix = ReturnFullMatrixforSymmetric((*MolWalker)->cell_size);
+      double * FullMatrix = ReturnFullMatrixforSymmetric(World::getInstance().getDomain());
       double * FullInverseMatrix = InverseMatrix(FullMatrix);
-      Log() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl;
-      atom *Walker = (*MolWalker)->start;
-      while (Walker->next != (*MolWalker)->end) {
-        Walker = Walker->next;
-        Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl);
+      atom *Walker = (*MolWalker)->start;
+      while (Walker->next != (*MolWalker)->end) {
+        Walker = Walker->next;
+        DoLog(3) && (Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl);
         if ((type == NULL) || (Walker->type == type)) {
-          periodicX.CopyVector(Walker->node);
+          periodicX = *(Walker->node);
           periodicX.MatrixMultiplication(FullInverseMatrix);  // x now in [0,1)^3
           // go through every range in xyz and get distance
@@ -222,9 +222,8 @@
             for (n[1]=-ranges[1]; n[1] <= ranges[1]; n[1]++)
               for (n[2]=-ranges[2]; n[2] <= ranges[2]; n[2]++) {
-                checkX.Init(n[0], n[1], n[2]);
-                checkX.AddVector(&periodicX);
+                checkX = Vector(n[0], n[1], n[2]) + periodicX;
                 checkX.MatrixMultiplication(FullMatrix);
-                distance = checkX.Distance(point);
-                Log() << Verbose(4) << "Current distance is " << distance << "." << endl;
+                distance = checkX.distance(*point);
+                DoLog(4) && (Log() << Verbose(4) << "Current distance is " << distance << "." << endl);
                 outmap->insert ( pair<double, pair<atom *, const Vector*> >(distance, pair<atom *, const Vector*> (Walker, point) ) );
               }
@@ -255,5 +254,5 @@
 
   if ((Surface == NULL) || (LC == NULL) || (molecules->ListOfMolecules.empty())) {
-    Log() << Verbose(1) <<"No Tesselation, no LinkedCell or no molecule given." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) <<"No Tesselation, no LinkedCell or no molecule given." << endl);
     return outmap;
   }
@@ -261,18 +260,18 @@
   for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin(); MolWalker != molecules->ListOfMolecules.end(); MolWalker++)
     if ((*MolWalker)->ActiveFlag) {
-      Log() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl;
-      atom *Walker = (*MolWalker)->start;
-      while (Walker->next != (*MolWalker)->end) {
-        Walker = Walker->next;
-        Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Current molecule is " << (*MolWalker)->name << "." << endl);
+      atom *Walker = (*MolWalker)->start;
+      while (Walker->next != (*MolWalker)->end) {
+        Walker = Walker->next;
+        //Log() << Verbose(1) << "Current atom is " << *Walker << "." << endl;
         if ((type == NULL) || (Walker->type == type)) {
-          triangle = Surface->FindClosestTriangleToVector(Walker->node, LC );
-          if (triangle != NULL) {
-            distance = DistanceToTrianglePlane(Walker->node, triangle);
-            outmap->insert ( pair<double, pair<atom *, BoundaryTriangleSet*> >(distance, pair<atom *, BoundaryTriangleSet*> (Walker, triangle) ) );
-          }
-        }
-      }
-    }
+          TriangleIntersectionList Intersections(Walker->node,Surface,LC);
+          distance = Intersections.GetSmallestDistance();
+          triangle = Intersections.GetClosestTriangle();
+          outmap->insert ( pair<double, pair<atom *, BoundaryTriangleSet*> >(distance, pair<atom *, BoundaryTriangleSet*> (Walker, triangle) ) );
+        }
+      }
+    } else
+      DoLog(1) && (Log() << Verbose(1) << "molecule " << (*MolWalker)->name << " is not active." << endl);
 
   return outmap;
@@ -304,5 +303,5 @@
 
   if ((Surface == NULL) || (LC == NULL) || (molecules->ListOfMolecules.empty())) {
-    Log() << Verbose(1) <<"No Tesselation, no LinkedCell or no molecule given." << endl;
+    DoLog(1) && (Log() << Verbose(1) <<"No Tesselation, no LinkedCell or no molecule given." << endl);
     return outmap;
   }
@@ -312,13 +311,13 @@
   for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin(); MolWalker != molecules->ListOfMolecules.end(); MolWalker++)
     if ((*MolWalker)->ActiveFlag) {
-      double * FullMatrix = ReturnFullMatrixforSymmetric((*MolWalker)->cell_size);
+      double * FullMatrix = ReturnFullMatrixforSymmetric(World::getInstance().getDomain());
       double * FullInverseMatrix = InverseMatrix(FullMatrix);
-      Log() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl;
-      atom *Walker = (*MolWalker)->start;
-      while (Walker->next != (*MolWalker)->end) {
-        Walker = Walker->next;
-        Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "Current molecule is " << *MolWalker << "." << endl);
+      atom *Walker = (*MolWalker)->start;
+      while (Walker->next != (*MolWalker)->end) {
+        Walker = Walker->next;
+        DoLog(3) && (Log() << Verbose(3) << "Current atom is " << *Walker << "." << endl);
         if ((type == NULL) || (Walker->type == type)) {
-          periodicX.CopyVector(Walker->node);
+          periodicX = *(Walker->node);
           periodicX.MatrixMultiplication(FullInverseMatrix);  // x now in [0,1)^3
           // go through every range in xyz and get distance
@@ -327,9 +326,9 @@
             for (n[1]=-ranges[1]; n[1] <= ranges[1]; n[1]++)
               for (n[2]=-ranges[2]; n[2] <= ranges[2]; n[2]++) {
-                checkX.Init(n[0], n[1], n[2]);
-                checkX.AddVector(&periodicX);
+                checkX = Vector(n[0], n[1], n[2]) + periodicX;
                 checkX.MatrixMultiplication(FullMatrix);
-                triangle = Surface->FindClosestTriangleToVector(&checkX, LC);
-                distance = Surface->GetDistanceSquaredToTriangle(checkX, triangle);
+                TriangleIntersectionList Intersections(&checkX,Surface,LC);
+                distance = Intersections.GetSmallestDistance();
+                triangle = Intersections.GetClosestTriangle();
                 if ((ShortestDistance == -1.) || (distance < ShortestDistance)) {
                   ShortestDistance = distance;
@@ -338,5 +337,4 @@
               }
           // insert
-          ShortestDistance = sqrt(ShortestDistance);
           outmap->insert ( pair<double, pair<atom *, BoundaryTriangleSet*> >(ShortestDistance, pair<atom *, BoundaryTriangleSet*> (Walker, ShortestTriangle) ) );
           //Log() << Verbose(1) << "INFO: Inserting " << Walker << " with distance " << ShortestDistance << " to " << *ShortestTriangle << "." << endl;
@@ -350,14 +348,14 @@
 };
 
-/** Returns the start of the bin for a given value.
+/** Returns the index of the bin for a given value.
  * \param value value whose bin to look for
  * \param BinWidth width of bin
  * \param BinStart first bin
  */
-double GetBin ( const double value, const double BinWidth, const double BinStart )
-{
-  Info FunctionInfo(__func__);
-  double bin =(double) (floor((value - BinStart)/BinWidth));
-  return (bin*BinWidth+BinStart);
+int GetBin ( const double value, const double BinWidth, const double BinStart )
+{
+  Info FunctionInfo(__func__);
+  int bin =(int) (floor((value - BinStart)/BinWidth));
+  return (bin);
 };
 
@@ -372,5 +370,5 @@
   *file << "BinStart\tCount" << endl;
   for (BinPairMap::const_iterator runner = map->begin(); runner != map->end(); ++runner) {
-    *file << runner->first << "\t" << runner->second << endl;
+    *file << setprecision(8) << runner->first << "\t" << runner->second << endl;
   }
 };
@@ -385,5 +383,5 @@
   *file << "BinStart\tAtom1\tAtom2" << endl;
   for (PairCorrelationMap::const_iterator runner = map->begin(); runner != map->end(); ++runner) {
-    *file << runner->first << "\t" << *(runner->second.first) << "\t" << *(runner->second.second) << endl;
+    *file << setprecision(8) << runner->first << "\t" << *(runner->second.first) << "\t" << *(runner->second.second) << endl;
   }
 };
@@ -400,5 +398,5 @@
     *file << runner->first;
     for (int i=0;i<NDIM;i++)
-      *file << "\t" << (runner->second.first->node->x[i] - runner->second.second->x[i]);
+      *file << "\t" << setprecision(8) << (runner->second.first->node->at(i) - runner->second.second->at(i));
     *file << endl;
   }
@@ -413,7 +411,8 @@
   Info FunctionInfo(__func__);
   *file << "BinStart\tTriangle" << endl;
-  for (CorrelationToSurfaceMap::const_iterator runner = map->begin(); runner != map->end(); ++runner) {
-    *file << runner->first << "\t" << *(runner->second.first) << "\t" << *(runner->second.second) << endl;
-  }
-};
-
+  if (!map->empty())
+    for (CorrelationToSurfaceMap::const_iterator runner = map->begin(); runner != map->end(); ++runner) {
+      *file << setprecision(8) << runner->first << "\t" << *(runner->second.first) << "\t" << *(runner->second.second) << endl;
+    }
+};
+
Index: src/analysis_correlation.hpp
===================================================================
--- src/analysis_correlation.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/analysis_correlation.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -51,5 +51,5 @@
 CorrelationToPointMap *PeriodicCorrelationToPoint(MoleculeListClass * const &molecules, const element * const type, const Vector *point, const int ranges[NDIM] );
 CorrelationToSurfaceMap *PeriodicCorrelationToSurface(MoleculeListClass * const &molecules, const element * const type, const Tesselation * const Surface, const LinkedCell *LC, const int ranges[NDIM] );
-double GetBin ( const double value, const double BinWidth, const double BinStart );
+int GetBin ( const double value, const double BinWidth, const double BinStart );
 void OutputCorrelation( ofstream * const file, const BinPairMap * const map );
 void OutputPairCorrelation( ofstream * const file, const PairCorrelationMap * const map );
@@ -71,5 +71,5 @@
 
   if (map == NULL) {
-    eLog() << Verbose(0) << "Nothing to min/max, map is NULL!" << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "Nothing to min/max, map is NULL!" << endl);
     performCriticalExit();
     return;
@@ -103,5 +103,5 @@
 {
   BinPairMap *outmap = new BinPairMap;
-  double bin = 0.;
+  int bin = 0;
   double start = 0.;
   double end = 0.;
@@ -109,5 +109,5 @@
 
   if (map == NULL) {
-    eLog() << Verbose(0) << "Nothing to bin, is NULL!" << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "Nothing to bin, is NULL!" << endl);
     performCriticalExit();
     return outmap;
@@ -122,11 +122,11 @@
     start = BinStart;
     end = BinEnd;
-    for (double runner = start; runner <= end; runner += BinWidth)
-      outmap->insert( pair<double, int> (runner, 0) );
   }
+  for (int runner = 0; runner <= ceil((end-start)/BinWidth); runner++)
+    outmap->insert( pair<double, int> ((double)runner*BinWidth+start, 0) );
 
   for (typename T::iterator runner = map->begin(); runner != map->end(); ++runner) {
     bin = GetBin (runner->first, BinWidth, start);
-    BinPairMapInserter = outmap->insert ( pair<double, int> (bin, 1) );
+    BinPairMapInserter = outmap->insert ( pair<double, int> ((double)bin*BinWidth+start, 1) );
     if (!BinPairMapInserter.second) {  // bin already present, increase
       BinPairMapInserter.first->second += 1;
Index: src/analyzer.cpp
===================================================================
--- src/analyzer.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/analyzer.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -63,14 +63,14 @@
   int counter = 0;
 
-  Log() << Verbose(0) << "ANOVA Analyzer" << endl;
-  Log() << Verbose(0) << "==============" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "ANOVA Analyzer" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "==============" << endl);
 
   // Get the command line options
   if (argc < 4) {
-    Log() << Verbose(0) << "Usage: " << argv[0] << " <inputdir> <prefix> <outputdir> [elementsdb]" << endl;
-    Log() << Verbose(0) << "<inputdir>\ttherein the output of a molecuilder fragmentation is expected, each fragment with a subdir containing an energy.all and a forces.all file." << endl;
-    Log() << Verbose(0) << "<prefix>\tprefix of energy and forces file." << endl;
-    Log() << Verbose(0) << "<outputdir>\tcreated plotfiles and datafiles are placed into this directory " << endl;
-    Log() << Verbose(0) << "[elementsdb]\tpath to elements database, needed for shieldings." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Usage: " << argv[0] << " <inputdir> <prefix> <outputdir> [elementsdb]" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "<inputdir>\ttherein the output of a molecuilder fragmentation is expected, each fragment with a subdir containing an energy.all and a forces.all file." << endl);
+    DoLog(0) && (Log() << Verbose(0) << "<prefix>\tprefix of energy and forces file." << endl);
+    DoLog(0) && (Log() << Verbose(0) << "<outputdir>\tcreated plotfiles and datafiles are placed into this directory " << endl);
+    DoLog(0) && (Log() << Verbose(0) << "[elementsdb]\tpath to elements database, needed for shieldings." << endl);
     return 1;
   } else {
@@ -81,5 +81,5 @@
 
   if (argc > 4) {
-    Log() << Verbose(0) << "Loading periodentafel." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Loading periodentafel." << endl);
     periode = Malloc<periodentafel>(1, "main - periode");
     periode->LoadPeriodentafel(argv[4]);
@@ -96,5 +96,5 @@
   if (!Hcorrection.ParseFragmentMatrix(argv[1], "", HCORRECTIONSUFFIX,0,0)) {
     NoHCorrection = true;
-    eLog() << Verbose(2) << "No HCorrection file found, skipping these." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "No HCorrection file found, skipping these." << endl);
   }
   
@@ -102,9 +102,9 @@
   if (!Hessian.ParseFragmentMatrix(argv[1], dir, HessianSuffix,0,0)) {
     NoHessian = true;
-    eLog() << Verbose(2) << "No Hessian file found, skipping these." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "No Hessian file found, skipping these." << endl);
   }
   if (!Time.ParseFragmentMatrix(argv[1], dir, TimeSuffix, 10,1)) {
     NoTime = true;
-    eLog() << Verbose(2) << "No speed file found, skipping these." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "No speed file found, skipping these." << endl);
   }
   if (periode != NULL) { // also look for PAS values
@@ -248,5 +248,5 @@
   // +++++++++++++++ ANALYZING ++++++++++++++++++++++++++++++
 
-  Log() << Verbose(0) << "Analyzing ..." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Analyzing ..." << endl);
 
   // ======================================= Creating the data files ==============================================================
@@ -559,5 +559,5 @@
   delete(periode);
   Free(&dir);
-  Log() << Verbose(0) << "done." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done." << endl);
   return 0;
 };
Index: src/atom.cpp
===================================================================
--- src/atom.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -20,7 +20,7 @@
 /** Constructor of class atom.
  */
-atom::atom() : previous(NULL), next(NULL), father(this), sort(&nr)
-{
-  World::get()->registerAtom(this);
+atom::atom() :
+  previous(NULL), next(NULL), father(this), sort(&nr)
+{
   node = &x;  // TesselPoint::x can only be referenced from here
 };
@@ -28,14 +28,30 @@
 /** Constructor of class atom.
  */
-atom::atom(atom *pointer) : previous(NULL), next(NULL), father(pointer), sort(&nr)
-{
-  World::get()->registerAtom(this);
+atom::atom(atom *pointer) :
+    ParticleInfo(pointer),
+    previous(NULL), next(NULL), father(pointer), sort(&nr)
+{
   type = pointer->type;  // copy element of atom
-  x.CopyVector(&pointer->x); // copy coordination
-  v.CopyVector(&pointer->v); // copy velocity
+  x = pointer->x; // copy coordination
+  v = pointer->v; // copy velocity
   FixedIon = pointer->FixedIon;
   node = &x;
 };
 
+atom *atom::clone(){
+  atom *res = new atom();
+  res->previous=0;
+  res->next=0;
+  res->father = this;
+  res->sort = &res->nr;
+  res->type = type;
+  res->x = this->x;
+  res->v = this->v;
+  res->FixedIon = FixedIon;
+  res->node = &x;
+  World::getInstance().registerAtom(res);
+  return res;
+}
+
 
 /** Destructor of class atom.
@@ -43,5 +59,4 @@
 atom::~atom()
 {
-  World::get()->unregisterAtom(this);
   unlink(this);
 };
@@ -115,8 +130,8 @@
   if (out != NULL) {
     *out << "Ion_Type" << ElementNo << "_" << AtomNo << "\t"  << fixed << setprecision(9) << showpoint;
-    *out << x.x[0] << "\t" << x.x[1] << "\t" << x.x[2];
+    *out << x[0] << "\t" << x[1] << "\t" << x[2];
     *out << "\t" << FixedIon;
     if (v.Norm() > MYEPSILON)
-      *out << "\t" << scientific << setprecision(6) << v.x[0] << "\t" << v.x[1] << "\t" << v.x[2] << "\t";
+      *out << "\t" << scientific << setprecision(6) << v[0] << "\t" << v[1] << "\t" << v[2] << "\t";
     if (comment != NULL)
       *out << " # " << comment << endl;
@@ -140,8 +155,8 @@
   if (out != NULL) {
     *out << "Ion_Type" << ElementNo[type->Z] << "_" << AtomNo[type->Z] << "\t"  << fixed << setprecision(9) << showpoint;
-    *out << x.x[0] << "\t" << x.x[1] << "\t" << x.x[2];
+    *out << x[0] << "\t" << x[1] << "\t" << x[2];
     *out << "\t" << FixedIon;
     if (v.Norm() > MYEPSILON)
-      *out << "\t" << scientific << setprecision(6) << v.x[0] << "\t" << v.x[1] << "\t" << v.x[2] << "\t";
+      *out << "\t" << scientific << setprecision(6) << v[0] << "\t" << v[1] << "\t" << v[2] << "\t";
     if (comment != NULL)
       *out << " # " << comment << endl;
@@ -160,5 +175,5 @@
 {
   if (out != NULL) {
-    *out << type->symbol << "\t" << x.x[0] << "\t" << x.x[1] << "\t" << x.x[2] << "\t" << endl;
+    *out << type->symbol << "\t" << x[0] << "\t" << x[1] << "\t" << x[2] << "\t" << endl;
     return true;
   } else
@@ -178,10 +193,10 @@
   if (out != NULL) {
     *out << "Ion_Type" << ElementNo[type->Z] << "_" << AtomNo[type->Z] << "\t"  << fixed << setprecision(9) << showpoint;
-    *out << Trajectory.R.at(step).x[0] << "\t" << Trajectory.R.at(step).x[1] << "\t" << Trajectory.R.at(step).x[2];
+    *out << Trajectory.R.at(step)[0] << "\t" << Trajectory.R.at(step)[1] << "\t" << Trajectory.R.at(step)[2];
     *out << "\t" << FixedIon;
     if (Trajectory.U.at(step).Norm() > MYEPSILON)
-      *out << "\t" << scientific << setprecision(6) << Trajectory.U.at(step).x[0] << "\t" << Trajectory.U.at(step).x[1] << "\t" << Trajectory.U.at(step).x[2] << "\t";
+      *out << "\t" << scientific << setprecision(6) << Trajectory.U.at(step)[0] << "\t" << Trajectory.U.at(step)[1] << "\t" << Trajectory.U.at(step)[2] << "\t";
     if (Trajectory.F.at(step).Norm() > MYEPSILON)
-      *out << "\t" << scientific << setprecision(6) << Trajectory.F.at(step).x[0] << "\t" << Trajectory.F.at(step).x[1] << "\t" << Trajectory.F.at(step).x[2] << "\t";
+      *out << "\t" << scientific << setprecision(6) << Trajectory.F.at(step)[0] << "\t" << Trajectory.F.at(step)[1] << "\t" << Trajectory.F.at(step)[2] << "\t";
     *out << "\t# Number in molecule " << nr << endl;
     return true;
@@ -199,7 +214,7 @@
   if (out != NULL) {
     *out << type->symbol << "\t";
-    *out << Trajectory.R.at(step).x[0] << "\t";
-    *out << Trajectory.R.at(step).x[1] << "\t";
-    *out << Trajectory.R.at(step).x[2] << endl;
+    *out << Trajectory.R.at(step)[0] << "\t";
+    *out << Trajectory.R.at(step)[1] << "\t";
+    *out << Trajectory.R.at(step)[2] << endl;
     return true;
   } else
@@ -214,5 +229,5 @@
 void atom::OutputMPQCLine(ofstream * const out, const Vector *center, int *AtomNo = NULL) const
 {
-  *out << "\t\t" << type->symbol << " [ " << x.x[0]-center->x[0] << "\t" << x.x[1]-center->x[1] << "\t" << x.x[2]-center->x[2] << " ]" << endl;
+  *out << "\t\t" << type->symbol << " [ " << x[0]-center->at(0) << "\t" << x[1]-center->at(1) << "\t" << x[2]-center->at(2) << " ]" << endl;
   if (AtomNo != NULL)
     *AtomNo++;
@@ -237,5 +252,5 @@
 double atom::DistanceSquaredToVector(const Vector &origin) const
 {
-  return origin.DistanceSquared(&x);
+  return origin.DistanceSquared(x);
 };
 
@@ -246,5 +261,5 @@
 double atom::DistanceToVector(const Vector &origin) const
 {
-  return origin.Distance(&x);
+  return origin.distance(x);
 };
 
@@ -267,2 +282,39 @@
 };
 
+World *atom::getWorld(){
+  return world;
+}
+
+void atom::setWorld(World* _world){
+  world = _world;
+}
+
+bool atom::changeId(atomId_t newId){
+  // first we move ourselves in the world
+  // the world lets us know if that succeeded
+  if(world->changeAtomId(id,newId,this)){
+    id = newId;
+    return true;
+  }
+  else{
+    return false;
+  }
+}
+
+void atom::setId(atomId_t _id) {
+  id=_id;
+}
+
+atomId_t atom::getId() {
+  return id;
+}
+
+atom* NewAtom(atomId_t _id){
+  atom * res =new atom();
+  res->setId(_id);
+  return res;
+}
+
+void DeleteAtom(atom* atom){
+  delete atom;
+}
Index: src/atom.hpp
===================================================================
--- src/atom.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -28,8 +28,10 @@
 #include "atom_trajectoryparticle.hpp"
 #include "tesselation.hpp"
+#include "types.hpp"
 
 /****************************************** forward declarations *****************************/
 
 class Vector;
+class World;
 
 /********************************************** declarations *******************************/
@@ -39,4 +41,6 @@
  */
 class atom : public TesselPoint, public TrajectoryParticle, public GraphNode, public BondedParticle, public virtual ParticleInfo, public virtual AtomInfo {
+  friend atom* NewAtom(atomId_t);
+  friend void  DeleteAtom(atom*);
   public:
     atom *previous; //!< previous atom in molecule list
@@ -45,7 +49,5 @@
     int *sort;      //!< sort criteria
 
-  atom();
-  atom(class atom *pointer);
-  virtual ~atom();
+  virtual atom *clone();
 
   bool OutputIndexed(ofstream * const out, const int ElementNo, const int AtomNo, const char *comment = NULL) const;
@@ -67,6 +69,61 @@
   bool IsInParallelepiped(const Vector offset, const double *parallelepiped) const;
 
+  // getter and setter
+
+  /**
+   * returns the World that contains this atom.
+   * Use this if you need to get the world without locking
+   * the singleton for example.
+   *
+   */
+  World *getWorld();
+  void setWorld(World*);
+
+  virtual atomId_t getId();
+  virtual bool changeId(atomId_t newId);
+
+  /**
+   * this function sets the Id without notifying the world. Only use it, if the world has already
+   * gotten an ID for this Atom.
+   */
+   virtual void setId(atomId_t);
+
+  protected:
+    /**
+     * Protected constructor to ensure construction of atoms through the world.
+     * see World::createAtom()
+     */
+    atom();
+
+    /**
+     * Protected copy-constructor to ensure construction of atoms by cloning.
+     * see atom::clone()
+     */
+    atom(class atom *pointer);
+
+    /**
+     * Protected destructor to ensure destruction of atoms through the world.
+     * see World::destroyAtom()
+     */
+    virtual ~atom();
   private:
+    World* world;
+    atomId_t id;
 };
 
+/**
+ * internal method used by the world. Do not use if you don't know what you are doing.
+ * You might get burned...
+ * Use World::createAtom() instead.
+ */
+atom* NewAtom(atomId_t _id);
+
+/**
+* internal method used by the world. Do not use if you don't know what you are doing.
+ * You might get burned...
+ * Use World::destroyAtom() instead.
+ */
+void  DeleteAtom(atom*);
+
+
 #endif /* ATOM_HPP_ */
Index: src/atom_atominfo.cpp
===================================================================
--- src/atom_atominfo.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom_atominfo.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -6,4 +6,6 @@
  */
 
+#include "periodentafel.hpp"
+#include "World.hpp"
 #include "atom_atominfo.hpp"
 
@@ -18,2 +20,14 @@
 };
 
+const element *AtomInfo::getType(){
+  return type;
+}
+
+void AtomInfo::setType(const element* _type) {
+  type = _type;
+}
+
+void AtomInfo::setType(int Z) {
+  const element *elem = World::getInstance().getPeriode()->FindElement(Z);
+  setType(elem);
+}
Index: src/atom_atominfo.hpp
===================================================================
--- src/atom_atominfo.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom_atominfo.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -32,8 +32,12 @@
   Vector v;       //!< velocity vector of atom, giving last velocity within cell
   Vector F;       //!< Force vector of atom, giving last force within cell
-  element *type;  //!< pointing to element
+  const element *type;  //!< pointing to element
 
   AtomInfo();
   ~AtomInfo();
+
+  const element *getType();
+  void setType(const element *);
+  void setType(int);
 
 private:
Index: src/atom_bondedparticle.cpp
===================================================================
--- src/atom_bondedparticle.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom_bondedparticle.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -44,11 +44,11 @@
 void BondedParticle::OutputBondOfAtom() const
 {
-  Log() << Verbose(4) << "Atom " << Name << "/" << nr << " with " << ListOfBonds.size() << " bonds: " << endl;
+  DoLog(4) && (Log() << Verbose(4) << "Atom " << Name << "/" << nr << " with " << ListOfBonds.size() << " bonds: " << endl);
   int TotalDegree = 0;
   for (BondList::const_iterator Runner = ListOfBonds.begin(); Runner != ListOfBonds.end(); ++Runner) {
-    Log() << Verbose(4) << **Runner << endl;
+    DoLog(4) && (Log() << Verbose(4) << **Runner << endl);
     TotalDegree += (*Runner)->BondDegree;
   }
-  Log() << Verbose(4) << " -- TotalDegree: " << TotalDegree << endl;
+  DoLog(4) && (Log() << Verbose(4) << " -- TotalDegree: " << TotalDegree << endl);
 };
 
@@ -75,4 +75,20 @@
 };
 
+/**
+ * Adds a bond between this bonded particle and another. Does nothing if this
+ * bond already exists.
+ *
+ * \param bonding partner
+ */
+void BondedParticle::addBond(BondedParticle* Partner) {
+  if (IsBondedTo(Partner)) {
+    return;
+  }
+
+  bond* newBond = new bond((atom*) this, (atom*) Partner, 1, 0);
+  RegisterBond(newBond);
+  Partner->RegisterBond(newBond);
+}
+
 /** Puts a given bond into atom::ListOfBonds.
  * \param *Binder bond to insert
@@ -86,8 +102,8 @@
       status = true;
     } else {
-      eLog() << Verbose(1) << *Binder << " does not contain " << *this << "." << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << *Binder << " does not contain " << *this << "." << endl);
     }
   } else {
-    eLog() << Verbose(1) << "Binder is " << Binder << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Binder is " << Binder << "." << endl);
   }
   return status;
@@ -105,8 +121,8 @@
       status = true;
     } else {
-      eLog() << Verbose(1) << *Binder << " does not contain " << *this << "." << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << *Binder << " does not contain " << *this << "." << endl);
     }
   } else {
-    eLog() << Verbose(1) << "Binder is " << Binder << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Binder is " << Binder << "." << endl);
   }
   return status;
@@ -150,5 +166,5 @@
       //Log() << Verbose(2) << "Increased bond degree for bond " << *CandidateBond << "." << endl;
     } else {
-      eLog() << Verbose(2) << "Could not find correct degree for atom " << *this << "." << endl;
+      DoeLog(2) && (eLog()<< Verbose(2) << "Could not find correct degree for atom " << *this << "." << endl);
       FalseBondDegree++;
     }
Index: src/atom_bondedparticle.hpp
===================================================================
--- src/atom_bondedparticle.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom_bondedparticle.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -37,4 +37,5 @@
   virtual ~BondedParticle();
 
+  void addBond(BondedParticle* Partner);
   bool RegisterBond(bond *Binder);
   bool UnregisterBond(bond *Binder);
Index: src/atom_graphnode.cpp
===================================================================
--- src/atom_graphnode.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom_graphnode.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -27,7 +27,7 @@
 void GraphNode::OutputGraphInfo() const
 {
-  Log() << Verbose(2) << "Atom " << Name << " is " << ((SeparationVertex) ? "a" : "not a") << " separation vertex, components are ";
+  DoLog(2) && (Log() << Verbose(2) << "Atom " << Name << " is " << ((SeparationVertex) ? "a" : "not a") << " separation vertex, components are ");
   OutputComponentNumber();
-  Log() << Verbose(3) << " with Lowpoint " << LowpointNr << " and Graph Nr. " << GraphNr << "." << endl;
+  DoLog(3) && (Log() << Verbose(3) << " with Lowpoint " << LowpointNr << " and Graph Nr. " << GraphNr << "." << endl);
 };
 
@@ -40,5 +40,5 @@
   if (ComponentNr != NULL) {
     for (int i=0; ComponentNr[i] != -1; i++)
-      Log() << Verbose(2) << ComponentNr[i] << " ";
+      DoLog(2) && (Log() << Verbose(2) << ComponentNr[i] << " ");
   }
 };
Index: src/atom_particleinfo.cpp
===================================================================
--- src/atom_particleinfo.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom_particleinfo.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -13,4 +13,13 @@
 ParticleInfo::ParticleInfo() : nr(-1), Name(NULL) {};
 
+ParticleInfo::ParticleInfo(ParticleInfo *pointer) :
+    nr(pointer->nr),
+    Name(pointer->Name)
+    {
+      if (Name == NULL)
+        Name = " ";
+    }
+
+
 /** Destructor of ParticleInfo.
  */
@@ -20,11 +29,10 @@
 };
 
-int ParticleInfo::getId() {
-  return nr;
-}
-
 ostream & operator << (ostream &ost, const ParticleInfo &a)
 {
-  ost << "[" << a.Name << "|" << &a << "]";
+  if (a.Name == NULL)
+    ost << "[NULL]";
+  else
+    ost << "[" << a.Name << "|" << &a << "]";
   return ost;
 };
@@ -32,5 +40,8 @@
 ostream & ParticleInfo::operator << (ostream &ost) const
 {
-  ost << "[" << Name << "|" << this << "]";
+  if (Name == NULL)
+    ost << "[NULL]";
+  else
+    ost << "[" << Name << "|" << this << "]";
   return ost;
 };
Index: src/atom_particleinfo.hpp
===================================================================
--- src/atom_particleinfo.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom_particleinfo.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -31,9 +31,8 @@
 
   ParticleInfo();
+  ParticleInfo(ParticleInfo*);
   ~ParticleInfo();
 
   ostream & operator << (ostream &ost) const;
-
-  virtual int getId();
 
 private:
Index: src/atom_trajectoryparticle.cpp
===================================================================
--- src/atom_trajectoryparticle.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/atom_trajectoryparticle.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -34,5 +34,5 @@
 {
   for (int i=NDIM;i--;)
-    *temperature += type->mass * Trajectory.U.at(step).x[i]* Trajectory.U.at(step).x[i];
+    *temperature += type->mass * Trajectory.U.at(step)[i]* Trajectory.U.at(step)[i];
 };
 
@@ -49,5 +49,5 @@
   // set forces
   for (int i=NDIM;i++;)
-    Force->Matrix[0][nr][5+i] += 2.*constant*sqrt(Trajectory.R.at(startstep).Distance(&Sprinter->Trajectory.R.at(endstep)));
+    Force->Matrix[0][nr][5+i] += 2.*constant*sqrt(Trajectory.R.at(startstep).distance(Sprinter->Trajectory.R.at(endstep)));
 };
 
@@ -60,6 +60,6 @@
 {
   for(int d=0;d<NDIM;d++) {
-    Trajectory.U.at(Step).x[d] -= CoGVelocity->x[d];
-    *ActualTemp += 0.5 * type->mass * Trajectory.U.at(Step).x[d] * Trajectory.U.at(Step).x[d];
+    Trajectory.U.at(Step)[d] -= CoGVelocity->at(d);
+    *ActualTemp += 0.5 * type->mass * Trajectory.U.at(Step)[d] * Trajectory.U.at(Step)[d];
   }
 };
@@ -89,7 +89,7 @@
 
   for (int n=NDIM;n--;) {
-    Trajectory.R.at(dest).x[n] = Trajectory.R.at(src).x[n];
-    Trajectory.U.at(dest).x[n] = Trajectory.U.at(src).x[n];
-    Trajectory.F.at(dest).x[n] = Trajectory.F.at(src).x[n];
+    Trajectory.R.at(dest)[n] = Trajectory.R.at(src)[n];
+    Trajectory.U.at(dest)[n] = Trajectory.U.at(src)[n];
+    Trajectory.F.at(dest)[n] = Trajectory.F.at(src)[n];
   }
 };
@@ -105,13 +105,13 @@
   //a = configuration.Deltat*0.5/walker->type->mass;        // (F+F_old)/2m = a and thus: v = (F+F_old)/2m * t = (F + F_old) * a
   for (int d=0; d<NDIM; d++) {
-    Trajectory.F.at(NextStep).x[d] = -Force->Matrix[0][nr][d+5]*(configuration->GetIsAngstroem() ? AtomicLengthToAngstroem : 1.);
-    Trajectory.R.at(NextStep).x[d] = Trajectory.R.at(NextStep-1).x[d];
-    Trajectory.R.at(NextStep).x[d] += configuration->Deltat*(Trajectory.U.at(NextStep-1).x[d]);     // s(t) = s(0) + v * deltat + 1/2 a * deltat^2
-    Trajectory.R.at(NextStep).x[d] += 0.5*configuration->Deltat*configuration->Deltat*(Trajectory.F.at(NextStep).x[d]/type->mass);     // F = m * a and s =
+    Trajectory.F.at(NextStep)[d] = -Force->Matrix[0][nr][d+5]*(configuration->GetIsAngstroem() ? AtomicLengthToAngstroem : 1.);
+    Trajectory.R.at(NextStep)[d] = Trajectory.R.at(NextStep-1)[d];
+    Trajectory.R.at(NextStep)[d] += configuration->Deltat*(Trajectory.U.at(NextStep-1)[d]);     // s(t) = s(0) + v * deltat + 1/2 a * deltat^2
+    Trajectory.R.at(NextStep)[d] += 0.5*configuration->Deltat*configuration->Deltat*(Trajectory.F.at(NextStep)[d]/type->mass);     // F = m * a and s =
   }
   // Update U
   for (int d=0; d<NDIM; d++) {
-    Trajectory.U.at(NextStep).x[d] = Trajectory.U.at(NextStep-1).x[d];
-    Trajectory.U.at(NextStep).x[d] += configuration->Deltat * (Trajectory.F.at(NextStep).x[d]+Trajectory.F.at(NextStep-1).x[d]/type->mass); // v = F/m * t
+    Trajectory.U.at(NextStep)[d] = Trajectory.U.at(NextStep-1)[d];
+    Trajectory.U.at(NextStep)[d] += configuration->Deltat * (Trajectory.F.at(NextStep)[d]+Trajectory.F.at(NextStep-1)[d]/type->mass); // v = F/m * t
   }
   // Update R (and F)
@@ -134,5 +134,5 @@
   *TotalMass += type->mass;  // sum up total mass
   for(int d=0;d<NDIM;d++) {
-    TotalVelocity->x[d] += Trajectory.U.at(Step).x[d]*type->mass;
+    TotalVelocity->at(d) += Trajectory.U.at(Step)[d]*type->mass;
   }
 };
@@ -145,5 +145,5 @@
 void TrajectoryParticle::Thermostat_Woodcock(double ScaleTempFactor, int Step, double *ekin)
 {
-  double *U = Trajectory.U.at(Step).x;
+  Vector &U = Trajectory.U.at(Step);
   if (FixedIon == 0) // even FixedIon moves, only not by other's forces
     for (int d=0; d<NDIM; d++) {
@@ -160,6 +160,6 @@
 void TrajectoryParticle::Thermostat_Gaussian_init(int Step, double *G, double *E)
 {
-  double *U = Trajectory.U.at(Step).x;
-  double *F = Trajectory.F.at(Step).x;
+  Vector &U = Trajectory.U.at(Step);
+  Vector &F = Trajectory.F.at(Step);
   if (FixedIon == 0) // even FixedIon moves, only not by other's forces
     for (int d=0; d<NDIM; d++) {
@@ -177,5 +177,5 @@
 void TrajectoryParticle::Thermostat_Gaussian_least_constraint(int Step, double G_over_E, double *ekin, config *configuration)
 {
-  double *U = Trajectory.U.at(Step).x;
+  Vector &U = Trajectory.U.at(Step);
   if (FixedIon == 0) // even FixedIon moves, only not by other's forces
     for (int d=0; d<NDIM; d++) {
@@ -194,14 +194,14 @@
 {
   double sigma  = sqrt(configuration->TargetTemp/type->mass); // sigma = (k_b T)/m (Hartree/atomicmass = atomiclength/atomictime)
-  double *U = Trajectory.U.at(Step).x;
+  Vector &U = Trajectory.U.at(Step);
   if (FixedIon == 0) { // even FixedIon moves, only not by other's forces
     // throw a dice to determine whether it gets hit by a heat bath particle
     if (((((rand()/(double)RAND_MAX))*configuration->TempFrequency) < 1.)) {
-      Log() << Verbose(3) << "Particle " << *this << " was hit (sigma " << sigma << "): " << sqrt(U[0]*U[0]+U[1]*U[1]+U[2]*U[2]) << " -> ";
+      DoLog(3) && (Log() << Verbose(3) << "Particle " << *this << " was hit (sigma " << sigma << "): " << sqrt(U[0]*U[0]+U[1]*U[1]+U[2]*U[2]) << " -> ");
       // pick three random numbers from a Boltzmann distribution around the desired temperature T for each momenta axis
       for (int d=0; d<NDIM; d++) {
         U[d] = gsl_ran_gaussian (r, sigma);
       }
-      Log() << Verbose(2) << sqrt(U[0]*U[0]+U[1]*U[1]+U[2]*U[2]) << endl;
+      DoLog(2) && (Log() << Verbose(2) << sqrt(U[0]*U[0]+U[1]*U[1]+U[2]*U[2]) << endl);
     }
     for (int d=0; d<NDIM; d++)
@@ -218,5 +218,5 @@
 void TrajectoryParticle::Thermostat_Berendsen(int Step, double ScaleTempFactor, double *ekin, config *configuration)
 {
-  double *U = Trajectory.U.at(Step).x;
+  Vector &U = Trajectory.U.at(Step);
   if (FixedIon == 0) { // even FixedIon moves, only not by other's forces
     for (int d=0; d<NDIM; d++) {
@@ -233,5 +233,5 @@
 void TrajectoryParticle::Thermostat_NoseHoover_init(int Step, double *delta_alpha)
 {
-  double *U = Trajectory.U.at(Step).x;
+  Vector &U = Trajectory.U.at(Step);
   if (FixedIon == 0) { // even FixedIon moves, only not by other's forces
     for (int d=0; d<NDIM; d++) {
@@ -248,5 +248,5 @@
 void TrajectoryParticle::Thermostat_NoseHoover_scale(int Step, double *ekin, config *configuration)
 {
-  double *U = Trajectory.U.at(Step).x;
+  Vector &U = Trajectory.U.at(Step);
   if (FixedIon == 0) { // even FixedIon moves, only not by other's forces
     for (int d=0; d<NDIM; d++) {
Index: src/bond.cpp
===================================================================
--- src/bond.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/bond.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -15,5 +15,7 @@
 /** Empty Constructor for class bond.
  */
-bond::bond() : leftatom(NULL), rightatom(NULL), previous(NULL), next(NULL), HydrogenBond(0), BondDegree(0), nr(-1), Cyclic(false), Type(Undetermined), Used(white)
+bond::bond()
+  : leftatom(NULL), rightatom(NULL), previous(NULL), next(NULL), HydrogenBond(0),
+    BondDegree(0), nr(-1), Cyclic(false), Type(Undetermined), Used(white)
 {
 };
@@ -25,5 +27,7 @@
  * \param number increasing index
  */
-bond::bond(atom *left, atom *right, const int degree, const int number) : leftatom(left), rightatom(right), previous(NULL), next(NULL), HydrogenBond(0), BondDegree(degree), nr(number), Cyclic(false), Type(Undetermined), Used(white)
+bond::bond(atom *left, atom *right, const int degree, const int number)
+  : leftatom(left), rightatom(right), previous(NULL), next(NULL), HydrogenBond(0),
+    BondDegree(degree), nr(number), Cyclic(false), Type(Undetermined), Used(white)
 {
   if ((left != NULL) && (right != NULL)) {
@@ -63,5 +67,5 @@
   if(rightatom == Atom) 
     return leftatom;
-  eLog() << Verbose(1) << "Bond " << *this << " does not contain atom " << *Atom << "!" << endl;
+  DoeLog(1) && (eLog()<< Verbose(1) << "Bond " << *this << " does not contain atom " << *Atom << "!" << endl);
   return NULL;
 };
@@ -99,5 +103,5 @@
 bool bond::MarkUsed(const enum Shading color) {
   if (Used == black) {
-    eLog() << Verbose(1) << "Bond " << this << " was already marked black!." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Bond " << this << " was already marked black!." << endl);
     return false;
   } else {
@@ -119,5 +123,5 @@
 double bond::GetDistance() const
 {
-  return (leftatom->node->Distance(rightatom->node));
+  return (leftatom->node->distance(*rightatom->node));
 };
 
@@ -127,4 +131,4 @@
 double bond::GetDistanceSquared() const
 {
-  return (leftatom->node->DistanceSquared(rightatom->node));
+  return (leftatom->node->DistanceSquared(*rightatom->node));
 };
Index: src/bondgraph.cpp
===================================================================
--- src/bondgraph.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/bondgraph.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,4 +9,5 @@
 
 #include "atom.hpp"
+#include "bond.hpp"
 #include "bondgraph.hpp"
 #include "element.hpp"
@@ -49,5 +50,5 @@
   // allocate MatrixContainer
   if (BondLengthMatrix != NULL) {
-    Log() << Verbose(1) << "MatrixContainer for Bond length already present, removing." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "MatrixContainer for Bond length already present, removing." << endl);
     delete(BondLengthMatrix);
   }
@@ -55,8 +56,8 @@
 
   // parse in matrix
-  if (status = TempContainer->ParseMatrix(filename.c_str(), 0, 1, 0)) {
-    Log() << Verbose(1) << "Parsing bond length matrix successful." << endl;
+  if ((status = TempContainer->ParseMatrix(filename.c_str(), 0, 1, 0))) {
+    DoLog(1) && (Log() << Verbose(1) << "Parsing bond length matrix successful." << endl);
   } else {
-    eLog() << Verbose(1) << "Parsing bond length matrix failed." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Parsing bond length matrix failed." << endl);
   }
 
@@ -86,5 +87,6 @@
 bool BondGraph::ConstructBondGraph(molecule * const mol)
 {
-  bool status = true;
+  Info FunctionInfo(__func__);
+bool status = true;
 
   if (mol->start->next == mol->end) // only construct if molecule is not empty
@@ -119,4 +121,5 @@
 double BondGraph::SetMaxDistanceToMaxOfCovalentRadii(const molecule * const mol)
 {
+  Info FunctionInfo(__func__);
   max_distance = 0.;
 
@@ -159,5 +162,5 @@
 {
   if (BondLengthMatrix == NULL) {// safety measure if no matrix has been parsed yet
-    eLog() << Verbose(2) << "BondLengthMatrixMinMaxDistance() called without having parsed the bond length matrix yet!" << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "BondLengthMatrixMinMaxDistance() called without having parsed the bond length matrix yet!" << endl);
     CovalentMinMaxDistance(Walker, OtherWalker, MinDistance, MaxDistance, IsAngstroem);
   } else {
@@ -168,3 +171,2 @@
   }
 };
-
Index: src/bondgraph.hpp
===================================================================
--- src/bondgraph.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/bondgraph.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -19,4 +19,8 @@
 
 #include <iostream>
+
+/*********************************************** defines ***********************************/
+
+#define BONDTHRESHOLD 0.4   //!< CSD threshold in bond check which is the width of the interval whose center is the sum of the covalent radii
 
 /****************************************** forward declarations *****************************/
Index: src/boundary.cpp
===================================================================
--- src/boundary.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/boundary.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -4,4 +4,5 @@
  */
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
@@ -17,4 +18,6 @@
 #include "tesselation.hpp"
 #include "tesselationhelpers.hpp"
+#include "World.hpp"
+#include "Plane.hpp"
 
 #include<gsl/gsl_poly.h>
@@ -56,5 +59,5 @@
   } else {
     BoundaryPoints = BoundaryPtr;
-    Log() << Verbose(0) << "Using given boundary points set." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Using given boundary points set." << endl);
   }
   // determine biggest "diameter" of cluster for each axis
@@ -76,17 +79,15 @@
               if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
                 Neighbour = BoundaryPoints[axis].begin();
-              DistanceVector.CopyVector(&runner->second.second->x);
-              DistanceVector.SubtractVector(&Neighbour->second.second->x);
+              DistanceVector = runner->second.second->x - Neighbour->second.second->x;
               do { // seek for neighbour pair where it flips
-                  OldComponent = DistanceVector.x[Othercomponent];
+                  OldComponent = DistanceVector[Othercomponent];
                   Neighbour++;
                   if (Neighbour == BoundaryPoints[axis].end()) // make it wrap around
                     Neighbour = BoundaryPoints[axis].begin();
-                  DistanceVector.CopyVector(&runner->second.second->x);
-                  DistanceVector.SubtractVector(&Neighbour->second.second->x);
+                  DistanceVector = runner->second.second->x - Neighbour->second.second->x;
                   //Log() << Verbose(2) << "OldComponent is " << OldComponent << ", new one is " << DistanceVector.x[Othercomponent] << "." << endl;
                 } while ((runner != Neighbour) && (fabs(OldComponent / fabs(
-                  OldComponent) - DistanceVector.x[Othercomponent] / fabs(
-                  DistanceVector.x[Othercomponent])) < MYEPSILON)); // as long as sign does not flip
+                  OldComponent) - DistanceVector[Othercomponent] / fabs(
+                  DistanceVector[Othercomponent])) < MYEPSILON)); // as long as sign does not flip
               if (runner != Neighbour) {
                   OtherNeighbour = Neighbour;
@@ -96,13 +97,12 @@
                   //Log() << Verbose(1) << "The pair, where the sign of OtherComponent flips, is: " << *(Neighbour->second.second) << " and " << *(OtherNeighbour->second.second) << "." << endl;
                   // now we have found the pair: Neighbour and OtherNeighbour
-                  OtherVector.CopyVector(&runner->second.second->x);
-                  OtherVector.SubtractVector(&OtherNeighbour->second.second->x);
+                  OtherVector = runner->second.second->x - OtherNeighbour->second.second->x;
                   //Log() << Verbose(1) << "Distances to Neighbour and OtherNeighbour are " << DistanceVector.x[component] << " and " << OtherVector.x[component] << "." << endl;
                   //Log() << Verbose(1) << "OtherComponents to Neighbour and OtherNeighbour are " << DistanceVector.x[Othercomponent] << " and " << OtherVector.x[Othercomponent] << "." << endl;
                   // do linear interpolation between points (is exact) to extract exact intersection between Neighbour and OtherNeighbour
-                  w1 = fabs(OtherVector.x[Othercomponent]);
-                  w2 = fabs(DistanceVector.x[Othercomponent]);
-                  tmp = fabs((w1 * DistanceVector.x[component] + w2
-                      * OtherVector.x[component]) / (w1 + w2));
+                  w1 = fabs(OtherVector[Othercomponent]);
+                  w2 = fabs(DistanceVector[Othercomponent]);
+                  tmp = fabs((w1 * DistanceVector[component] + w2
+                      * OtherVector[component]) / (w1 + w2));
                   // mark if it has greater diameter
                   //Log() << Verbose(1) << "Comparing current greatest " << GreatestDiameter[component] << " to new " << tmp << "." << endl;
@@ -158,9 +158,9 @@
     AngleReferenceVector.Zero();
     AngleReferenceNormalVector.Zero();
-    AxisVector.x[axis] = 1.;
-    AngleReferenceVector.x[(axis + 1) % NDIM] = 1.;
-    AngleReferenceNormalVector.x[(axis + 2) % NDIM] = 1.;
-
-    Log() << Verbose(1) << "Axisvector is " << AxisVector << " and AngleReferenceVector is " << AngleReferenceVector << ", and AngleReferenceNormalVector is " << AngleReferenceNormalVector << "." << endl;
+    AxisVector[axis] = 1.;
+    AngleReferenceVector[(axis + 1) % NDIM] = 1.;
+    AngleReferenceNormalVector[(axis + 2) % NDIM] = 1.;
+
+    DoLog(1) && (Log() << Verbose(1) << "Axisvector is " << AxisVector << " and AngleReferenceVector is " << AngleReferenceVector << ", and AngleReferenceNormalVector is " << AngleReferenceNormalVector << "." << endl);
 
     // 3b. construct set of all points, transformed into cylindrical system and with left and right neighbours
@@ -168,44 +168,41 @@
     while (Walker->next != mol->end) {
       Walker = Walker->next;
-      ProjectedVector.CopyVector(&Walker->x);
-      ProjectedVector.SubtractVector(MolCenter);
-      ProjectedVector.ProjectOntoPlane(&AxisVector);
+      ProjectedVector = Walker->x - (*MolCenter);
+      ProjectedVector.ProjectOntoPlane(AxisVector);
 
       // correct for negative side
       const double radius = ProjectedVector.NormSquared();
       if (fabs(radius) > MYEPSILON)
-        angle = ProjectedVector.Angle(&AngleReferenceVector);
+        angle = ProjectedVector.Angle(AngleReferenceVector);
       else
         angle = 0.; // otherwise it's a vector in Axis Direction and unimportant for boundary issues
 
       //Log() << Verbose(1) << "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << "." << endl;
-      if (ProjectedVector.ScalarProduct(&AngleReferenceNormalVector) > 0) {
+      if (ProjectedVector.ScalarProduct(AngleReferenceNormalVector) > 0) {
         angle = 2. * M_PI - angle;
       }
-      Log() << Verbose(1) << "Inserting " << *Walker << ": (r, alpha) = (" << radius << "," << angle << "): " << ProjectedVector << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Inserting " << *Walker << ": (r, alpha) = (" << radius << "," << angle << "): " << ProjectedVector << endl);
       BoundaryTestPair = BoundaryPoints[axis].insert(BoundariesPair(angle, DistancePair (radius, Walker)));
       if (!BoundaryTestPair.second) { // same point exists, check first r, then distance of original vectors to center of gravity
-        Log() << Verbose(2) << "Encountered two vectors whose projection onto axis " << axis << " is equal: " << endl;
-        Log() << Verbose(2) << "Present vector: " << *BoundaryTestPair.first->second.second << endl;
-        Log() << Verbose(2) << "New vector: " << *Walker << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Encountered two vectors whose projection onto axis " << axis << " is equal: " << endl);
+        DoLog(2) && (Log() << Verbose(2) << "Present vector: " << *BoundaryTestPair.first->second.second << endl);
+        DoLog(2) && (Log() << Verbose(2) << "New vector: " << *Walker << endl);
         const double ProjectedVectorNorm = ProjectedVector.NormSquared();
         if ((ProjectedVectorNorm - BoundaryTestPair.first->second.first) > MYEPSILON) {
           BoundaryTestPair.first->second.first = ProjectedVectorNorm;
           BoundaryTestPair.first->second.second = Walker;
-          Log() << Verbose(2) << "Keeping new vector due to larger projected distance " << ProjectedVectorNorm << "." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "Keeping new vector due to larger projected distance " << ProjectedVectorNorm << "." << endl);
         } else if (fabs(ProjectedVectorNorm - BoundaryTestPair.first->second.first) < MYEPSILON) {
-          helper.CopyVector(&Walker->x);
-          helper.SubtractVector(MolCenter);
+          helper = Walker->x - (*MolCenter);
           const double oldhelperNorm = helper.NormSquared();
-          helper.CopyVector(&BoundaryTestPair.first->second.second->x);
-          helper.SubtractVector(MolCenter);
+          helper = BoundaryTestPair.first->second.second->x - (*MolCenter);
           if (helper.NormSquared() < oldhelperNorm) {
             BoundaryTestPair.first->second.second = Walker;
-            Log() << Verbose(2) << "Keeping new vector due to larger distance to molecule center " << helper.NormSquared() << "." << endl;
+            DoLog(2) && (Log() << Verbose(2) << "Keeping new vector due to larger distance to molecule center " << helper.NormSquared() << "." << endl);
           } else {
-            Log() << Verbose(2) << "Keeping present vector due to larger distance to molecule center " << oldhelperNorm << "." << endl;
+            DoLog(2) && (Log() << Verbose(2) << "Keeping present vector due to larger distance to molecule center " << oldhelperNorm << "." << endl);
           }
         } else {
-          Log() << Verbose(2) << "Keeping present vector due to larger projected distance " << ProjectedVectorNorm << "." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "Keeping present vector due to larger projected distance " << ProjectedVectorNorm << "." << endl);
         }
       }
@@ -226,5 +223,5 @@
     // 3c. throw out points whose distance is less than the mean of left and right neighbours
     bool flag = false;
-    Log() << Verbose(1) << "Looking for candidates to kick out by convex condition ... " << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Looking for candidates to kick out by convex condition ... " << endl);
     do { // do as long as we still throw one out per round
       flag = false;
@@ -249,22 +246,18 @@
         {
           Vector SideA, SideB, SideC, SideH;
-          SideA.CopyVector(&left->second.second->x);
-          SideA.SubtractVector(MolCenter);
-          SideA.ProjectOntoPlane(&AxisVector);
+          SideA = left->second.second->x - (*MolCenter);
+          SideA.ProjectOntoPlane(AxisVector);
           //          Log() << Verbose(1) << "SideA: " << SideA << endl;
 
-          SideB.CopyVector(&right->second.second->x);
-          SideB.SubtractVector(MolCenter);
-          SideB.ProjectOntoPlane(&AxisVector);
+          SideB = right->second.second->x -(*MolCenter);
+          SideB.ProjectOntoPlane(AxisVector);
           //          Log() << Verbose(1) << "SideB: " << SideB << endl;
 
-          SideC.CopyVector(&left->second.second->x);
-          SideC.SubtractVector(&right->second.second->x);
-          SideC.ProjectOntoPlane(&AxisVector);
+          SideC = left->second.second->x - right->second.second->x;
+          SideC.ProjectOntoPlane(AxisVector);
           //          Log() << Verbose(1) << "SideC: " << SideC << endl;
 
-          SideH.CopyVector(&runner->second.second->x);
-          SideH.SubtractVector(MolCenter);
-          SideH.ProjectOntoPlane(&AxisVector);
+          SideH = runner->second.second->x -(*MolCenter);
+          SideH.ProjectOntoPlane(AxisVector);
           //          Log() << Verbose(1) << "SideH: " << SideH << endl;
 
@@ -275,14 +268,14 @@
           const double h = SideH.Norm();
           // calculate the angles
-          const double alpha = SideA.Angle(&SideH);
-          const double beta = SideA.Angle(&SideC);
-          const double gamma = SideB.Angle(&SideH);
-          const double delta = SideC.Angle(&SideH);
+          const double alpha = SideA.Angle(SideH);
+          const double beta = SideA.Angle(SideC);
+          const double gamma = SideB.Angle(SideH);
+          const double delta = SideC.Angle(SideH);
           const double MinDistance = a * sin(beta) / (sin(delta)) * (((alpha < M_PI / 2.) || (gamma < M_PI / 2.)) ? 1. : -1.);
           //Log() << Verbose(1) << " I calculated: a = " << a << ", h = " << h << ", beta(" << left->second.second->Name << "," << left->second.second->Name << "-" << right->second.second->Name << ") = " << beta << ", delta(" << left->second.second->Name << "," << runner->second.second->Name << ") = " << delta << ", Min = " << MinDistance << "." << endl;
-          Log() << Verbose(1) << "Checking CoG distance of runner " << *runner->second.second << " " << h << " against triangle's side length spanned by (" << *left->second.second << "," << *right->second.second << ") of " << MinDistance << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "Checking CoG distance of runner " << *runner->second.second << " " << h << " against triangle's side length spanned by (" << *left->second.second << "," << *right->second.second << ") of " << MinDistance << "." << endl);
           if ((fabs(h / fabs(h) - MinDistance / fabs(MinDistance)) < MYEPSILON) && ((h - MinDistance)) < -MYEPSILON) {
             // throw out point
-            Log() << Verbose(1) << "Throwing out " << *runner->second.second << "." << endl;
+            DoLog(1) && (Log() << Verbose(1) << "Throwing out " << *runner->second.second << "." << endl);
             BoundaryPoints[axis].erase(runner);
             flag = true;
@@ -319,5 +312,5 @@
       BoundaryPoints = GetBoundaryPoints(mol, TesselStruct);
   } else {
-      Log() << Verbose(0) << "Using given boundary points set." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Using given boundary points set." << endl);
   }
 
@@ -325,14 +318,14 @@
   for (int axis=0; axis < NDIM; axis++)
     {
-      Log() << Verbose(1) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl);
       int i=0;
       for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
         if (runner != BoundaryPoints[axis].begin())
-          Log() << Verbose(0) << ", " << i << ": " << *runner->second.second;
+          DoLog(0) && (Log() << Verbose(0) << ", " << i << ": " << *runner->second.second);
         else
-          Log() << Verbose(0) << i << ": " << *runner->second.second;
+          DoLog(0) && (Log() << Verbose(0) << i << ": " << *runner->second.second);
         i++;
       }
-      Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << endl);
     }
 
@@ -341,7 +334,7 @@
     for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++)
         if (!TesselStruct->AddBoundaryPoint(runner->second.second, 0))
-          eLog() << Verbose(2) << "Point " << *(runner->second.second) << " is already present!" << endl;
-
-  Log() << Verbose(0) << "I found " << TesselStruct->PointsOnBoundaryCount << " points on the convex boundary." << endl;
+          DoeLog(2) && (eLog()<< Verbose(2) << "Point " << *(runner->second.second) << " is already present!" << endl);
+
+  DoLog(0) && (Log() << Verbose(0) << "I found " << TesselStruct->PointsOnBoundaryCount << " points on the convex boundary." << endl);
   // now we have the whole set of edge points in the BoundaryList
 
@@ -361,7 +354,7 @@
   // 3c. check whether all atoms lay inside the boundary, if not, add to boundary points, segment triangle into three with the new point
   if (!TesselStruct->InsertStraddlingPoints(mol, LCList))
-    eLog() << Verbose(1) << "Insertion of straddling points failed!" << endl;
-
-  Log() << Verbose(0) << "I created " << TesselStruct->TrianglesOnBoundary.size() << " intermediate triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Insertion of straddling points failed!" << endl);
+
+  DoLog(0) && (Log() << Verbose(0) << "I created " << TesselStruct->TrianglesOnBoundary.size() << " intermediate triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points." << endl);
 
   // 4. Store triangles in tecplot file
@@ -394,14 +387,14 @@
     for (LineMap::iterator LineRunner = TesselStruct->LinesOnBoundary.begin(); LineRunner != TesselStruct->LinesOnBoundary.end(); LineRunner++) {
       line = LineRunner->second;
-      Log() << Verbose(1) << "INFO: Current line is " << *line << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "INFO: Current line is " << *line << "." << endl);
       if (!line->CheckConvexityCriterion()) {
-        Log() << Verbose(1) << "... line " << *line << " is concave, flipping it." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "... line " << *line << " is concave, flipping it." << endl);
 
         // flip the line
         if (TesselStruct->PickFarthestofTwoBaselines(line) == 0.)
-          eLog() << Verbose(1) << "Correction of concave baselines failed!" << endl;
+          DoeLog(1) && (eLog()<< Verbose(1) << "Correction of concave baselines failed!" << endl);
         else {
           TesselStruct->FlipBaseline(line);
-          Log() << Verbose(1) << "INFO: Correction of concave baselines worked." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "INFO: Correction of concave baselines worked." << endl);
         }
       }
@@ -413,5 +406,5 @@
 //    Log() << Verbose(1) << "Correction of concave tesselpoints failed!" << endl;
 
-  Log() << Verbose(0) << "I created " << TesselStruct->TrianglesOnBoundary.size() << " triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "I created " << TesselStruct->TrianglesOnBoundary.size() << " triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points." << endl);
 
   // 4. Store triangles in tecplot file
@@ -455,5 +448,5 @@
 
   if ((TesselStruct == NULL) || (TesselStruct->PointsOnBoundary.empty())) {
-    eLog() << Verbose(1) << "TesselStruct is empty." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "TesselStruct is empty." << endl);
     return false;
   }
@@ -461,8 +454,8 @@
   PointMap::iterator PointRunner;
   while (!TesselStruct->PointsOnBoundary.empty()) {
-    Log() << Verbose(1) << "Remaining points are: ";
+    DoLog(1) && (Log() << Verbose(1) << "Remaining points are: ");
     for (PointMap::iterator PointSprinter = TesselStruct->PointsOnBoundary.begin(); PointSprinter != TesselStruct->PointsOnBoundary.end(); PointSprinter++)
-      Log() << Verbose(0) << *(PointSprinter->second) << "\t";
-    Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << *(PointSprinter->second) << "\t");
+    DoLog(0) && (Log() << Verbose(0) << endl);
 
     PointRunner = TesselStruct->PointsOnBoundary.begin();
@@ -520,5 +513,5 @@
   // check whether there is something to work on
   if (TesselStruct == NULL) {
-    eLog() << Verbose(1) << "TesselStruct is empty!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "TesselStruct is empty!" << endl);
     return volume;
   }
@@ -536,11 +529,11 @@
       PointAdvance++;
       point = PointRunner->second;
-      Log() << Verbose(1) << "INFO: Current point is " << *point << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "INFO: Current point is " << *point << "." << endl);
       for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
         line = LineRunner->second;
-        Log() << Verbose(1) << "INFO: Current line of point " << *point << " is " << *line << "." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "INFO: Current line of point " << *point << " is " << *line << "." << endl);
         if (!line->CheckConvexityCriterion()) {
           // remove the point if needed
-          Log() << Verbose(1) << "... point " << *point << " cannot be on convex envelope." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "... point " << *point << " cannot be on convex envelope." << endl);
           volume += TesselStruct->RemovePointFromTesselatedSurface(point);
           sprintf(dummy, "-first-%d", ++run);
@@ -563,5 +556,5 @@
       LineAdvance++;
       line = LineRunner->second;
-      Log() << Verbose(1) << "INFO: Picking farthest baseline for line is " << *line << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "INFO: Picking farthest baseline for line is " << *line << "." << endl);
       // take highest of both lines
       if (TesselStruct->IsConvexRectangle(line) == NULL) {
@@ -604,5 +597,5 @@
 
   // end
-  Log() << Verbose(0) << "Volume is " << volume << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Volume is " << volume << "." << endl);
   return volume;
 };
@@ -627,14 +620,14 @@
   for (TriangleMap::iterator runner = TesselStruct->TrianglesOnBoundary.begin(); runner != TesselStruct->TrianglesOnBoundary.end(); runner++)
     { // go through every triangle, calculate volume of its pyramid with CoG as peak
-      x.CopyVector(runner->second->endpoints[0]->node->node);
-      x.SubtractVector(runner->second->endpoints[1]->node->node);
-      y.CopyVector(runner->second->endpoints[0]->node->node);
-      y.SubtractVector(runner->second->endpoints[2]->node->node);
-      const double a = sqrt(runner->second->endpoints[0]->node->node->DistanceSquared(runner->second->endpoints[1]->node->node));
-      const double b = sqrt(runner->second->endpoints[0]->node->node->DistanceSquared(runner->second->endpoints[2]->node->node));
-      const double c = sqrt(runner->second->endpoints[2]->node->node->DistanceSquared(runner->second->endpoints[1]->node->node));
+      x = (*runner->second->endpoints[0]->node->node) - (*runner->second->endpoints[1]->node->node);
+      y = (*runner->second->endpoints[0]->node->node) - (*runner->second->endpoints[2]->node->node);
+      const double a = sqrt(runner->second->endpoints[0]->node->node->DistanceSquared(*runner->second->endpoints[1]->node->node));
+      const double b = sqrt(runner->second->endpoints[0]->node->node->DistanceSquared(*runner->second->endpoints[2]->node->node));
+      const double c = sqrt(runner->second->endpoints[2]->node->node->DistanceSquared(*runner->second->endpoints[1]->node->node));
       const double G = sqrt(((a + b + c) * (a + b + c) - 2 * (a * a + b * b + c * c)) / 16.); // area of tesselated triangle
-      x.MakeNormalVector(runner->second->endpoints[0]->node->node, runner->second->endpoints[1]->node->node, runner->second->endpoints[2]->node->node);
-      x.Scale(runner->second->endpoints[1]->node->node->ScalarProduct(&x));
+      x = Plane(*(runner->second->endpoints[0]->node->node),
+                *(runner->second->endpoints[1]->node->node),
+                *(runner->second->endpoints[2]->node->node)).getNormal();
+      x.Scale(runner->second->endpoints[1]->node->node->ScalarProduct(x));
       const double h = x.Norm(); // distance of CoG to triangle
       const double PyramidVolume = (1. / 3.) * G * h; // this formula holds for _all_ pyramids (independent of n-edge base or (not) centered peak)
@@ -733,34 +726,34 @@
       totalmass += Walker->type->mass;
   }
-  Log() << Verbose(0) << "RESULT: The summed mass is " << setprecision(10) << totalmass << " atomicmassunit." << endl;
-  Log() << Verbose(0) << "RESULT: The average density is " << setprecision(10) << totalmass / clustervolume << " atomicmassunit/" << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "RESULT: The summed mass is " << setprecision(10) << totalmass << " atomicmassunit." << endl);
+  DoLog(0) && (Log() << Verbose(0) << "RESULT: The average density is " << setprecision(10) << totalmass / clustervolume << " atomicmassunit/" << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl);
 
   // solve cubic polynomial
-  Log() << Verbose(1) << "Solving equidistant suspension in water problem ..." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Solving equidistant suspension in water problem ..." << endl);
   if (IsAngstroem)
     cellvolume = (TotalNoClusters * totalmass / SOLVENTDENSITY_A - (totalmass / clustervolume)) / (celldensity - 1);
   else
     cellvolume = (TotalNoClusters * totalmass / SOLVENTDENSITY_a0 - (totalmass / clustervolume)) / (celldensity - 1);
-  Log() << Verbose(1) << "Cellvolume needed for a density of " << celldensity << " g/cm^3 is " << cellvolume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Cellvolume needed for a density of " << celldensity << " g/cm^3 is " << cellvolume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl);
 
   double minimumvolume = TotalNoClusters * (GreatestDiameter[0] * GreatestDiameter[1] * GreatestDiameter[2]);
-  Log() << Verbose(1) << "Minimum volume of the convex envelope contained in a rectangular box is " << minimumvolume << " atomicmassunit/" << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Minimum volume of the convex envelope contained in a rectangular box is " << minimumvolume << " atomicmassunit/" << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl);
   if (minimumvolume > cellvolume) {
-    eLog() << Verbose(1) << "the containing box already has a greater volume than the envisaged cell volume!" << endl;
-    Log() << Verbose(0) << "Setting Box dimensions to minimum possible, the greatest diameters." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "the containing box already has a greater volume than the envisaged cell volume!" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "Setting Box dimensions to minimum possible, the greatest diameters." << endl);
     for (int i = 0; i < NDIM; i++)
-      BoxLengths.x[i] = GreatestDiameter[i];
+      BoxLengths[i] = GreatestDiameter[i];
     mol->CenterEdge(&BoxLengths);
   } else {
-    BoxLengths.x[0] = (repetition[0] * GreatestDiameter[0] + repetition[1] * GreatestDiameter[1] + repetition[2] * GreatestDiameter[2]);
-    BoxLengths.x[1] = (repetition[0] * repetition[1] * GreatestDiameter[0] * GreatestDiameter[1] + repetition[0] * repetition[2] * GreatestDiameter[0] * GreatestDiameter[2] + repetition[1] * repetition[2] * GreatestDiameter[1] * GreatestDiameter[2]);
-    BoxLengths.x[2] = minimumvolume - cellvolume;
+    BoxLengths[0] = (repetition[0] * GreatestDiameter[0] + repetition[1] * GreatestDiameter[1] + repetition[2] * GreatestDiameter[2]);
+    BoxLengths[1] = (repetition[0] * repetition[1] * GreatestDiameter[0] * GreatestDiameter[1] + repetition[0] * repetition[2] * GreatestDiameter[0] * GreatestDiameter[2] + repetition[1] * repetition[2] * GreatestDiameter[1] * GreatestDiameter[2]);
+    BoxLengths[2] = minimumvolume - cellvolume;
     double x0 = 0.;
     double x1 = 0.;
     double x2 = 0.;
-    if (gsl_poly_solve_cubic(BoxLengths.x[0], BoxLengths.x[1], BoxLengths.x[2], &x0, &x1, &x2) == 1) // either 1 or 3 on return
-      Log() << Verbose(0) << "RESULT: The resulting spacing is: " << x0 << " ." << endl;
+    if (gsl_poly_solve_cubic(BoxLengths[0], BoxLengths[1], BoxLengths[2], &x0, &x1, &x2) == 1) // either 1 or 3 on return
+      DoLog(0) && (Log() << Verbose(0) << "RESULT: The resulting spacing is: " << x0 << " ." << endl);
     else {
-      Log() << Verbose(0) << "RESULT: The resulting spacings are: " << x0 << " and " << x1 << " and " << x2 << " ." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "RESULT: The resulting spacings are: " << x0 << " and " << x1 << " and " << x2 << " ." << endl);
       x0 = x2; // sorted in ascending order
     }
@@ -768,10 +761,10 @@
     cellvolume = 1.;
     for (int i = 0; i < NDIM; i++) {
-      BoxLengths.x[i] = repetition[i] * (x0 + GreatestDiameter[i]);
-      cellvolume *= BoxLengths.x[i];
+      BoxLengths[i] = repetition[i] * (x0 + GreatestDiameter[i]);
+      cellvolume *= BoxLengths[i];
     }
 
     // set new box dimensions
-    Log() << Verbose(0) << "Translating to box with these boundaries." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Translating to box with these boundaries." << endl);
     mol->SetBoxDimension(&BoxLengths);
     mol->CenterInBox();
@@ -779,5 +772,5 @@
   // update Box of atoms by boundary
   mol->SetBoxDimension(&BoxLengths);
-  Log() << Verbose(0) << "RESULT: The resulting cell dimensions are: " << BoxLengths.x[0] << " and " << BoxLengths.x[1] << " and " << BoxLengths.x[2] << " with total volume of " << cellvolume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "RESULT: The resulting cell dimensions are: " << BoxLengths[0] << " and " << BoxLengths[1] << " and " << BoxLengths[2] << " with total volume of " << cellvolume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl);
 };
 
@@ -789,4 +782,5 @@
  * \param *filler molecule which the box is to be filled with
  * \param configuration contains box dimensions
+ * \param MaxDistance fills in molecules only up to this distance (set to -1 if whole of the domain)
  * \param distance[NDIM] distance between filling molecules in each direction
  * \param boundary length of boundary zone between molecule and filling mollecules
@@ -797,37 +791,43 @@
  * \return *mol pointer to new molecule with filled atoms
  */
-molecule * FillBoxWithMolecule(MoleculeListClass *List, molecule *filler, config &configuration, const double distance[NDIM], const double boundary, const double RandomAtomDisplacement, const double RandomMolDisplacement, const bool DoRandomRotation)
+molecule * FillBoxWithMolecule(MoleculeListClass *List, molecule *filler, config &configuration, const double MaxDistance, const double distance[NDIM], const double boundary, const double RandomAtomDisplacement, const double RandomMolDisplacement, const bool DoRandomRotation)
 {
 	Info FunctionInfo(__func__);
-  molecule *Filling = new molecule(filler->elemente);
+  molecule *Filling = World::getInstance().createMolecule();
   Vector CurrentPosition;
   int N[NDIM];
   int n[NDIM];
-  double *M =  ReturnFullMatrixforSymmetric(filler->cell_size);
+  double *M =  ReturnFullMatrixforSymmetric(World::getInstance().getDomain());
   double Rotations[NDIM*NDIM];
+  double *MInverse = InverseMatrix(M);
   Vector AtomTranslations;
   Vector FillerTranslations;
   Vector FillerDistance;
+  Vector Inserter;
   double FillIt = false;
   atom *Walker = NULL;
   bond *Binder = NULL;
-  int i = 0;
-  LinkedCell *LCList[List->ListOfMolecules.size()];
   double phi[NDIM];
-  class Tesselation *TesselStruct[List->ListOfMolecules.size()];
-
-  i=0;
-  for (MoleculeList::iterator ListRunner = List->ListOfMolecules.begin(); ListRunner != List->ListOfMolecules.end(); ListRunner++) {
-    Log() << Verbose(1) << "Pre-creating linked cell lists for molecule " << *ListRunner << "." << endl;
-    LCList[i] = new LinkedCell((*ListRunner), 10.); // get linked cell list
-    Log() << Verbose(1) << "Pre-creating tesselation for molecule " << *ListRunner << "." << endl;
-    TesselStruct[i] = NULL;
-    FindNonConvexBorder((*ListRunner), TesselStruct[i], (const LinkedCell *&)LCList[i], 5., NULL);
-    i++;
-  }
+  map<molecule *, Tesselation *> TesselStruct;
+  map<molecule *, LinkedCell *> LCList;
+
+  for (MoleculeList::iterator ListRunner = List->ListOfMolecules.begin(); ListRunner != List->ListOfMolecules.end(); ListRunner++)
+    if ((*ListRunner)->AtomCount > 0) {
+      DoLog(1) && (Log() << Verbose(1) << "Pre-creating linked cell lists for molecule " << *ListRunner << "." << endl);
+      LCList[(*ListRunner)] = new LinkedCell((*ListRunner), 10.); // get linked cell list
+      DoLog(1) && (Log() << Verbose(1) << "Pre-creating tesselation for molecule " << *ListRunner << "." << endl);
+      TesselStruct[(*ListRunner)] = NULL;
+      FindNonConvexBorder((*ListRunner), TesselStruct[(*ListRunner)], (const LinkedCell *&)LCList[(*ListRunner)], 5., NULL);
+    }
 
   // Center filler at origin
-  filler->CenterOrigin();
+  filler->CenterEdge(&Inserter);
   filler->Center.Zero();
+  DoLog(2) && (Log() << Verbose(2) << "INFO: Filler molecule has the following bonds:" << endl);
+  Binder = filler->first;
+  while(Binder->next != filler->last) {
+    Binder = Binder->next;
+    DoLog(2) && (Log() << Verbose(2) << "  " << *Binder << endl);
+  }
 
   filler->CountAtoms();
@@ -835,9 +835,9 @@
 
   // calculate filler grid in [0,1]^3
-  FillerDistance.Init(distance[0], distance[1], distance[2]);
+  FillerDistance = Vector(distance[0], distance[1], distance[2]);
   FillerDistance.InverseMatrixMultiplication(M);
   for(int i=0;i<NDIM;i++)
-    N[i] = (int) ceil(1./FillerDistance.x[i]);
-  Log() << Verbose(1) << "INFO: Grid steps are " << N[0] << ", " << N[1] << ", " << N[2] << "." << endl;
+    N[i] = (int) ceil(1./FillerDistance[i]);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Grid steps are " << N[0] << ", " << N[1] << ", " << N[2] << "." << endl);
 
   // initialize seed of random number generator to current time
@@ -849,101 +849,87 @@
       for (n[2] = 0; n[2] < N[2]; n[2]++) {
         // calculate position of current grid vector in untransformed box
-        CurrentPosition.Init((double)n[0]/(double)N[0], (double)n[1]/(double)N[1], (double)n[2]/(double)N[2]);
+        CurrentPosition = Vector((double)n[0]/(double)N[0], (double)n[1]/(double)N[1], (double)n[2]/(double)N[2]);
         CurrentPosition.MatrixMultiplication(M);
-        Log() << Verbose(2) << "INFO: Current Position is " << CurrentPosition << "." << endl;
-        // Check whether point is in- or outside
-        FillIt = true;
-        i=0;
-        for (MoleculeList::iterator ListRunner = List->ListOfMolecules.begin(); ListRunner != List->ListOfMolecules.end(); ListRunner++) {
-          // get linked cell list
-          if (TesselStruct[i] == NULL) {
-            eLog() << Verbose(0) << "TesselStruct of " << (*ListRunner) << " is NULL. Didn't we pre-create it?" << endl;
-            FillIt = false;
+        // create molecule random translation vector ...
+        for (int i=0;i<NDIM;i++)
+          FillerTranslations[i] = RandomMolDisplacement*(rand()/(RAND_MAX/2.) - 1.);
+        DoLog(2) && (Log() << Verbose(2) << "INFO: Current Position is " << CurrentPosition << "+" << FillerTranslations << "." << endl);
+
+        // go through all atoms
+        for (int i=0;i<filler->AtomCount;i++)
+          CopyAtoms[i] = NULL;
+        Walker = filler->start;
+        while (Walker->next != filler->end) {
+          Walker = Walker->next;
+
+          // create atomic random translation vector ...
+          for (int i=0;i<NDIM;i++)
+            AtomTranslations[i] = RandomAtomDisplacement*(rand()/(RAND_MAX/2.) - 1.);
+
+          // ... and rotation matrix
+          if (DoRandomRotation) {
+            for (int i=0;i<NDIM;i++) {
+              phi[i] = rand()/(RAND_MAX/(2.*M_PI));
+            }
+
+            Rotations[0] =   cos(phi[0])            *cos(phi[2]) + (sin(phi[0])*sin(phi[1])*sin(phi[2]));
+            Rotations[3] =   sin(phi[0])            *cos(phi[2]) - (cos(phi[0])*sin(phi[1])*sin(phi[2]));
+            Rotations[6] =               cos(phi[1])*sin(phi[2])                                     ;
+            Rotations[1] = - sin(phi[0])*cos(phi[1])                                                ;
+            Rotations[4] =   cos(phi[0])*cos(phi[1])                                                ;
+            Rotations[7] =               sin(phi[1])                                                ;
+            Rotations[3] = - cos(phi[0])            *sin(phi[2]) + (sin(phi[0])*sin(phi[1])*cos(phi[2]));
+            Rotations[5] = - sin(phi[0])            *sin(phi[2]) - (cos(phi[0])*sin(phi[1])*cos(phi[2]));
+            Rotations[8] =               cos(phi[1])*cos(phi[2])                                     ;
+          }
+
+          // ... and put at new position
+          Inserter = Walker->x;
+          if (DoRandomRotation)
+            Inserter.MatrixMultiplication(Rotations);
+          Inserter += AtomTranslations + FillerTranslations + CurrentPosition;
+
+          // check whether inserter is inside box
+          Inserter.MatrixMultiplication(MInverse);
+          FillIt = true;
+          for (int i=0;i<NDIM;i++)
+            FillIt = FillIt && (Inserter[i] >= -MYEPSILON) && ((Inserter[i]-1.) <= MYEPSILON);
+          Inserter.MatrixMultiplication(M);
+
+          // Check whether point is in- or outside
+          for (MoleculeList::iterator ListRunner = List->ListOfMolecules.begin(); ListRunner != List->ListOfMolecules.end(); ListRunner++) {
+            // get linked cell list
+            if (TesselStruct[(*ListRunner)] != NULL) {
+              const double distance = (TesselStruct[(*ListRunner)]->GetDistanceToSurface(Inserter, LCList[(*ListRunner)]));
+              FillIt = FillIt && (distance > boundary) && ((MaxDistance < 0) || (MaxDistance > distance));
+            }
+          }
+          // insert into Filling
+          if (FillIt) {
+            DoLog(1) && (Log() << Verbose(1) << "INFO: Position at " << Inserter << " is outer point." << endl);
+            // copy atom ...
+            CopyAtoms[Walker->nr] = Walker->clone();
+            CopyAtoms[Walker->nr]->x = Inserter;
+            Filling->AddAtom(CopyAtoms[Walker->nr]);
+            DoLog(4) && (Log() << Verbose(4) << "Filling atom " << *Walker << ", translated to " << AtomTranslations << ", at final position is " << (CopyAtoms[Walker->nr]->x) << "." << endl);
           } else {
-            const double distance = (TesselStruct[i]->GetDistanceSquaredToSurface(CurrentPosition, LCList[i]));
-            FillIt = FillIt && (distance > boundary*boundary);
-            if (FillIt) {
-              Log() << Verbose(1) << "INFO: Position at " << CurrentPosition << " is outer point." << endl;
-            } else {
-              Log() << Verbose(1) << "INFO: Position at " << CurrentPosition << " is inner point or within boundary." << endl;
-              break;
-            }
-            i++;
+            DoLog(1) && (Log() << Verbose(1) << "INFO: Position at " << Inserter << " is inner point, within boundary or outside of MaxDistance." << endl);
+            CopyAtoms[Walker->nr] = NULL;
+            continue;
           }
         }
-
-        if (FillIt) {
-          // fill in Filler
-          Log() << Verbose(2) << "Space at " << CurrentPosition << " is unoccupied by any molecule, filling in." << endl;
-
-          // create molecule random translation vector ...
-          for (int i=0;i<NDIM;i++)
-            FillerTranslations.x[i] = RandomMolDisplacement*(rand()/(RAND_MAX/2.) - 1.);
-          Log() << Verbose(2) << "INFO: Translating this filler by " << FillerTranslations << "." << endl;
-
-          // go through all atoms
-          Walker = filler->start;
-          while (Walker->next != filler->end) {
-            Walker = Walker->next;
-            // copy atom ...
-            CopyAtoms[Walker->nr] = new atom(Walker);
-
-            // create atomic random translation vector ...
-            for (int i=0;i<NDIM;i++)
-              AtomTranslations.x[i] = RandomAtomDisplacement*(rand()/(RAND_MAX/2.) - 1.);
-
-            // ... and rotation matrix
-            if (DoRandomRotation) {
-              for (int i=0;i<NDIM;i++) {
-                phi[i] = rand()/(RAND_MAX/(2.*M_PI));
-              }
-
-              Rotations[0] =   cos(phi[0])            *cos(phi[2]) + (sin(phi[0])*sin(phi[1])*sin(phi[2]));
-              Rotations[3] =   sin(phi[0])            *cos(phi[2]) - (cos(phi[0])*sin(phi[1])*sin(phi[2]));
-              Rotations[6] =               cos(phi[1])*sin(phi[2])                                     ;
-              Rotations[1] = - sin(phi[0])*cos(phi[1])                                                ;
-              Rotations[4] =   cos(phi[0])*cos(phi[1])                                                ;
-              Rotations[7] =               sin(phi[1])                                                ;
-              Rotations[3] = - cos(phi[0])            *sin(phi[2]) + (sin(phi[0])*sin(phi[1])*cos(phi[2]));
-              Rotations[5] = - sin(phi[0])            *sin(phi[2]) - (cos(phi[0])*sin(phi[1])*cos(phi[2]));
-              Rotations[8] =               cos(phi[1])*cos(phi[2])                                     ;
-            }
-
-            // ... and put at new position
-            if (DoRandomRotation)
-              CopyAtoms[Walker->nr]->x.MatrixMultiplication(Rotations);
-            CopyAtoms[Walker->nr]->x.AddVector(&AtomTranslations);
-            CopyAtoms[Walker->nr]->x.AddVector(&FillerTranslations);
-            CopyAtoms[Walker->nr]->x.AddVector(&CurrentPosition);
-
-            // insert into Filling
-
-            // FIXME: gives completely different results if CopyAtoms[..] used instead of Walker, why???
-            Log() << Verbose(4) << "Filling atom " << *Walker << ", translated to " << AtomTranslations << ", at final position is " << (CopyAtoms[Walker->nr]->x) << "." << endl;
-            Filling->AddAtom(CopyAtoms[Walker->nr]);
-          }
-
-          // go through all bonds and add as well
-          Binder = filler->first;
-          while(Binder->next != filler->last) {
-            Binder = Binder->next;
-            Log() << Verbose(3) << "Adding Bond between " << *CopyAtoms[Binder->leftatom->nr] << " and " << *CopyAtoms[Binder->rightatom->nr]<< "." << endl;
+        // go through all bonds and add as well
+        Binder = filler->first;
+        while(Binder->next != filler->last) {
+          Binder = Binder->next;
+          if ((CopyAtoms[Binder->leftatom->nr] != NULL) && (CopyAtoms[Binder->rightatom->nr] != NULL)) {
+            Log()  << Verbose(3) << "Adding Bond between " << *CopyAtoms[Binder->leftatom->nr] << " and " << *CopyAtoms[Binder->rightatom->nr]<< "." << endl;
             Filling->AddBond(CopyAtoms[Binder->leftatom->nr], CopyAtoms[Binder->rightatom->nr], Binder->BondDegree);
           }
-        } else {
-          // leave empty
-          Log() << Verbose(2) << "Space at " << CurrentPosition << " is occupied." << endl;
         }
       }
   Free(&M);
-
-  // output to file
-  TesselStruct[0]->LastTriangle = NULL;
-  StoreTrianglesinFile(Filling, TesselStruct[0], "Tesselated", ".dat");
-
-  for (size_t i=0;i<List->ListOfMolecules.size();i++) {
-  	delete(LCList[i]);
-	delete(TesselStruct[i]);
-  }
+  Free(&MInverse);
+
   return Filling;
 };
@@ -964,16 +950,14 @@
   bool freeLC = false;
   bool status = false;
-  CandidateForTesselation *baseline;
-  LineMap::iterator testline;
+  CandidateForTesselation *baseline = NULL;
   bool OneLoopWithoutSuccessFlag = true;  // marks whether we went once through all baselines without finding any without two triangles
   bool TesselationFailFlag = false;
-  BoundaryTriangleSet *T = NULL;
 
   if (TesselStruct == NULL) {
-    Log() << Verbose(1) << "Allocating Tesselation struct ..." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Allocating Tesselation struct ..." << endl);
     TesselStruct= new Tesselation;
   } else {
     delete(TesselStruct);
-    Log() << Verbose(1) << "Re-Allocating Tesselation struct ..." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Re-Allocating Tesselation struct ..." << endl);
     TesselStruct = new Tesselation;
   }
@@ -986,42 +970,48 @@
 
   // 1. get starting triangle
-  TesselStruct->FindStartingTriangle(RADIUS, LCList);
+  if (!TesselStruct->FindStartingTriangle(RADIUS, LCList)) {
+    DoeLog(0) && (eLog() << Verbose(0) << "No valid starting triangle found." << endl);
+    //performCriticalExit();
+  }
+  if (filename != NULL) {
+    if ((DoSingleStepOutput && ((TesselStruct->TrianglesOnBoundary.size() % SingleStepWidth == 0)))) { // if we have a new triangle and want to output each new triangle configuration
+      TesselStruct->Output(filename, mol);
+    }
+  }
 
   // 2. expand from there
   while ((!TesselStruct->OpenLines.empty()) && (OneLoopWithoutSuccessFlag)) {
-    // 2a. fill all new OpenLines
-    Log() << Verbose(1) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for candidates:" << endl;
+    (cerr << "There are " <<  TesselStruct->TrianglesOnBoundary.size() << " triangles and " << TesselStruct->OpenLines.size() << " open lines to scan for candidates." << endl);
+    // 2a. print OpenLines without candidates
+    DoLog(1) && (Log() << Verbose(1) << "There are the following open lines to scan for a candidates:" << endl);
     for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
-      Log() << Verbose(2) << *(Runner->second) << endl;
-
-    for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
-      baseline = Runner->second;
-      if (baseline->pointlist.empty()) {
-        T = (((baseline->BaseLine->triangles.begin()))->second);
-        Log() << Verbose(1) << "Finding best candidate for open line " << *baseline->BaseLine << " of triangle " << *T << endl;
-        TesselationFailFlag = TesselStruct->FindNextSuitableTriangle(*baseline, *T, RADIUS, LCList); //the line is there, so there is a triangle, but only one.
-      }
-    }
-
-    // 2b. search for smallest ShortestAngle among all candidates
+      if (Runner->second->pointlist.empty())
+        DoLog(1) && (Log() << Verbose(1) << " " << *(Runner->second) << endl);
+
+    // 2b. find best candidate for each OpenLine
+    TesselationFailFlag = TesselStruct->FindCandidatesforOpenLines(RADIUS, LCList);
+
+    // 2c. print OpenLines with candidates again
+    DoLog(1) && (Log() << Verbose(1) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for the best candidates:" << endl);
+    for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
+      DoLog(1) && (Log() << Verbose(1) << " " << *(Runner->second) << endl);
+
+    // 2d. search for smallest ShortestAngle among all candidates
     double ShortestAngle = 4.*M_PI;
-    Log() << Verbose(1) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for the best candidates:" << endl;
-    for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
-      Log() << Verbose(2) << *(Runner->second) << endl;
-
     for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
       if (Runner->second->ShortestAngle < ShortestAngle) {
         baseline = Runner->second;
         ShortestAngle = baseline->ShortestAngle;
-        //Log() << Verbose(1) << "New best candidate is " << *baseline->BaseLine << " with point " << *baseline->point << " and angle " << baseline->ShortestAngle << endl;
+        DoLog(1) && (Log() << Verbose(1) << "New best candidate is " << *baseline->BaseLine << " with point " << *(*baseline->pointlist.begin()) << " and angle " << baseline->ShortestAngle << endl);
       }
     }
+    // 2e. if we found one, add candidate
     if ((ShortestAngle == 4.*M_PI) || (baseline->pointlist.empty()))
       OneLoopWithoutSuccessFlag = false;
     else {
-      TesselStruct->AddCandidateTriangle(*baseline);
-    }
-
-    // write temporary envelope
+      TesselStruct->AddCandidatePolygon(*baseline, RADIUS, LCList);
+    }
+
+    // 2f. write temporary envelope
     if (filename != NULL) {
       if ((DoSingleStepOutput && ((TesselStruct->TrianglesOnBoundary.size() % SingleStepWidth == 0)))) { // if we have a new triangle and want to output each new triangle configuration
@@ -1058,9 +1048,9 @@
   StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, "");
 
-  // correct degenerated polygons
-  TesselStruct->CorrectAllDegeneratedPolygons();
-
-  // check envelope for consistency
-  status = CheckListOfBaselines(TesselStruct);
+//  // correct degenerated polygons
+//  TesselStruct->CorrectAllDegeneratedPolygons();
+//
+//  // check envelope for consistency
+//  status = CheckListOfBaselines(TesselStruct);
 
   // write final envelope
Index: src/boundary.hpp
===================================================================
--- src/boundary.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/boundary.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -49,5 +49,5 @@
 
 double ConvexizeNonconvexEnvelope(class Tesselation *&TesselStruct, const molecule * const mol, const char * const filename);
-molecule * FillBoxWithMolecule(MoleculeListClass *List, molecule *filler, config &configuration, const double distance[NDIM], const double boundary, const double RandomAtomDisplacement, const double RandomMolDisplacement, const bool DoRandomRotation);
+molecule * FillBoxWithMolecule(MoleculeListClass *List, molecule *filler, config &configuration, const double MaxDistance, const double distance[NDIM], const double boundary, const double RandomAtomDisplacement, const double RandomMolDisplacement, const bool DoRandomRotation);
 void FindConvexBorder(const molecule* const mol, Tesselation *&TesselStruct, const LinkedCell *LCList, const char *filename);
 Vector* FindEmbeddingHole(MoleculeListClass *mols, molecule *srcmol);
Index: src/builder.cpp
===================================================================
--- src/builder.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/builder.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -54,4 +54,5 @@
 #include <cstring>
 
+#include "analysis_bonds.hpp"
 #include "analysis_correlation.hpp"
 #include "atom.hpp"
@@ -59,4 +60,5 @@
 #include "bondgraph.hpp"
 #include "boundary.hpp"
+#include "CommandLineParser.hpp"
 #include "config.hpp"
 #include "element.hpp"
@@ -66,5 +68,5 @@
 #include "linkedcell.hpp"
 #include "log.hpp"
-#include "memoryusageobserverunittest.hpp"
+#include "memoryusageobserver.hpp"
 #include "molecule.hpp"
 #include "periodentafel.hpp"
@@ -74,8 +76,11 @@
 #include "Menu/ActionMenuItem.hpp"
 #include "Actions/ActionRegistry.hpp"
+#include "Actions/ActionHistory.hpp"
 #include "Actions/MethodAction.hpp"
-#include "Actions/small_actions.hpp"
+#include "Actions/MoleculeAction/ChangeNameAction.hpp"
 #include "World.hpp"
 #include "version.h"
+#include "World.hpp"
+#include "Helpers/MemDebug.hpp"
 
 /********************************************* Subsubmenu routine ************************************/
@@ -94,24 +99,24 @@
   bool valid;
 
-  Log() << Verbose(0) << "===========ADD ATOM============================" << endl;
-  Log() << Verbose(0) << " a - state absolute coordinates of atom" << endl;
-  Log() << Verbose(0) << " b - state relative coordinates of atom wrt to reference point" << endl;
-  Log() << Verbose(0) << " c - state relative coordinates of atom wrt to already placed atom" << endl;
-  Log() << Verbose(0) << " d - state two atoms, two angles and a distance" << endl;
-  Log() << Verbose(0) << " e - least square distance position to a set of atoms" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
-  Log() << Verbose(0) << "Note: Specifiy angles in degrees not multiples of Pi!" << endl;
-  Log() << Verbose(0) << "INPUT: ";
+  cout << Verbose(0) << "===========ADD ATOM============================" << endl;
+  cout << Verbose(0) << " a - state absolute coordinates of atom" << endl;
+  cout << Verbose(0) << " b - state relative coordinates of atom wrt to reference point" << endl;
+  cout << Verbose(0) << " c - state relative coordinates of atom wrt to already placed atom" << endl;
+  cout << Verbose(0) << " d - state two atoms, two angles and a distance" << endl;
+  cout << Verbose(0) << " e - least square distance position to a set of atoms" << endl;
+  cout << Verbose(0) << "all else - go back" << endl;
+  cout << Verbose(0) << "===============================================" << endl;
+  cout << Verbose(0) << "Note: Specifiy angles in degrees not multiples of Pi!" << endl;
+  cout << Verbose(0) << "INPUT: ";
   cin >> choice;
 
   switch (choice) {
     default:
-      eLog() << Verbose(2) << "Not a valid choice." << endl;
+      DoeLog(2) && (eLog()<< Verbose(2) << "Not a valid choice." << endl);
       break;
       case 'a': // absolute coordinates of atom
-        Log() << Verbose(0) << "Enter absolute coordinates." << endl;
+        cout << Verbose(0) << "Enter absolute coordinates." << endl;
         first = new atom;
-        first->x.AskPosition(mol->cell_size, false);
+        first->x.AskPosition(World::getInstance().getDomain(), false);
         first->type = periode->AskElement();  // give type
         mol->AddAtom(first);  // add to molecule
@@ -122,11 +127,11 @@
         valid = true;
         do {
-          if (!valid) eLog() << Verbose(2) << "Resulting position out of cell." << endl;
-          Log() << Verbose(0) << "Enter reference coordinates." << endl;
-          x.AskPosition(mol->cell_size, true);
-          Log() << Verbose(0) << "Enter relative coordinates." << endl;
-          first->x.AskPosition(mol->cell_size, false);
+          if (!valid) DoeLog(2) && (eLog()<< Verbose(2) << "Resulting position out of cell." << endl);
+          cout << Verbose(0) << "Enter reference coordinates." << endl;
+          x.AskPosition(World::getInstance().getDomain(), true);
+          cout << Verbose(0) << "Enter relative coordinates." << endl;
+          first->x.AskPosition(World::getInstance().getDomain(), false);
           first->x.AddVector((const Vector *)&x);
-          Log() << Verbose(0) << "\n";
+          cout << Verbose(0) << "\n";
         } while (!(valid = mol->CheckBounds((const Vector *)&first->x)));
         first->type = periode->AskElement();  // give type
@@ -138,8 +143,8 @@
         valid = true;
         do {
-          if (!valid) eLog() << Verbose(2) << "Resulting position out of cell." << endl;
+          if (!valid) DoeLog(2) && (eLog()<< Verbose(2) << "Resulting position out of cell." << endl);
           second = mol->AskAtom("Enter atom number: ");
-          Log() << Verbose(0) << "Enter relative coordinates." << endl;
-          first->x.AskPosition(mol->cell_size, false);
+          DoLog(0) && (Log() << Verbose(0) << "Enter relative coordinates." << endl);
+          first->x.AskPosition(World::getInstance().getDomain(), false);
           for (int i=NDIM;i--;) {
             first->x.x[i] += second->x.x[i];
@@ -155,7 +160,7 @@
         do {
           if (!valid) {
-            eLog() << Verbose(2) << "Resulting coordinates out of cell - " << first->x << endl;
+            DoeLog(2) && (eLog()<< Verbose(2) << "Resulting coordinates out of cell - " << first->x << endl);
           }
-          Log() << Verbose(0) << "First, we need two atoms, the first atom is the central, while the second is the outer one." << endl;
+          cout << Verbose(0) << "First, we need two atoms, the first atom is the central, while the second is the outer one." << endl;
           second = mol->AskAtom("Enter central atom: ");
           third = mol->AskAtom("Enter second atom (specifying the axis for first angle): ");
@@ -168,5 +173,5 @@
           c *= M_PI/180.;
           bound(&c, -M_PI, M_PI);
-          Log() << Verbose(0) << "radius: " << a << "\t phi: " << b*180./M_PI << "\t theta: " << c*180./M_PI << endl;
+          cout << Verbose(0) << "radius: " << a << "\t phi: " << b*180./M_PI << "\t theta: " << c*180./M_PI << endl;
 /*
           second->Output(1,1,(ofstream *)&cout);
@@ -180,10 +185,10 @@
 
           if (!z.SolveSystem(&x,&y,&n, b, c, a)) {
-            Log() << Verbose(0) << "Failure solving self-dependent linear system!" << endl;
+         coutg() << Verbose(0) << "Failure solving self-dependent linear system!" << endl;
             continue;
           }
-          Log() << Verbose(0) << "resulting relative coordinates: ";
+          DoLog(0) && (Log() << Verbose(0) << "resulting relative coordinates: ");
           z.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
           */
           // calc axis vector
@@ -193,13 +198,13 @@
           Log() << Verbose(0) << "x: ",
           x.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
           z.MakeNormalVector(&second->x,&third->x,&fourth->x);
           Log() << Verbose(0) << "z: ",
           z.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
           y.MakeNormalVector(&x,&z);
           Log() << Verbose(0) << "y: ",
           y.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
 
           // rotate vector around first angle
@@ -208,5 +213,5 @@
           Log() << Verbose(0) << "Rotated vector: ",
           first->x.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
           // remove the projection onto the rotation plane of the second angle
           n.CopyVector(&y);
@@ -214,18 +219,18 @@
           Log() << Verbose(0) << "N1: ",
           n.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
           first->x.SubtractVector(&n);
           Log() << Verbose(0) << "Subtracted vector: ",
           first->x.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
           n.CopyVector(&z);
           n.Scale(first->x.ScalarProduct(&z));
           Log() << Verbose(0) << "N2: ",
           n.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
           first->x.SubtractVector(&n);
           Log() << Verbose(0) << "2nd subtracted vector: ",
           first->x.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
 
           // rotate another vector around second angle
@@ -234,5 +239,5 @@
           Log() << Verbose(0) << "2nd Rotated vector: ",
           n.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
 
           // add the two linear independent vectors
@@ -242,7 +247,7 @@
           first->x.AddVector(&second->x);
 
-          Log() << Verbose(0) << "resulting coordinates: ";
+          DoLog(0) && (Log() << Verbose(0) << "resulting coordinates: ");
           first->x.Output();
-          Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << endl);
         } while (!(valid = mol->CheckBounds((const Vector *)&first->x)));
         first->type = periode->AskElement();  // give type
@@ -257,7 +262,7 @@
           atoms[i] = NULL;
         int i=0, j=0;
-        Log() << Verbose(0) << "Now we need at least three molecules.\n";
+        cout << Verbose(0) << "Now we need at least three molecules.\n";
         do {
-          Log() << Verbose(0) << "Enter " << i+1 << "th atom: ";
+          cout << Verbose(0) << "Enter " << i+1 << "th atom: ";
           cin >> j;
           if (j != -1) {
@@ -273,5 +278,5 @@
         } else {
           delete first;
-          Log() << Verbose(0) << "Please enter at least two vectors!\n";
+          cout << Verbose(0) << "Please enter at least two vectors!\n";
         }
         break;
@@ -287,30 +292,30 @@
   char choice;  // menu choice char
 
-  Log() << Verbose(0) << "===========CENTER ATOMS=========================" << endl;
-  Log() << Verbose(0) << " a - on origin" << endl;
-  Log() << Verbose(0) << " b - on center of gravity" << endl;
-  Log() << Verbose(0) << " c - within box with additional boundary" << endl;
-  Log() << Verbose(0) << " d - within given simulation box" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
-  Log() << Verbose(0) << "INPUT: ";
+  cout << Verbose(0) << "===========CENTER ATOMS=========================" << endl;
+  cout << Verbose(0) << " a - on origin" << endl;
+  cout << Verbose(0) << " b - on center of gravity" << endl;
+  cout << Verbose(0) << " c - within box with additional boundary" << endl;
+  cout << Verbose(0) << " d - within given simulation box" << endl;
+  cout << Verbose(0) << "all else - go back" << endl;
+  cout << Verbose(0) << "===============================================" << endl;
+  cout << Verbose(0) << "INPUT: ";
   cin >> choice;
 
   switch (choice) {
     default:
-      Log() << Verbose(0) << "Not a valid choice." << endl;
+      cout << Verbose(0) << "Not a valid choice." << endl;
       break;
     case 'a':
-      Log() << Verbose(0) << "Centering atoms in config file on origin." << endl;
+      cout << Verbose(0) << "Centering atoms in config file on origin." << endl;
       mol->CenterOrigin();
       break;
     case 'b':
-      Log() << Verbose(0) << "Centering atoms in config file on center of gravity." << endl;
+      cout << Verbose(0) << "Centering atoms in config file on center of gravity." << endl;
       mol->CenterPeriodic();
       break;
     case 'c':
-      Log() << Verbose(0) << "Centering atoms in config file within given additional boundary." << endl;
+      cout << Verbose(0) << "Centering atoms in config file within given additional boundary." << endl;
       for (int i=0;i<NDIM;i++) {
-        Log() << Verbose(0) << "Enter axis " << i << " boundary: ";
+        cout << Verbose(0) << "Enter axis " << i << " boundary: ";
         cin >> y.x[i];
       }
@@ -323,7 +328,7 @@
       break;
     case 'd':
-      Log() << Verbose(1) << "Centering atoms in config file within given simulation box." << endl;
+      cout << Verbose(1) << "Centering atoms in config file within given simulation box." << endl;
       for (int i=0;i<NDIM;i++) {
-        Log() << Verbose(0) << "Enter axis " << i << " boundary: ";
+        cout << Verbose(0) << "Enter axis " << i << " boundary: ";
         cin >> x.x[i];
       }
@@ -346,12 +351,12 @@
   char choice;  // menu choice char
 
-  Log() << Verbose(0) << "===========ALIGN ATOMS=========================" << endl;
-  Log() << Verbose(0) << " a - state three atoms defining align plane" << endl;
-  Log() << Verbose(0) << " b - state alignment vector" << endl;
-  Log() << Verbose(0) << " c - state two atoms in alignment direction" << endl;
-  Log() << Verbose(0) << " d - align automatically by least square fit" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
-  Log() << Verbose(0) << "INPUT: ";
+  cout << Verbose(0) << "===========ALIGN ATOMS=========================" << endl;
+  cout << Verbose(0) << " a - state three atoms defining align plane" << endl;
+  cout << Verbose(0) << " b - state alignment vector" << endl;
+  cout << Verbose(0) << " c - state two atoms in alignment direction" << endl;
+  cout << Verbose(0) << " d - align automatically by least square fit" << endl;
+  cout << Verbose(0) << "all else - go back" << endl;
+  cout << Verbose(0) << "===============================================" << endl;
+  cout << Verbose(0) << "INPUT: ";
   cin >> choice;
 
@@ -366,6 +371,6 @@
       break;
     case 'b': // normal vector of mirror plane
-      Log() << Verbose(0) << "Enter normal vector of mirror plane." << endl;
-      n.AskPosition(mol->cell_size,0);
+      cout << Verbose(0) << "Enter normal vector of mirror plane." << endl;
+      n.AskPosition(World::getInstance().getDomain(),0);
       n.Normalize();
       break;
@@ -386,5 +391,5 @@
         fscanf(stdin, "%3s", shorthand);
       } while ((param.type = periode->FindElement(shorthand)) == NULL);
-      Log() << Verbose(0) << "Element is " << param.type->name << endl;
+      cout << Verbose(0) << "Element is " << param.type->name << endl;
       mol->GetAlignvector(&param);
       for (int i=NDIM;i--;) {
@@ -393,13 +398,13 @@
       }
       gsl_vector_free(param.x);
-      Log() << Verbose(0) << "Offset vector: ";
+      cout << Verbose(0) << "Offset vector: ";
       x.Output();
-      Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << endl);
       n.Normalize();
       break;
   };
-  Log() << Verbose(0) << "Alignment vector: ";
+  DoLog(0) && (Log() << Verbose(0) << "Alignment vector: ");
   n.Output();
-  Log() << Verbose(0) << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
   mol->Align(&n);
 };
@@ -414,11 +419,11 @@
   char choice;  // menu choice char
 
-  Log() << Verbose(0) << "===========MIRROR ATOMS=========================" << endl;
-  Log() << Verbose(0) << " a - state three atoms defining mirror plane" << endl;
-  Log() << Verbose(0) << " b - state normal vector of mirror plane" << endl;
-  Log() << Verbose(0) << " c - state two atoms in normal direction" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
-  Log() << Verbose(0) << "INPUT: ";
+  DoLog(0) && (Log() << Verbose(0) << "===========MIRROR ATOMS=========================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " a - state three atoms defining mirror plane" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " b - state normal vector of mirror plane" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " c - state two atoms in normal direction" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "all else - go back" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "===============================================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
   cin >> choice;
 
@@ -433,6 +438,6 @@
       break;
     case 'b': // normal vector of mirror plane
-      Log() << Verbose(0) << "Enter normal vector of mirror plane." << endl;
-      n.AskPosition(mol->cell_size,0);
+      DoLog(0) && (Log() << Verbose(0) << "Enter normal vector of mirror plane." << endl);
+      n.AskPosition(World::getInstance().getDomain(),0);
       n.Normalize();
       break;
@@ -446,7 +451,7 @@
       break;
   };
-  Log() << Verbose(0) << "Normal vector: ";
+  DoLog(0) && (Log() << Verbose(0) << "Normal vector: ");
   n.Output();
-  Log() << Verbose(0) << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
   mol->Mirror((const Vector *)&n);
 };
@@ -462,11 +467,11 @@
   char choice;  // menu choice char
 
-  Log() << Verbose(0) << "===========REMOVE ATOMS=========================" << endl;
-  Log() << Verbose(0) << " a - state atom for removal by number" << endl;
-  Log() << Verbose(0) << " b - keep only in radius around atom" << endl;
-  Log() << Verbose(0) << " c - remove this with one axis greater value" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
-  Log() << Verbose(0) << "INPUT: ";
+  DoLog(0) && (Log() << Verbose(0) << "===========REMOVE ATOMS=========================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " a - state atom for removal by number" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " b - keep only in radius around atom" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " c - remove this with one axis greater value" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "all else - go back" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "===============================================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
   cin >> choice;
 
@@ -475,11 +480,11 @@
     case 'a':
       if (mol->RemoveAtom(mol->AskAtom("Enter number of atom within molecule: ")))
-        Log() << Verbose(1) << "Atom removed." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Atom removed." << endl);
       else
-        Log() << Verbose(1) << "Atom not found." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Atom not found." << endl);
       break;
     case 'b':
       second = mol->AskAtom("Enter number of atom as reference point: ");
-      Log() << Verbose(0) << "Enter radius: ";
+      DoLog(0) && (Log() << Verbose(0) << "Enter radius: ");
       cin >> tmp1;
       first = mol->start;
@@ -493,9 +498,9 @@
       break;
     case 'c':
-      Log() << Verbose(0) << "Which axis is it: ";
+      DoLog(0) && (Log() << Verbose(0) << "Which axis is it: ");
       cin >> axis;
-      Log() << Verbose(0) << "Lower boundary: ";
+      DoLog(0) && (Log() << Verbose(0) << "Lower boundary: ");
       cin >> tmp1;
-      Log() << Verbose(0) << "Upper boundary: ";
+      DoLog(0) && (Log() << Verbose(0) << "Upper boundary: ");
       cin >> tmp2;
       first = mol->start;
@@ -527,20 +532,20 @@
   char choice;  // menu choice char
 
-  Log() << Verbose(0) << "===========MEASURE ATOMS=========================" << endl;
-  Log() << Verbose(0) << " a - calculate bond length between one atom and all others" << endl;
-  Log() << Verbose(0) << " b - calculate bond length between two atoms" << endl;
-  Log() << Verbose(0) << " c - calculate bond angle" << endl;
-  Log() << Verbose(0) << " d - calculate principal axis of the system" << endl;
-  Log() << Verbose(0) << " e - calculate volume of the convex envelope" << endl;
-  Log() << Verbose(0) << " f - calculate temperature from current velocity" << endl;
-  Log() << Verbose(0) << " g - output all temperatures per step from velocities" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
-  Log() << Verbose(0) << "INPUT: ";
+  DoLog(0) && (Log() << Verbose(0) << "===========MEASURE ATOMS=========================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " a - calculate bond length between one atom and all others" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " b - calculate bond length between two atoms" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " c - calculate bond angle" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " d - calculate principal axis of the system" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " e - calculate volume of the convex envelope" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " f - calculate temperature from current velocity" << endl);
+  DoLog(0) && (Log() << Verbose(0) << " g - output all temperatures per step from velocities" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "all else - go back" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "===============================================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
   cin >> choice;
 
   switch(choice) {
     default:
-      Log() << Verbose(1) << "Not a valid choice." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Not a valid choice." << endl);
       break;
     case 'a':
@@ -574,11 +579,11 @@
       x.SubtractVector((const Vector *)&second->x);
       tmp1 = x.Norm();
-      Log() << Verbose(1) << "Distance vector is ";
+      DoLog(1) && (Log() << Verbose(1) << "Distance vector is ");
       x.Output();
-      Log() << Verbose(0) << "." << endl << "Norm of distance is " << tmp1 << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "." << endl << "Norm of distance is " << tmp1 << "." << endl);
       break;
 
     case 'c':
-      Log() << Verbose(0) << "Evaluating bond angle between three - first, central, last - atoms." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Evaluating bond angle between three - first, central, last - atoms." << endl);
       first = mol->AskAtom("Enter first atom: ");
       second = mol->AskAtom("Enter central atom: ");
@@ -589,10 +594,10 @@
       y.CopyVector((const Vector *)&third->x);
       y.SubtractVector((const Vector *)&second->x);
-      Log() << Verbose(0) << "Bond angle between first atom Nr." << first->nr << ", central atom Nr." << second->nr << " and last atom Nr." << third->nr << ": ";
-      Log() << Verbose(0) << (acos(x.ScalarProduct((const Vector *)&y)/(y.Norm()*x.Norm()))/M_PI*180.) << " degrees" << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Bond angle between first atom Nr." << first->nr << ", central atom Nr." << second->nr << " and last atom Nr." << third->nr << ": ");
+      DoLog(0) && (Log() << Verbose(0) << (acos(x.ScalarProduct((const Vector *)&y)/(y.Norm()*x.Norm()))/M_PI*180.) << " degrees" << endl);
       break;
     case 'd':
-      Log() << Verbose(0) << "Evaluating prinicipal axis." << endl;
-      Log() << Verbose(0) << "Shall we rotate? [0/1]: ";
+      DoLog(0) && (Log() << Verbose(0) << "Evaluating prinicipal axis." << endl);
+      DoLog(0) && (Log() << Verbose(0) << "Shall we rotate? [0/1]: ");
       cin >> Z;
       if ((Z >=0) && (Z <=1))
@@ -603,5 +608,5 @@
     case 'e':
       {
-        Log() << Verbose(0) << "Evaluating volume of the convex envelope.";
+        DoLog(0) && (Log() << Verbose(0) << "Evaluating volume of the convex envelope.");
         class Tesselation *TesselStruct = NULL;
         const LinkedCell *LCList = NULL;
@@ -609,5 +614,5 @@
         FindConvexBorder(mol, TesselStruct, LCList, NULL);
         double clustervolume = VolumeOfConvexEnvelope(TesselStruct, configuration);
-        Log() << Verbose(0) << "The tesselated surface area is " << clustervolume << "." << endl;\
+        DoLog(0) && (Log() << Verbose(0) << "The tesselated surface area is " << clustervolume << "." << endl);\
         delete(LCList);
         delete(TesselStruct);
@@ -620,12 +625,12 @@
       {
         char filename[255];
-        Log() << Verbose(0) << "Please enter filename: " << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Please enter filename: " << endl);
         cin >> filename;
-        Log() << Verbose(1) << "Storing temperatures in " << filename << "." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Storing temperatures in " << filename << "." << endl);
         ofstream *output = new ofstream(filename, ios::trunc);
         if (!mol->OutputTemperatureFromTrajectories(output, 0, mol->MDSteps))
-          Log() << Verbose(2) << "File could not be written." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "File could not be written." << endl);
         else
-          Log() << Verbose(2) << "File stored." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "File stored." << endl);
         output->close();
         delete(output);
@@ -644,6 +649,6 @@
   clock_t start, end;
 
-  Log() << Verbose(0) << "Fragmenting molecule with current connection matrix ..." << endl;
-  Log() << Verbose(0) << "What's the desired bond order: ";
+  DoLog(0) && (Log() << Verbose(0) << "Fragmenting molecule with current connection matrix ..." << endl);
+  DoLog(0) && (Log() << Verbose(0) << "What's the desired bond order: ");
   cin >> Order1;
   if (mol->first->next != mol->last) {  // there are bonds
@@ -651,7 +656,7 @@
     mol->FragmentMolecule(Order1, configuration);
     end = clock();
-    Log() << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl);
   } else
-    Log() << Verbose(0) << "Connection matrix has not yet been generated!" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Connection matrix has not yet been generated!" << endl);
 };
 
@@ -664,5 +669,5 @@
 static void ManipulateAtoms(periodentafel *periode, MoleculeListClass *molecules, config *configuration)
 {
-  atom *first, *second;
+  atom *first, *second, *third;
   molecule *mol = NULL;
   Vector x,y,z,n; // coordinates for absolute point in cell volume
@@ -672,20 +677,21 @@
   bool valid;
 
-  Log() << Verbose(0) << "=========MANIPULATE ATOMS======================" << endl;
-  Log() << Verbose(0) << "a - add an atom" << endl;
-  Log() << Verbose(0) << "r - remove an atom" << endl;
-  Log() << Verbose(0) << "b - scale a bond between atoms" << endl;
-  Log() << Verbose(0) << "u - change an atoms element" << endl;
-  Log() << Verbose(0) << "l - measure lengths, angles, ... for an atom" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "=========MANIPULATE ATOMS======================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "a - add an atom" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "r - remove an atom" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "b - scale a bond between atoms" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "t - turn an atom round another bond" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "u - change an atoms element" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "l - measure lengths, angles, ... for an atom" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "all else - go back" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "===============================================" << endl);
   if (molecules->NumberOfActiveMolecules() > 1)
-    eLog() << Verbose(2) << "There is more than one molecule active! Atoms will be added to each." << endl;
-  Log() << Verbose(0) << "INPUT: ";
+    DoeLog(2) && (eLog()<< Verbose(2) << "There is more than one molecule active! Atoms will be added to each." << endl);
+  DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
   cin >> choice;
 
   switch (choice) {
     default:
-      Log() << Verbose(0) << "Not a valid choice." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Not a valid choice." << endl);
       break;
 
@@ -694,5 +700,5 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
         AddAtoms(periode, mol);
       }
@@ -703,6 +709,6 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
-        Log() << Verbose(0) << "Scaling bond length between two atoms." << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
+        DoLog(0) && (Log() << Verbose(0) << "Scaling bond length between two atoms." << endl);
         first = mol->AskAtom("Enter first (fixed) atom: ");
         second = mol->AskAtom("Enter second (shifting) atom: ");
@@ -711,6 +717,6 @@
           minBond += (first->x.x[i]-second->x.x[i])*(first->x.x[i] - second->x.x[i]);
         minBond = sqrt(minBond);
-        Log() << Verbose(0) << "Current Bond length between " << first->type->name << " Atom " << first->nr << " and " << second->type->name << " Atom " << second->nr << ": " << minBond << " a.u." << endl;
-        Log() << Verbose(0) << "Enter new bond length [a.u.]: ";
+        DoLog(0) && (Log() << Verbose(0) << "Current Bond length between " << first->type->name << " Atom " << first->nr << " and " << second->type->name << " Atom " << second->nr << ": " << minBond << " a.u." << endl);
+        DoLog(0) && (Log() << Verbose(0) << "Enter new bond length [a.u.]: ");
         cin >> bond;
         for (int i=NDIM;i--;) {
@@ -726,7 +732,7 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
-       Log() << Verbose(0) << "Angstroem -> Bohrradius: 1.8897261\t\tBohrradius -> Angstroem: 0.52917721" << endl;
-       Log() << Verbose(0) << "Enter three factors: ";
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
+       DoLog(0) && (Log() << Verbose(0) << "Angstroem -> Bohrradius: 1.8897261\t\tBohrradius -> Angstroem: 0.52917721" << endl);
+       DoLog(0) && (Log() << Verbose(0) << "Enter three factors: ");
        factor = new double[NDIM];
        cin >> factor[0];
@@ -743,5 +749,5 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
         MeasureAtoms(periode, mol, configuration);
       }
@@ -752,7 +758,40 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
         RemoveAtoms(mol);
       }
+      break;
+
+    case 't': // turn/rotate atom
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
+          mol = *ListRunner;
+          DoLog(0) && (Log() << Verbose(0) << "Turning atom around another bond - first is atom to turn, second (central) and third specify bond" << endl);
+          first = mol->AskAtom("Enter turning atom: ");
+          second = mol->AskAtom("Enter central atom: ");
+          third  = mol->AskAtom("Enter bond atom: ");
+          cout << Verbose(0) << "Enter new angle in degrees: ";
+          double tmp = 0.;
+          cin >> tmp;
+          // calculate old angle
+          x.CopyVector((const Vector *)&first->x);
+          x.SubtractVector((const Vector *)&second->x);
+          y.CopyVector((const Vector *)&third->x);
+          y.SubtractVector((const Vector *)&second->x);
+          double alpha = (acos(x.ScalarProduct((const Vector *)&y)/(y.Norm()*x.Norm()))/M_PI*180.);
+          cout << Verbose(0) << "Bond angle between first atom Nr." << first->nr << ", central atom Nr." << second->nr << " and last atom Nr." << third->nr << ": ";
+          cout << Verbose(0) << alpha << " degrees" << endl;
+          // rotate
+          z.MakeNormalVector(&x,&y);
+          x.RotateVector(&z,(alpha-tmp)*M_PI/180.);
+          x.AddVector(&second->x);
+          first->x.CopyVector(&x);
+          // check new angle
+          x.CopyVector((const Vector *)&first->x);
+          x.SubtractVector((const Vector *)&second->x);
+          alpha = (acos(x.ScalarProduct((const Vector *)&y)/(y.Norm()*x.Norm()))/M_PI*180.);
+          cout << Verbose(0) << "new Bond angle between first atom Nr." << first->nr << ", central atom Nr." << second->nr << " and last atom Nr." << third->nr << ": ";
+          cout << Verbose(0) << alpha << " degrees" << endl;
+        }
       break;
 
@@ -762,14 +801,14 @@
         int Z;
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
         first = NULL;
         do {
-          Log() << Verbose(0) << "Change the element of which atom: ";
+          DoLog(0) && (Log() << Verbose(0) << "Change the element of which atom: ");
           cin >> Z;
         } while ((first = mol->FindAtom(Z)) == NULL);
-        Log() << Verbose(0) << "New element by atomic number Z: ";
+        DoLog(0) && (Log() << Verbose(0) << "New element by atomic number Z: ");
         cin >> Z;
         first->type = periode->FindElement(Z);
-        Log() << Verbose(0) << "Atom " << first->nr << "'s element is " << first->type->name << "." << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Atom " << first->nr << "'s element is " << first->type->name << "." << endl);
       }
       break;
@@ -792,23 +831,23 @@
   MoleculeLeafClass *Subgraphs = NULL;
 
-  Log() << Verbose(0) << "=========MANIPULATE GLOBALLY===================" << endl;
-  Log() << Verbose(0) << "c - scale by unit transformation" << endl;
-  Log() << Verbose(0) << "d - duplicate molecule/periodic cell" << endl;
-  Log() << Verbose(0) << "f - fragment molecule many-body bond order style" << endl;
-  Log() << Verbose(0) << "g - center atoms in box" << endl;
-  Log() << Verbose(0) << "i - realign molecule" << endl;
-  Log() << Verbose(0) << "m - mirror all molecules" << endl;
-  Log() << Verbose(0) << "o - create connection matrix" << endl;
-  Log() << Verbose(0) << "t - translate molecule by vector" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "=========MANIPULATE GLOBALLY===================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "c - scale by unit transformation" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "d - duplicate molecule/periodic cell" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "f - fragment molecule many-body bond order style" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "g - center atoms in box" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "i - realign molecule" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "m - mirror all molecules" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "o - create connection matrix" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "t - translate molecule by vector" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "all else - go back" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "===============================================" << endl);
   if (molecules->NumberOfActiveMolecules() > 1)
-    eLog() << Verbose(2) << "There is more than one molecule active! Atoms will be added to each." << endl;
-  Log() << Verbose(0) << "INPUT: ";
+    DoeLog(2) && (eLog()<< Verbose(2) << "There is more than one molecule active! Atoms will be added to each." << endl);
+  DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
   cin >> choice;
 
   switch (choice) {
     default:
-      Log() << Verbose(0) << "Not a valid choice." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Not a valid choice." << endl);
       break;
 
@@ -817,8 +856,8 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
-        Log() << Verbose(0) << "State the axis [(+-)123]: ";
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
+        DoLog(0) && (Log() << Verbose(0) << "State the axis [(+-)123]: ");
         cin >> axis;
-        Log() << Verbose(0) << "State the factor: ";
+        DoLog(0) && (Log() << Verbose(0) << "State the factor: ");
         cin >> faktor;
 
@@ -837,8 +876,8 @@
           }
           if (count != j)
-            eLog() << Verbose(1) << "AtomCount " << count << " is not equal to number of atoms in molecule " << j << "!" << endl;
+            DoeLog(1) && (eLog()<< Verbose(1) << "AtomCount " << count << " is not equal to number of atoms in molecule " << j << "!" << endl);
           x.Zero();
           y.Zero();
-          y.x[abs(axis)-1] = mol->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] * abs(axis)/axis; // last term is for sign, first is for magnitude
+          y.x[abs(axis)-1] = World::getInstance().getDomain()[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] * abs(axis)/axis; // last term is for sign, first is for magnitude
           for (int i=1;i<faktor;i++) {  // then add this list with respective translation factor times
             x.AddVector(&y); // per factor one cell width further
@@ -863,5 +902,5 @@
             mol->Translate(&x);
           }
-          mol->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor;
+          World::getInstance().getDomain()[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor;
         }
       }
@@ -876,5 +915,5 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
         CenterAtoms(mol);
       }
@@ -885,5 +924,5 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
         AlignAtoms(periode, mol);
       }
@@ -894,5 +933,5 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
         MirrorAtoms(mol);
       }
@@ -905,10 +944,10 @@
           double bonddistance;
           clock_t start,end;
-          Log() << Verbose(0) << "What's the maximum bond distance: ";
+          DoLog(0) && (Log() << Verbose(0) << "What's the maximum bond distance: ");
           cin >> bonddistance;
           start = clock();
           mol->CreateAdjacencyList(bonddistance, configuration->GetIsAngstroem(), &BondGraph::CovalentMinMaxDistance, NULL);
           end = clock();
-          Log() << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl);
         }
       break;
@@ -918,7 +957,7 @@
         if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
-        Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
-        Log() << Verbose(0) << "Enter translation vector." << endl;
-        x.AskPosition(mol->cell_size,0);
+        DoLog(0) && (Log() << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl);
+        DoLog(0) && (Log() << Verbose(0) << "Enter translation vector." << endl);
+        x.AskPosition(World::getInstance().getDomain(),0);
         mol->Center.AddVector((const Vector *)&x);
      }
@@ -947,22 +986,22 @@
   molecule *mol = NULL;
 
-  Log() << Verbose(0) << "==========EDIT MOLECULES=====================" << endl;
-  Log() << Verbose(0) << "c - create new molecule" << endl;
-  Log() << Verbose(0) << "l - load molecule from xyz file" << endl;
-  Log() << Verbose(0) << "n - change molecule's name" << endl;
-  Log() << Verbose(0) << "N - give molecules filename" << endl;
-  Log() << Verbose(0) << "p - parse atoms in xyz file into molecule" << endl;
-  Log() << Verbose(0) << "r - remove a molecule" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
-  Log() << Verbose(0) << "INPUT: ";
+  DoLog(0) && (Log() << Verbose(0) << "==========EDIT MOLECULES=====================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "c - create new molecule" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "l - load molecule from xyz file" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "n - change molecule's name" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "N - give molecules filename" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "p - parse atoms in xyz file into molecule" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "r - remove a molecule" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "all else - go back" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "===============================================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
   cin >> choice;
 
   switch (choice) {
     default:
-      Log() << Verbose(0) << "Not a valid choice." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Not a valid choice." << endl);
       break;
     case 'c':
-      mol = new molecule(periode);
+      mol = World::getInstance().createMolecule();
       molecules->insert(mol);
       break;
@@ -971,8 +1010,8 @@
       {
         char filename[MAXSTRINGSIZE];
-        Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
-        mol = new molecule(periode);
+        DoLog(0) && (Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl);
+        mol = World::getInstance().createMolecule();
         do {
-          Log() << Verbose(0) << "Enter file name: ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter file name: ");
           cin >> filename;
         } while (!mol->AddXYZFile(filename));
@@ -980,10 +1019,11 @@
         // center at set box dimensions
         mol->CenterEdge(&center);
-        mol->cell_size[0] = center.x[0];
-        mol->cell_size[1] = 0;
-        mol->cell_size[2] = center.x[1];
-        mol->cell_size[3] = 0;
-        mol->cell_size[4] = 0;
-        mol->cell_size[5] = center.x[2];
+        double * const cell_size = World::getInstance().getDomain();
+        cell_size[0] = center.x[0];
+        cell_size[1] = 0;
+        cell_size[2] = center.x[1];
+        cell_size[3] = 0;
+        cell_size[4] = 0;
+        cell_size[5] = center.x[2];
         molecules->insert(mol);
       }
@@ -994,9 +1034,9 @@
         char filename[MAXSTRINGSIZE];
         do {
-          Log() << Verbose(0) << "Enter index of molecule: ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter index of molecule: ");
           cin >> nr;
           mol = molecules->ReturnIndex(nr);
         } while (mol == NULL);
-        Log() << Verbose(0) << "Enter name: ";
+        DoLog(0) && (Log() << Verbose(0) << "Enter name: ");
         cin >> filename;
         strcpy(mol->name, filename);
@@ -1008,9 +1048,9 @@
         char filename[MAXSTRINGSIZE];
         do {
-          Log() << Verbose(0) << "Enter index of molecule: ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter index of molecule: ");
           cin >> nr;
           mol = molecules->ReturnIndex(nr);
         } while (mol == NULL);
-        Log() << Verbose(0) << "Enter name: ";
+        DoLog(0) && (Log() << Verbose(0) << "Enter name: ");
         cin >> filename;
         mol->SetNameFromFilename(filename);
@@ -1023,11 +1063,11 @@
         mol = NULL;
         do {
-          Log() << Verbose(0) << "Enter index of molecule: ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter index of molecule: ");
           cin >> nr;
           mol = molecules->ReturnIndex(nr);
         } while (mol == NULL);
-        Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl);
         do {
-          Log() << Verbose(0) << "Enter file name: ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter file name: ");
           cin >> filename;
         } while (!mol->AddXYZFile(filename));
@@ -1037,5 +1077,5 @@
 
     case 'r':
-      Log() << Verbose(0) << "Enter index of molecule: ";
+      DoLog(0) && (Log() << Verbose(0) << "Enter index of molecule: ");
       cin >> nr;
       count = 1;
@@ -1060,18 +1100,22 @@
   char choice;  // menu choice char
 
-  Log() << Verbose(0) << "===========MERGE MOLECULES=====================" << endl;
-  Log() << Verbose(0) << "a - simple add of one molecule to another" << endl;
-  Log() << Verbose(0) << "e - embedding merge of two molecules" << endl;
-  Log() << Verbose(0) << "m - multi-merge of all molecules" << endl;
-  Log() << Verbose(0) << "s - scatter merge of two molecules" << endl;
-  Log() << Verbose(0) << "t - simple merge of two molecules" << endl;
-  Log() << Verbose(0) << "all else - go back" << endl;
-  Log() << Verbose(0) << "===============================================" << endl;
-  Log() << Verbose(0) << "INPUT: ";
+  DoLog(0) && (Log() << Verbose(0) << "===========MERGE MOLECULES=====================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "a - simple add of one molecule to another" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "b - count the number of bonds of two elements" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "B - count the number of bonds of three elements " << endl);
+  DoLog(0) && (Log() << Verbose(0) << "e - embedding merge of two molecules" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "h - count the number of hydrogen bonds" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "b - count the number of hydrogen bonds" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "m - multi-merge of all molecules" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "s - scatter merge of two molecules" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "t - simple merge of two molecules" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "all else - go back" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "===============================================" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
   cin >> choice;
 
   switch (choice) {
     default:
-      Log() << Verbose(0) << "Not a valid choice." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Not a valid choice." << endl);
       break;
 
@@ -1082,10 +1126,10 @@
         {
           do {
-            Log() << Verbose(0) << "Enter index of destination molecule: ";
+            DoLog(0) && (Log() << Verbose(0) << "Enter index of destination molecule: ");
             cin >> dest;
             destmol = molecules->ReturnIndex(dest);
           } while ((destmol == NULL) && (dest != -1));
           do {
-            Log() << Verbose(0) << "Enter index of source molecule to add from: ";
+            DoLog(0) && (Log() << Verbose(0) << "Enter index of source molecule to add from: ");
             cin >> src;
             srcmol = molecules->ReturnIndex(src);
@@ -1097,4 +1141,56 @@
       break;
 
+    case 'b':
+      {
+        const int nr = 2;
+        char *names[nr] = {"first", "second"};
+        int Z[nr];
+        element *elements[nr];
+        for (int i=0;i<nr;i++) {
+          Z[i] = 0;
+          do {
+            cout << "Enter " << names[i] << " element: ";
+            cin >> Z[i];
+          } while ((Z[i] <= 0) && (Z[i] > MAX_ELEMENTS));
+          elements[i] = periode->FindElement(Z[i]);
+        }
+        const int count = CountBondsOfTwo(molecules, elements[0], elements[1]);
+        cout << endl << "There are " << count << " ";
+        for (int i=0;i<nr;i++) {
+          if (i==0)
+            cout << elements[i]->symbol;
+          else
+            cout << "-" << elements[i]->symbol;
+        }
+        cout << " bonds." << endl;
+      }
+    break;
+
+    case 'B':
+      {
+        const int nr = 3;
+        char *names[nr] = {"first", "second", "third"};
+        int Z[nr];
+        element *elements[nr];
+        for (int i=0;i<nr;i++) {
+          Z[i] = 0;
+          do {
+            cout << "Enter " << names[i] << " element: ";
+            cin >> Z[i];
+          } while ((Z[i] <= 0) && (Z[i] > MAX_ELEMENTS));
+          elements[i] = periode->FindElement(Z[i]);
+        }
+        const int count = CountBondsOfThree(molecules, elements[0], elements[1], elements[2]);
+        cout << endl << "There are " << count << " ";
+        for (int i=0;i<nr;i++) {
+          if (i==0)
+            cout << elements[i]->symbol;
+          else
+            cout << "-" << elements[i]->symbol;
+        }
+        cout << " bonds." << endl;
+      }
+    break;
+
     case 'e':
       {
@@ -1102,10 +1198,10 @@
         molecule *srcmol = NULL, *destmol = NULL;
         do {
-          Log() << Verbose(0) << "Enter index of matrix molecule (the variable one): ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter index of matrix molecule (the variable one): ");
           cin >> src;
           srcmol = molecules->ReturnIndex(src);
         } while ((srcmol == NULL) && (src != -1));
         do {
-          Log() << Verbose(0) << "Enter index of molecule to merge into (the fixed one): ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter index of molecule to merge into (the fixed one): ");
           cin >> dest;
           destmol = molecules->ReturnIndex(dest);
@@ -1116,4 +1212,14 @@
       break;
 
+    case 'h':
+      {
+        int Z;
+        cout << "Please enter interface element: ";
+        cin >> Z;
+        element * const InterfaceElement = periode->FindElement(Z);
+        cout << endl << "There are " << CountHydrogenBridgeBonds(molecules, InterfaceElement) << " hydrogen bridges with connections to " << (InterfaceElement != 0 ? InterfaceElement->name : "None") << "." << endl;
+      }
+      break;
+
     case 'm':
       {
@@ -1121,5 +1227,5 @@
         molecule *mol = NULL;
         do {
-          Log() << Verbose(0) << "Enter index of molecule to merge into: ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter index of molecule to merge into: ");
           cin >> nr;
           mol = molecules->ReturnIndex(nr);
@@ -1138,5 +1244,5 @@
 
     case 's':
-      Log() << Verbose(0) << "Not implemented yet." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Not implemented yet." << endl);
       break;
 
@@ -1147,10 +1253,10 @@
         {
           do {
-            Log() << Verbose(0) << "Enter index of destination molecule: ";
+            DoLog(0) && (Log() << Verbose(0) << "Enter index of destination molecule: ");
             cin >> dest;
             destmol = molecules->ReturnIndex(dest);
           } while ((destmol == NULL) && (dest != -1));
           do {
-            Log() << Verbose(0) << "Enter index of source molecule to merge into: ";
+            DoLog(0) && (Log() << Verbose(0) << "Enter index of source molecule to merge into: ");
             cin >> src;
             srcmol = molecules->ReturnIndex(src);
@@ -1180,5 +1286,5 @@
     mol = (molecules->ListOfMolecules.front())->CopyMolecule();
   else {
-    eLog() << Verbose(0) << "I don't have anything to test on ... ";
+    DoeLog(0) && (eLog()<< Verbose(0) << "I don't have anything to test on ... ");
     performCriticalExit();
     return;
@@ -1187,5 +1293,5 @@
 
   // generate some KeySets
-  Log() << Verbose(0) << "Generating KeySets." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Generating KeySets." << endl);
   KeySet TestSets[mol->AtomCount+1];
   i=1;
@@ -1197,11 +1303,11 @@
     i++;
   }
-  Log() << Verbose(0) << "Testing insertion of already present item in KeySets." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Testing insertion of already present item in KeySets." << endl);
   KeySetTestPair test;
   test = TestSets[mol->AtomCount-1].insert(Walker->nr);
   if (test.second) {
-    Log() << Verbose(1) << "Insertion worked?!" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Insertion worked?!" << endl);
   } else {
-    Log() << Verbose(1) << "Insertion rejected: Present object is " << (*test.first) << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Insertion rejected: Present object is " << (*test.first) << "." << endl);
   }
   TestSets[mol->AtomCount].insert(mol->end->previous->nr);
@@ -1209,37 +1315,37 @@
 
   // constructing Graph structure
-  Log() << Verbose(0) << "Generating Subgraph class." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Generating Subgraph class." << endl);
   Graph Subgraphs;
 
   // insert KeySets into Subgraphs
-  Log() << Verbose(0) << "Inserting KeySets into Subgraph class." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Inserting KeySets into Subgraph class." << endl);
   for (int j=0;j<mol->AtomCount;j++) {
     Subgraphs.insert(GraphPair (TestSets[j],pair<int, double>(counter++, 1.)));
   }
-  Log() << Verbose(0) << "Testing insertion of already present item in Subgraph." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Testing insertion of already present item in Subgraph." << endl);
   GraphTestPair test2;
   test2 = Subgraphs.insert(GraphPair (TestSets[mol->AtomCount],pair<int, double>(counter++, 1.)));
   if (test2.second) {
-    Log() << Verbose(1) << "Insertion worked?!" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Insertion worked?!" << endl);
   } else {
-    Log() << Verbose(1) << "Insertion rejected: Present object is " << (*(test2.first)).second.first << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Insertion rejected: Present object is " << (*(test2.first)).second.first << "." << endl);
   }
 
   // show graphs
-  Log() << Verbose(0) << "Showing Subgraph's contents, checking that it's sorted." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Showing Subgraph's contents, checking that it's sorted." << endl);
   Graph::iterator A = Subgraphs.begin();
   while (A !=  Subgraphs.end()) {
-    Log() << Verbose(0) << (*A).second.first << ": ";
+    DoLog(0) && (Log() << Verbose(0) << (*A).second.first << ": ");
     KeySet::iterator key = (*A).first.begin();
     comp = -1;
     while (key != (*A).first.end()) {
       if ((*key) > comp)
-        Log() << Verbose(0) << (*key) << " ";
+        DoLog(0) && (Log() << Verbose(0) << (*key) << " ");
       else
-        Log() << Verbose(0) << (*key) << "! ";
+        DoLog(0) && (Log() << Verbose(0) << (*key) << "! ");
       comp = (*key);
       key++;
     }
-    Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl);
     A++;
   }
@@ -1248,4 +1354,128 @@
 
 #endif
+
+/** Tries given filename or standard on saving the config file.
+ * \param *ConfigFileName name of file
+ * \param *configuration pointer to configuration structure with all the values
+ * \param *periode pointer to periodentafel structure with all the elements
+ * \param *molecules list of molecules structure with all the atoms and coordinates
+ */
+static void SaveConfig(char *ConfigFileName, config *configuration, periodentafel *periode, MoleculeListClass *molecules)
+{
+  char filename[MAXSTRINGSIZE];
+  ofstream output;
+  molecule *mol = World::getInstance().createMolecule();
+  mol->SetNameFromFilename(ConfigFileName);
+
+  if (!strcmp(configuration->configpath, configuration->GetDefaultPath())) {
+    DoeLog(2) && (eLog()<< Verbose(2) << "config is found under different path then stated in config file::defaultpath!" << endl);
+  }
+
+
+  // first save as PDB data
+  if (ConfigFileName != NULL)
+    strcpy(filename, ConfigFileName);
+  if (output == NULL)
+    strcpy(filename,"main_pcp_linux");
+  DoLog(0) && (Log() << Verbose(0) << "Saving as pdb input ");
+  if (configuration->SavePDB(filename, molecules))
+    DoLog(0) && (Log() << Verbose(0) << "done." << endl);
+  else
+    DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
+
+  // then save as tremolo data file
+  if (ConfigFileName != NULL)
+    strcpy(filename, ConfigFileName);
+  if (output == NULL)
+    strcpy(filename,"main_pcp_linux");
+  DoLog(0) && (Log() << Verbose(0) << "Saving as tremolo data input ");
+  if (configuration->SaveTREMOLO(filename, molecules))
+    DoLog(0) && (Log() << Verbose(0) << "done." << endl);
+  else
+    DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
+
+  // translate each to its center and merge all molecules in MoleculeListClass into this molecule
+  int N = molecules->ListOfMolecules.size();
+  int *src = new int[N];
+  N=0;
+  for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+    src[N++] = (*ListRunner)->IndexNr;
+    (*ListRunner)->Translate(&(*ListRunner)->Center);
+  }
+  molecules->SimpleMultiAdd(mol, src, N);
+  delete[](src);
+
+  // ... and translate back
+  for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+    (*ListRunner)->Center.Scale(-1.);
+    (*ListRunner)->Translate(&(*ListRunner)->Center);
+    (*ListRunner)->Center.Scale(-1.);
+  }
+
+  DoLog(0) && (Log() << Verbose(0) << "Storing configuration ... " << endl);
+  // get correct valence orbitals
+  mol->CalculateOrbitals(*configuration);
+  configuration->InitMaxMinStopStep = configuration->MaxMinStopStep = configuration->MaxPsiDouble;
+  if (ConfigFileName != NULL) { // test the file name
+    strcpy(filename, ConfigFileName);
+    output.open(filename, ios::trunc);
+  } else if (strlen(configuration->configname) != 0) {
+    strcpy(filename, configuration->configname);
+    output.open(configuration->configname, ios::trunc);
+    } else {
+      strcpy(filename, DEFAULTCONFIG);
+      output.open(DEFAULTCONFIG, ios::trunc);
+    }
+  output.close();
+  output.clear();
+  DoLog(0) && (Log() << Verbose(0) << "Saving of config file ");
+  if (configuration->Save(filename, periode, mol))
+    DoLog(0) && (Log() << Verbose(0) << "successful." << endl);
+  else
+    DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
+
+  // and save to xyz file
+  if (ConfigFileName != NULL) {
+    strcpy(filename, ConfigFileName);
+    strcat(filename, ".xyz");
+    output.open(filename, ios::trunc);
+  }
+  if (output == NULL) {
+    strcpy(filename,"main_pcp_linux");
+    strcat(filename, ".xyz");
+    output.open(filename, ios::trunc);
+  }
+  DoLog(0) && (Log() << Verbose(0) << "Saving of XYZ file ");
+  if (mol->MDSteps <= 1) {
+    if (mol->OutputXYZ(&output))
+      DoLog(0) && (Log() << Verbose(0) << "successful." << endl);
+    else
+      DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
+  } else {
+    if (mol->OutputTrajectoriesXYZ(&output))
+      DoLog(0) && (Log() << Verbose(0) << "successful." << endl);
+    else
+      DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
+  }
+  output.close();
+  output.clear();
+
+  // and save as MPQC configuration
+  if (ConfigFileName != NULL)
+    strcpy(filename, ConfigFileName);
+  if (output == NULL)
+    strcpy(filename,"main_pcp_linux");
+  DoLog(0) && (Log() << Verbose(0) << "Saving as mpqc input ");
+  if (configuration->SaveMPQC(filename, mol))
+    DoLog(0) && (Log() << Verbose(0) << "done." << endl);
+  else
+    DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
+
+  if (!strcmp(configuration->configpath, configuration->GetDefaultPath())) {
+    DoeLog(2) && (eLog()<< Verbose(2) << "config is found under different path then stated in config file::defaultpath!" << endl);
+  }
+
+  World::getInstance().destroyMolecule(mol);
+};
 
 /** Parses the command line options.
@@ -1274,4 +1504,5 @@
   enum ConfigStatus configPresent = absent;
   clock_t start,end;
+  double MaxDistance = -1;
   int argptr;
   molecule *mol = NULL;
@@ -1285,5 +1516,5 @@
     do {
       if (argv[argptr][0] == '-') {
-        Log() << Verbose(0) << "Recognized command line argument: " << argv[argptr][1] << ".\n";
+        DoLog(0) && (Log() << Verbose(0) << "Recognized command line argument: " << argv[argptr][1] << ".\n");
         argptr++;
         switch(argv[argptr-1][1]) {
@@ -1291,43 +1522,45 @@
           case 'H':
           case '?':
-            Log() << Verbose(0) << "MoleCuilder suite" << endl << "==================" << endl << endl;
-            Log() << Verbose(0) << "Usage: " << argv[0] << "[config file] [-{acefpsthH?vfrp}] [further arguments]" << endl;
-            Log() << Verbose(0) << "or simply " << argv[0] << " without arguments for interactive session." << endl;
-            Log() << Verbose(0) << "\t-a Z x1 x2 x3\tAdd new atom of element Z at coordinates (x1,x2,x3)." << endl;
-            Log() << Verbose(0) << "\t-A <source>\tCreate adjacency list from bonds parsed from 'dbond'-style file." <<endl;
-            Log() << Verbose(0) << "\t-b xx xy xz yy yz zz\tCenter atoms in domain with given symmetric matrix of (xx,xy,xz,yy,yz,zz)." << endl;
-            Log() << Verbose(0) << "\t-B xx xy xz yy yz zz\tBound atoms by domain with given symmetric matrix of (xx,xy,xz,yy,yz,zz)." << endl;
-            Log() << Verbose(0) << "\t-c x1 x2 x3\tCenter atoms in domain with a minimum distance to boundary of (x1,x2,x3)." << endl;
-            Log() << Verbose(0) << "\t-C <Z> <output> <bin output>\tPair Correlation analysis." << endl;
-            Log() << Verbose(0) << "\t-d x1 x2 x3\tDuplicate cell along each axis by given factor." << endl;
-            Log() << Verbose(0) << "\t-D <bond distance>\tDepth-First-Search Analysis of the molecule, giving cycles and tree/back edges." << endl;
-            Log() << Verbose(0) << "\t-e <file>\tSets the databases path to be parsed (default: ./)." << endl;
-            Log() << Verbose(0) << "\t-E <id> <Z>\tChange atom <id>'s element to <Z>, <id> begins at 0." << endl;
-            Log() << Verbose(0) << "\t-f <dist> <order>\tFragments the molecule in BOSSANOVA manner (with/out rings compressed) and stores config files in same dir as config (return code 0 - fragmented, 2 - no fragmentation necessary)." << endl;
-            Log() << Verbose(0) << "\t-F <dist_x> <dist_y> <dist_z> <epsilon> <randatom> <randmol> <DoRotate>\tFilling Box with water molecules." << endl;
-            Log() << Verbose(0) << "\t-g <file>\tParses a bond length table from the given file." << endl;
-            Log() << Verbose(0) << "\t-h/-H/-?\tGive this help screen." << endl;
-            Log() << Verbose(0) << "\t-I\t Dissect current system of molecules into a set of disconnected (subgraphs of) molecules." << endl;
-            Log() << Verbose(0) << "\t-j\t<path> Store all bonds to file." << endl;
-            Log() << Verbose(0) << "\t-J\t<path> Store adjacency per atom to file." << endl;
-            Log() << Verbose(0) << "\t-L <step0> <step1> <prefix>\tStore a linear interpolation between two configurations <step0> and <step1> into single config files with prefix <prefix> and as Trajectories into the current config file." << endl;
-            Log() << Verbose(0) << "\t-m <0/1>\tCalculate (0)/ Align in(1) PAS with greatest EV along z axis." << endl;
-            Log() << Verbose(0) << "\t-M <basis>\tSetting basis to store to MPQC config files." << endl;
-            Log() << Verbose(0) << "\t-n\tFast parsing (i.e. no trajectories are looked for)." << endl;
-            Log() << Verbose(0) << "\t-N <radius> <file>\tGet non-convex-envelope." << endl;
-            Log() << Verbose(0) << "\t-o <out>\tGet volume of the convex envelope (and store to tecplot file)." << endl;
-            Log() << Verbose(0) << "\t-O\tCenter atoms in origin." << endl;
-            Log() << Verbose(0) << "\t-p <file>\tParse given xyz file and create raw config file from it." << endl;
-            Log() << Verbose(0) << "\t-P <file>\tParse given forces file and append as an MD step to config file via Verlet." << endl;
-            Log() << Verbose(0) << "\t-r <id>\t\tRemove an atom with given id." << endl;
-            Log() << Verbose(0) << "\t-R <id> <radius>\t\tRemove all atoms out of sphere around a given one." << endl;
-            Log() << Verbose(0) << "\t-s x1 x2 x3\tScale all atom coordinates by this vector (x1,x2,x3)." << endl;
-            Log() << Verbose(0) << "\t-S <file> Store temperatures from the config file in <file>." << endl;
-            Log() << Verbose(0) << "\t-t x1 x2 x3\tTranslate all atoms by this vector (x1,x2,x3)." << endl;
-            Log() << Verbose(0) << "\t-T x1 x2 x3\tTranslate periodically all atoms by this vector (x1,x2,x3)." << endl;
-            Log() << Verbose(0) << "\t-u rho\tsuspend in water solution and output necessary cell lengths, average density rho and repetition." << endl;
-            Log() << Verbose(0) << "\t-v\t\tsets verbosity (more is more)." << endl;
-            Log() << Verbose(0) << "\t-V\t\tGives version information." << endl;
-            Log() << Verbose(0) << "Note: config files must not begin with '-' !" << endl;
+            DoLog(0) && (Log() << Verbose(0) << "MoleCuilder suite" << endl << "==================" << endl << endl);
+            DoLog(0) && (Log() << Verbose(0) << "Usage: " << argv[0] << "[config file] [-{acefpsthH?vfrp}] [further arguments]" << endl);
+            DoLog(0) && (Log() << Verbose(0) << "or simply " << argv[0] << " without arguments for interactive session." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-a Z x1 x2 x3\tAdd new atom of element Z at coordinates (x1,x2,x3)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-A <source>\tCreate adjacency list from bonds parsed from 'dbond'-style file." <<endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-b xx xy xz yy yz zz\tCenter atoms in domain with given symmetric matrix of (xx,xy,xz,yy,yz,zz)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-B xx xy xz yy yz zz\tBound atoms by domain with given symmetric matrix of (xx,xy,xz,yy,yz,zz)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-c x1 x2 x3\tCenter atoms in domain with a minimum distance to boundary of (x1,x2,x3)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-C <type> [params] <output> <bin output> <BinWidth> <BinStart> <BinEnd>\tPair Correlation analysis." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-d x1 x2 x3\tDuplicate cell along each axis by given factor." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-D <bond distance>\tDepth-First-Search Analysis of the molecule, giving cycles and tree/back edges." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-e <file>\tSets the databases path to be parsed (default: ./)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-E <id> <Z>\tChange atom <id>'s element to <Z>, <id> begins at 0." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-f <dist> <order>\tFragments the molecule in BOSSANOVA manner (with/out rings compressed) and stores config files in same dir as config (return code 0 - fragmented, 2 - no fragmentation necessary)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-F <xyz of filler> <dist_x> <dist_y> <dist_z> <epsilon> <randatom> <randmol> <DoRotate>\tFilling Box with water molecules." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-FF <MaxDistance> <xyz of filler> <dist_x> <dist_y> <dist_z> <epsilon> <randatom> <randmol> <DoRotate>\tFilling Box with water molecules." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-g <file>\tParses a bond length table from the given file." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-h/-H/-?\tGive this help screen." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-I\t Dissect current system of molecules into a set of disconnected (subgraphs of) molecules." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-j\t<path> Store all bonds to file." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-J\t<path> Store adjacency per atom to file." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-L <step0> <step1> <prefix>\tStore a linear interpolation between two configurations <step0> and <step1> into single config files with prefix <prefix> and as Trajectories into the current config file." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-m <0/1>\tCalculate (0)/ Align in(1) PAS with greatest EV along z axis." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-M <basis>\tSetting basis to store to MPQC config files." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-n\tFast parsing (i.e. no trajectories are looked for)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-N <radius> <file>\tGet non-convex-envelope." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-o <out>\tGet volume of the convex envelope (and store to tecplot file)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-O\tCenter atoms in origin." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-p <file>\tParse given xyz file and create raw config file from it." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-P <file>\tParse given forces file and append as an MD step to config file via Verlet." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-r <id>\t\tRemove an atom with given id." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-R <id> <radius>\t\tRemove all atoms out of sphere around a given one." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-s x1 x2 x3\tScale all atom coordinates by this vector (x1,x2,x3)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-S <file> Store temperatures from the config file in <file>." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-t x1 x2 x3\tTranslate all atoms by this vector (x1,x2,x3)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-T x1 x2 x3\tTranslate periodically all atoms by this vector (x1,x2,x3)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-u rho\tsuspend in water solution and output necessary cell lengths, average density rho and repetition." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-v\t\tsets verbosity (more is more)." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-V\t\tGives version information." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "\t-X\t\tset default name of a molecule." << endl);
+            DoLog(0) && (Log() << Verbose(0) << "Note: config files must not begin with '-' !" << endl);
             return (1);
             break;
@@ -1337,17 +1570,34 @@
             }
             setVerbosity(verbosity);
-            Log() << Verbose(0) << "Setting verbosity to " << verbosity << "." << endl;
+            DoLog(0) && (Log() << Verbose(0) << "Setting verbosity to " << verbosity << "." << endl);
             break;
           case 'V':
-            Log() << Verbose(0) << argv[0] << " " << VERSIONSTRING << endl;
-            Log() << Verbose(0) << "Build your own molecule position set." << endl;
+            DoLog(0) && (Log() << Verbose(0) << argv[0] << " " << VERSIONSTRING << endl);
+            DoLog(0) && (Log() << Verbose(0) << "Build your own molecule position set." << endl);
             return (1);
+            break;
+          case 'B':
+            if (ExitFlag == 0) ExitFlag = 1;
+            if ((argptr+5 >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) || (!IsValidNumber(argv[argptr+3])) || (!IsValidNumber(argv[argptr+4])) || (!IsValidNumber(argv[argptr+5])) ) {
+              ExitFlag = 255;
+              DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for bounding in box: -B <xx> <xy> <xz> <yy> <yz> <zz>" << endl);
+              performCriticalExit();
+            } else {
+              SaveFlag = true;
+              j = -1;
+              DoLog(1) && (Log() << Verbose(1) << "Centering atoms in config file within given simulation box." << endl);
+              double * const cell_size = World::getInstance().getDomain();
+              for (int i=0;i<6;i++) {
+                cell_size[i] = atof(argv[argptr+i]);
+              }
+              argptr+=6;
+            }
             break;
           case 'e':
             if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-              eLog() << Verbose(0) << "Not enough or invalid arguments for specifying element db: -e <db file>" << endl;
+              DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments for specifying element db: -e <db file>" << endl);
               performCriticalExit();
             } else {
-              Log() << Verbose(0) << "Using " << argv[argptr] << " as elements database." << endl;
+              DoLog(0) && (Log() << Verbose(0) << "Using " << argv[argptr] << " as elements database." << endl);
               strncpy (configuration.databasepath, argv[argptr], MAXSTRINGSIZE-1);
               argptr+=1;
@@ -1356,15 +1606,21 @@
           case 'g':
             if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-              eLog() << Verbose(0) << "Not enough or invalid arguments for specifying bond length table: -g <table file>" << endl;
+              DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments for specifying bond length table: -g <table file>" << endl);
               performCriticalExit();
             } else {
               BondGraphFileName = argv[argptr];
-              Log() << Verbose(0) << "Using " << BondGraphFileName << " as bond length table." << endl;
+              DoLog(0) && (Log() << Verbose(0) << "Using " << BondGraphFileName << " as bond length table." << endl);
               argptr+=1;
             }
             break;
           case 'n':
-            Log() << Verbose(0) << "I won't parse trajectories." << endl;
+            DoLog(0) && (Log() << Verbose(0) << "I won't parse trajectories." << endl);
             configuration.FastParsing = true;
+            break;
+          case 'X':
+            {
+              World::getInstance().setDefaultName(argv[argptr]);
+              DoLog(0) && (Log() << Verbose(0) << "Default name of new molecules set to " << *World::getInstance().getDefaultName() << "." << endl);
+            }
             break;
           default:   // no match? Step on
@@ -1378,8 +1634,8 @@
     // 3a. Parse the element database
     if (periode->LoadPeriodentafel(configuration.databasepath)) {
-      Log() << Verbose(0) << "Element list loaded successfully." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Element list loaded successfully." << endl);
       //periode->Output();
     } else {
-      Log() << Verbose(0) << "Element list loading failed." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Element list loading failed." << endl);
       return 1;
     }
@@ -1387,5 +1643,5 @@
     if (argv[1][0] != '-') {
       // simply create a new molecule, wherein the config file is loaded and the manipulation takes place
-      Log() << Verbose(0) << "Config file given." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Config file given." << endl);
       test.open(argv[1], ios::in);
       if (test == NULL) {
@@ -1393,8 +1649,8 @@
         output.open(argv[1], ios::out);
         if (output == NULL) {
-          Log() << Verbose(1) << "Specified config file " << argv[1] << " not found." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "Specified config file " << argv[1] << " not found." << endl);
           configPresent = absent;
         } else {
-          Log() << Verbose(0) << "Empty configuration file." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "Empty configuration file." << endl);
           ConfigFileName = argv[1];
           configPresent = empty;
@@ -1404,18 +1660,18 @@
         test.close();
         ConfigFileName = argv[1];
-        Log() << Verbose(1) << "Specified config file found, parsing ... ";
+        DoLog(1) && (Log() << Verbose(1) << "Specified config file found, parsing ... ");
         switch (configuration.TestSyntax(ConfigFileName, periode)) {
           case 1:
-            Log() << Verbose(0) << "new syntax." << endl;
+            DoLog(0) && (Log() << Verbose(0) << "new syntax." << endl);
             configuration.Load(ConfigFileName, BondGraphFileName, periode, molecules);
             configPresent = present;
             break;
           case 0:
-            Log() << Verbose(0) << "old syntax." << endl;
+            DoLog(0) && (Log() << Verbose(0) << "old syntax." << endl);
             configuration.LoadOld(ConfigFileName, BondGraphFileName, periode, molecules);
             configPresent = present;
             break;
           default:
-            Log() << Verbose(0) << "Unknown syntax or empty, yet present file." << endl;
+            DoLog(0) && (Log() << Verbose(0) << "Unknown syntax or empty, yet present file." << endl);
             configPresent = empty;
        }
@@ -1432,5 +1688,5 @@
      }
      if (mol == NULL) {
-       mol = new molecule(periode);
+       mol = World::getInstance().createMolecule();
        mol->ActiveFlag = true;
        if (ConfigFileName != NULL)
@@ -1441,7 +1697,7 @@
        configuration.BG = new BondGraph(configuration.GetIsAngstroem());
        if ((!BondGraphFileName.empty()) && (configuration.BG->LoadBondLengthTable(BondGraphFileName))) {
-         Log() << Verbose(0) << "Bond length table loaded successfully." << endl;
+         DoLog(0) && (Log() << Verbose(0) << "Bond length table loaded successfully." << endl);
        } else {
-         eLog() << Verbose(1) << "Bond length table loading failed." << endl;
+         DoeLog(1) && (eLog()<< Verbose(1) << "Bond length table loading failed." << endl);
        }
      }
@@ -1450,5 +1706,5 @@
     argptr = 1;
     do {
-      Log() << Verbose(0) << "Current Command line argument: " << argv[argptr] << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Current Command line argument: " << argv[argptr] << "." << endl);
       if (argv[argptr][0] == '-') {
         argptr++;
@@ -1459,13 +1715,13 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-')) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough arguments for parsing: -p <xyz file>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough arguments for parsing: -p <xyz file>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
-                Log() << Verbose(1) << "Parsing xyz file for new atoms." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Parsing xyz file for new atoms." << endl);
                 if (!mol->AddXYZFile(argv[argptr]))
-                  Log() << Verbose(2) << "File not found." << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "File not found." << endl);
                 else {
-                  Log() << Verbose(2) << "File found and parsed." << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "File found and parsed." << endl);
                   configPresent = present;
                 }
@@ -1476,15 +1732,15 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) || (!IsValidNumber(argv[argptr+3]))) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments for adding atom: -a <element> <x> <y> <z>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments for adding atom: -a <element> <x> <y> <z>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
                 Log() << Verbose(1) << "Adding new atom with element " << argv[argptr] << " at (" << argv[argptr+1] << "," << argv[argptr+2] << "," << argv[argptr+3] << "), ";
-                first = new atom;
+                first = World::getInstance().createAtom();
                 first->type = periode->FindElement(atoi(argv[argptr]));
                 if (first->type != NULL)
-                  Log() << Verbose(2) << "found element " << first->type->name << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "found element " << first->type->name << endl);
                 for (int i=NDIM;i--;)
-                  first->x.x[i] = atof(argv[argptr+1+i]);
+                  first->x[i] = atof(argv[argptr+1+i]);
                 if (first->type != NULL) {
                   mol->AddAtom(first);  // add to molecule
@@ -1492,5 +1748,5 @@
                     configPresent = present;
                 } else
-                  eLog() << Verbose(1) << "Could not find the specified element." << endl;
+                  DoeLog(1) && (eLog()<< Verbose(1) << "Could not find the specified element." << endl);
                 argptr+=4;
               }
@@ -1505,9 +1761,9 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-')) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for setting MPQC basis: -B <basis name>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for setting MPQC basis: -B <basis name>" << endl);
                 performCriticalExit();
               } else {
                 configuration.basis = argv[argptr];
-                Log() << Verbose(1) << "Setting MPQC basis to " << configuration.basis << "." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Setting MPQC basis to " << configuration.basis << "." << endl);
                 argptr+=1;
               }
@@ -1516,5 +1772,5 @@
               if (ExitFlag == 0) ExitFlag = 1;
               {
-                Log() << Verbose(1) << "Depth-First-Search Analysis." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Depth-First-Search Analysis." << endl);
                 MoleculeLeafClass *Subgraphs = NULL;      // list of subgraphs from DFS analysis
                 int *MinimumRingSize = new int[mol->AtomCount];
@@ -1547,5 +1803,5 @@
               break;
             case 'I':
-              Log() << Verbose(1) << "Dissecting molecular system into a set of disconnected subgraphs ... " << endl;
+              DoLog(1) && (Log() << Verbose(1) << "Dissecting molecular system into a set of disconnected subgraphs ... " << endl);
               // @TODO rather do the dissection afterwards
               molecules->DissectMoleculeIntoConnectedSubgraphs(periode, &configuration);
@@ -1558,65 +1814,173 @@
                   }
               }
-              if (mol == NULL) {
+              if ((mol == NULL) && (!molecules->ListOfMolecules.empty())) {
                 mol = *(molecules->ListOfMolecules.begin());
-                mol->ActiveFlag = true;
+                if (mol != NULL)
+                  mol->ActiveFlag = true;
               }
               break;
             case 'C':
-              if (ExitFlag == 0) ExitFlag = 1;
-              if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (argv[argptr][0] == '-') || (argv[argptr+1][0] == '-') || (argv[argptr+2][0] == '-')) {
-                ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for pair correlation analysis: -C <Z> <output> <bin output>" << endl;
-                performCriticalExit();
-              } else {
-                ofstream output(argv[argptr+1]);
-                ofstream binoutput(argv[argptr+2]);
-                const double radius = 5.;
-
-                // get the boundary
-                class molecule *Boundary = NULL;
-                class Tesselation *TesselStruct = NULL;
-                const LinkedCell *LCList = NULL;
-                // find biggest molecule
-                int counter  = 0;
-                for (MoleculeList::iterator BigFinder = molecules->ListOfMolecules.begin(); BigFinder != molecules->ListOfMolecules.end(); BigFinder++) {
-                  if ((Boundary == NULL) || (Boundary->AtomCount < (*BigFinder)->AtomCount)) {
-                    Boundary = *BigFinder;
+              {
+                int ranges[3] = {1, 1, 1};
+                bool periodic = (argv[argptr-1][2] =='p');
+                if (ExitFlag == 0) ExitFlag = 1;
+                if ((argptr >= argc)) {
+                  ExitFlag = 255;
+                  DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for pair correlation analysis: -C[p] <type: E/P/S> [more params] <output> <bin output> <BinStart> <BinEnd>" << endl);
+                  performCriticalExit();
+                } else {
+                  switch(argv[argptr][0]) {
+                    case 'E':
+                      {
+                        if ((argptr+6 >= argc) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+5])) || (!IsValidNumber(argv[argptr+6])) || (!IsValidNumber(argv[argptr+2])) || (argv[argptr+1][0] == '-') || (argv[argptr+2][0] == '-') || (argv[argptr+3][0] == '-') || (argv[argptr+4][0] == '-')) {
+                          ExitFlag = 255;
+                          DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for pair correlation analysis: -C E <Z1> <Z2> <output> <bin output>" << endl);
+                          performCriticalExit();
+                        } else {
+                          ofstream output(argv[argptr+3]);
+                          ofstream binoutput(argv[argptr+4]);
+                          const double BinStart = atof(argv[argptr+5]);
+                          const double BinEnd = atof(argv[argptr+6]);
+
+                          const element *elemental = periode->FindElement((const int) atoi(argv[argptr+1]));
+                          const element *elemental2 = periode->FindElement((const int) atoi(argv[argptr+2]));
+                          PairCorrelationMap *correlationmap = NULL;
+                          if (periodic)
+                            correlationmap = PeriodicPairCorrelation(molecules, elemental, elemental2, ranges);
+                          else
+                            correlationmap = PairCorrelation(molecules, elemental, elemental2);
+                          //OutputCorrelationToSurface(&output, correlationmap);
+                          BinPairMap *binmap = BinData( correlationmap, 0.5, BinStart, BinEnd );
+                          OutputCorrelation ( &binoutput, binmap );
+                          output.close();
+                          binoutput.close();
+                          delete(binmap);
+                          delete(correlationmap);
+                          argptr+=7;
+                        }
+                      }
+                      break;
+
+                    case 'P':
+                      {
+                        if ((argptr+8 >= argc) || (!IsValidNumber(argv[argptr+1])) ||  (!IsValidNumber(argv[argptr+2])) || (!IsValidNumber(argv[argptr+3])) || (!IsValidNumber(argv[argptr+4])) || (!IsValidNumber(argv[argptr+7])) || (!IsValidNumber(argv[argptr+8])) || (argv[argptr+1][0] == '-') || (argv[argptr+2][0] == '-') || (argv[argptr+3][0] == '-') || (argv[argptr+4][0] == '-') || (argv[argptr+5][0] == '-') || (argv[argptr+6][0] == '-')) {
+                          ExitFlag = 255;
+                          DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for pair correlation analysis: -C P <Z1> <x> <y> <z> <output> <bin output>" << endl);
+                          performCriticalExit();
+                        } else {
+                          ofstream output(argv[argptr+5]);
+                          ofstream binoutput(argv[argptr+6]);
+                          const double BinStart = atof(argv[argptr+7]);
+                          const double BinEnd = atof(argv[argptr+8]);
+
+                          const element *elemental = periode->FindElement((const int) atoi(argv[argptr+1]));
+                          Vector *Point = new Vector((const double) atof(argv[argptr+1]),(const double) atof(argv[argptr+2]),(const double) atof(argv[argptr+3]));
+                          CorrelationToPointMap *correlationmap = NULL;
+                          if (periodic)
+                            correlationmap  = PeriodicCorrelationToPoint(molecules, elemental, Point, ranges);
+                          else
+                            correlationmap = CorrelationToPoint(molecules, elemental, Point);
+                          //OutputCorrelationToSurface(&output, correlationmap);
+                          BinPairMap *binmap = BinData( correlationmap, 0.5, BinStart, BinEnd );
+                          OutputCorrelation ( &binoutput, binmap );
+                          output.close();
+                          binoutput.close();
+                          delete(Point);
+                          delete(binmap);
+                          delete(correlationmap);
+                          argptr+=9;
+                        }
+                      }
+                      break;
+
+                    case 'S':
+                      {
+                        if ((argptr+6 >= argc) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+4])) || (!IsValidNumber(argv[argptr+5])) || (!IsValidNumber(argv[argptr+6])) || (argv[argptr+1][0] == '-') || (argv[argptr+2][0] == '-') || (argv[argptr+3][0] == '-')) {
+                          ExitFlag = 255;
+                          DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for pair correlation analysis: -C S <Z> <output> <bin output> <BinWidth> <BinStart> <BinEnd>" << endl);
+                          performCriticalExit();
+                        } else {
+                          ofstream output(argv[argptr+2]);
+                          ofstream binoutput(argv[argptr+3]);
+                          const double radius = 4.;
+                          const double BinWidth = atof(argv[argptr+4]);
+                          const double BinStart = atof(argv[argptr+5]);
+                          const double BinEnd = atof(argv[argptr+6]);
+                          double LCWidth = 20.;
+                          if (BinEnd > 0) {
+                            if (BinEnd > 2.*radius)
+                                LCWidth = BinEnd;
+                            else
+                              LCWidth = 2.*radius;
+                          }
+
+                          // get the boundary
+                          class molecule *Boundary = NULL;
+                          class Tesselation *TesselStruct = NULL;
+                          const LinkedCell *LCList = NULL;
+                          // find biggest molecule
+                          int counter  = 0;
+                          for (MoleculeList::iterator BigFinder = molecules->ListOfMolecules.begin(); BigFinder != molecules->ListOfMolecules.end(); BigFinder++) {
+                            if ((Boundary == NULL) || (Boundary->AtomCount < (*BigFinder)->AtomCount)) {
+                              Boundary = *BigFinder;
+                            }
+                            counter++;
+                          }
+                          bool *Actives = Malloc<bool>(counter, "ParseCommandLineOptions() - case C -- *Actives");
+                          counter = 0;
+                          for (MoleculeList::iterator BigFinder = molecules->ListOfMolecules.begin(); BigFinder != molecules->ListOfMolecules.end(); BigFinder++) {
+                            Actives[counter++] = (*BigFinder)->ActiveFlag;
+                            (*BigFinder)->ActiveFlag = (*BigFinder == Boundary) ? false : true;
+                          }
+                          LCList = new LinkedCell(Boundary, LCWidth);
+                          const element *elemental = periode->FindElement((const int) atoi(argv[argptr+1]));
+                          FindNonConvexBorder(Boundary, TesselStruct, LCList, radius, NULL);
+                          CorrelationToSurfaceMap *surfacemap = NULL;
+                          if (periodic)
+                            surfacemap = PeriodicCorrelationToSurface( molecules, elemental, TesselStruct, LCList, ranges);
+                          else
+                            surfacemap = CorrelationToSurface( molecules, elemental, TesselStruct, LCList);
+                          OutputCorrelationToSurface(&output, surfacemap);
+                          // check whether radius was appropriate
+                          {
+                            double start; double end;
+                            GetMinMax( surfacemap, start, end);
+                            if (LCWidth < end)
+                              DoeLog(1) && (eLog()<< Verbose(1) << "Linked Cell width is smaller than the found range of values! Bins can only be correct up to: " << radius << "." << endl);
+                          }
+                          BinPairMap *binmap = BinData( surfacemap, BinWidth, BinStart, BinEnd );
+                          OutputCorrelation ( &binoutput, binmap );
+                          output.close();
+                          binoutput.close();
+                          for (MoleculeList::iterator BigFinder = molecules->ListOfMolecules.begin(); BigFinder != molecules->ListOfMolecules.end(); BigFinder++)
+                            (*BigFinder)->ActiveFlag = Actives[counter++];
+                          Free(&Actives);
+                          delete(LCList);
+                          delete(TesselStruct);
+                          delete(binmap);
+                          delete(surfacemap);
+                          argptr+=7;
+                        }
+                      }
+                      break;
+
+                    default:
+                      ExitFlag = 255;
+                      DoeLog(0) && (eLog()<< Verbose(0) << "Invalid type given for pair correlation analysis: -C <type: E/P/S> [more params] <output> <bin output>" << endl);
+                      performCriticalExit();
+                      break;
                   }
-                  counter++;
                 }
-                bool *Actives = Malloc<bool>(counter, "ParseCommandLineOptions() - case C -- *Actives");
-                counter = 0;
-                for (MoleculeList::iterator BigFinder = molecules->ListOfMolecules.begin(); BigFinder != molecules->ListOfMolecules.end(); BigFinder++) {
-                  Actives[counter++] = (*BigFinder)->ActiveFlag;
-                  (*BigFinder)->ActiveFlag = (*BigFinder == Boundary) ? false : true;
-                }
-                LCList = new LinkedCell(Boundary, 2.*radius);
-                element *elemental = periode->FindElement((const int) atoi(argv[argptr]));
-                FindNonConvexBorder(Boundary, TesselStruct, LCList, radius, NULL);
-                int ranges[NDIM] = {1,1,1};
-                CorrelationToSurfaceMap *surfacemap = PeriodicCorrelationToSurface( molecules, elemental, TesselStruct, LCList, ranges );
-                OutputCorrelationToSurface(&output, surfacemap);
-                BinPairMap *binmap = BinData( surfacemap, 0.5, 0., 20. );
-                OutputCorrelation ( &binoutput, binmap );
-                output.close();
-                binoutput.close();
-                for (MoleculeList::iterator BigFinder = molecules->ListOfMolecules.begin(); BigFinder != molecules->ListOfMolecules.end(); BigFinder++)
-                  (*BigFinder)->ActiveFlag = Actives[counter++];
-                Free(&Actives);
-                delete(LCList);
-                delete(TesselStruct);
-                argptr+=3;
-              }
-              break;
+                break;
+              }
             case 'E':
               if (ExitFlag == 0) ExitFlag = 1;
               if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (argv[argptr+1][0] == '-')) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for changing element: -E <atom nr.> <element>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for changing element: -E <atom nr.> <element>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
-                Log() << Verbose(1) << "Changing atom " << argv[argptr] << " to element " << argv[argptr+1] << "." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Changing atom " << argv[argptr] << " to element " << argv[argptr+1] << "." << endl);
                 first = mol->FindAtom(atoi(argv[argptr]));
                 first->type = periode->FindElement(atoi(argv[argptr+1]));
@@ -1626,30 +1990,37 @@
             case 'F':
               if (ExitFlag == 0) ExitFlag = 1;
-              if (argptr+6 >=argc) {
+              MaxDistance = -1;
+              if (argv[argptr-1][2] == 'F') { // option is -FF?
+                // fetch first argument as max distance to surface
+                MaxDistance = atof(argv[argptr++]);
+                DoLog(0) && (Log() << Verbose(0) << "Filling with maximum layer distance of " << MaxDistance << "." << endl);
+              }
+              if ((argptr+7 >=argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) || (!IsValidNumber(argv[argptr+3])) || (!IsValidNumber(argv[argptr+4])) || (!IsValidNumber(argv[argptr+5])) || (!IsValidNumber(argv[argptr+6])) || (!IsValidNumber(argv[argptr+7]))) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for filling box with water: -F <dist_x> <dist_y> <dist_z> <boundary> <randatom> <randmol> <DoRotate>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for filling box with water: -F <xyz of filler> <dist_x> <dist_y> <dist_z> <boundary> <randatom> <randmol> <DoRotate>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
-                Log() << Verbose(1) << "Filling Box with water molecules." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Filling Box with water molecules." << endl);
                 // construct water molecule
-                molecule *filler = new molecule(periode);
+                molecule *filler = World::getInstance().createMolecule();
+                if (!filler->AddXYZFile(argv[argptr])) {
+                  DoeLog(0) && (eLog()<< Verbose(0) << "Could not parse filler molecule from " << argv[argptr] << "." << endl);
+                }
+                filler->SetNameFromFilename(argv[argptr]);
+                configuration.BG->ConstructBondGraph(filler);
                 molecule *Filling = NULL;
                 atom *second = NULL, *third = NULL;
-//                first = new atom();
-//                first->type = periode->FindElement(5);
-//                first->x.Zero();
-//                filler->AddAtom(first);
-                first = new atom();
+                first = World::getInstance().createAtom();
                 first->type = periode->FindElement(1);
-                first->x.Init(0.441, -0.143, 0.);
+                first->x = Vector(0.441, -0.143, 0.);
                 filler->AddAtom(first);
-                second = new atom();
+                second = World::getInstance().createAtom();
                 second->type = periode->FindElement(1);
-                second->x.Init(-0.464, 1.137, 0.0);
+                second->x = Vector(-0.464, 1.137, 0.0);
                 filler->AddAtom(second);
-                third = new atom();
+                third = World::getInstance().createAtom();
                 third->type = periode->FindElement(8);
-                third->x.Init(-0.464, 0.177, 0.);
+                third->x = Vector(-0.464, 0.177, 0.);
                 filler->AddAtom(third);
                 filler->AddBond(first, third, 1);
@@ -1658,11 +2029,11 @@
                 double distance[NDIM];
                 for (int i=0;i<NDIM;i++)
-                  distance[i] = atof(argv[argptr+i]);
-                Filling = FillBoxWithMolecule(molecules, filler, configuration, distance, atof(argv[argptr+3]), atof(argv[argptr+4]), atof(argv[argptr+5]), atoi(argv[argptr+6]));
+                  distance[i] = atof(argv[argptr+i+1]);
+                Filling = FillBoxWithMolecule(molecules, filler, configuration, MaxDistance, distance, atof(argv[argptr+4]), atof(argv[argptr+5]), atof(argv[argptr+6]), atoi(argv[argptr+7]));
                 if (Filling != NULL) {
                   Filling->ActiveFlag = false;
                   molecules->insert(Filling);
                 }
-                delete(filler);
+                World::getInstance().destroyMolecule(filler);
                 argptr+=6;
               }
@@ -1672,8 +2043,8 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-')) {
                 ExitFlag =255;
-                eLog() << Verbose(0) << "Missing source file for bonds in molecule: -A <bond sourcefile>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Missing source file for bonds in molecule: -A <bond sourcefile>" << endl);
                 performCriticalExit();
               } else {
-                Log() << Verbose(0) << "Parsing bonds from " << argv[argptr] << "." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Parsing bonds from " << argv[argptr] << "." << endl);
                 ifstream *input = new ifstream(argv[argptr]);
                 mol->CreateAdjacencyListFromDbondFile(input);
@@ -1687,10 +2058,10 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-')) {
                 ExitFlag =255;
-                eLog() << Verbose(0) << "Missing path of adjacency file: -j <path>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Missing path of adjacency file: -j <path>" << endl);
                 performCriticalExit();
               } else {
-                Log() << Verbose(0) << "Storing adjacency to path " << argv[argptr] << "." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Storing adjacency to path " << argv[argptr] << "." << endl);
                 configuration.BG->ConstructBondGraph(mol);
-                mol->StoreAdjacencyToFile(argv[argptr]);
+                mol->StoreAdjacencyToFile(NULL, argv[argptr]);
                 argptr+=1;
               }
@@ -1701,10 +2072,10 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-')) {
                 ExitFlag =255;
-                eLog() << Verbose(0) << "Missing path of bonds file: -j <path>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Missing path of bonds file: -j <path>" << endl);
                 performCriticalExit();
               } else {
-                Log() << Verbose(0) << "Storing bonds to path " << argv[argptr] << "." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Storing bonds to path " << argv[argptr] << "." << endl);
                 configuration.BG->ConstructBondGraph(mol);
-                mol->StoreBondsToFile(argv[argptr]);
+                mol->StoreBondsToFile(NULL, argv[argptr]);
                 argptr+=1;
               }
@@ -1715,5 +2086,5 @@
               if ((argptr+1 >= argc) || (argv[argptr+1][0] == '-')){
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for non-convex envelope: -o <radius> <tecplot output file>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for non-convex envelope: -o <radius> <tecplot output file>" << endl);
                 performCriticalExit();
               } else {
@@ -1723,6 +2094,6 @@
                 //string filename(argv[argptr+1]);
                 //filename.append(".csv");
-                Log() << Verbose(0) << "Evaluating non-convex envelope of biggest molecule.";
-                Log() << Verbose(1) << "Using rolling ball of radius " << atof(argv[argptr]) << " and storing tecplot data in " << argv[argptr+1] << "." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Evaluating non-convex envelope of biggest molecule.");
+                DoLog(1) && (Log() << Verbose(1) << "Using rolling ball of radius " << atof(argv[argptr]) << " and storing tecplot data in " << argv[argptr+1] << "." << endl);
                 // find biggest molecule
                 int counter  = 0;
@@ -1734,5 +2105,5 @@
                   counter++;
                 }
-                Log() << Verbose(1) << "Biggest molecule has " << Boundary->AtomCount << " atoms." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Biggest molecule has " << Boundary->AtomCount << " atoms." << endl);
                 start = clock();
                 LCList = new LinkedCell(Boundary, atof(argv[argptr])*2.);
@@ -1741,5 +2112,5 @@
                 //FindDistributionOfEllipsoids(T, &LCList, N, number, filename.c_str());
                 end = clock();
-                Log() << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl);
                 delete(LCList);
                 delete(T);
@@ -1751,13 +2122,13 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-')) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for storing tempature: -S <temperature file>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for storing tempature: -S <temperature file>" << endl);
                 performCriticalExit();
               } else {
-                Log() << Verbose(1) << "Storing temperatures in " << argv[argptr] << "." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Storing temperatures in " << argv[argptr] << "." << endl);
                 ofstream *output = new ofstream(argv[argptr], ios::trunc);
                 if (!mol->OutputTemperatureFromTrajectories(output, 0, mol->MDSteps))
-                  Log() << Verbose(2) << "File could not be written." << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "File could not be written." << endl);
                 else
-                  Log() << Verbose(2) << "File stored." << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "File stored." << endl);
                 output->close();
                 delete(output);
@@ -1769,15 +2140,15 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-')) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for storing tempature: -L <step0> <step1> <prefix> <identity mapping?>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for storing tempature: -L <step0> <step1> <prefix> <identity mapping?>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
-                Log() << Verbose(1) << "Linear interpolation between configuration " << argv[argptr] << " and " << argv[argptr+1] << "." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Linear interpolation between configuration " << argv[argptr] << " and " << argv[argptr+1] << "." << endl);
                 if (atoi(argv[argptr+3]) == 1)
-                  Log() << Verbose(1) << "Using Identity for the permutation map." << endl;
+                  DoLog(1) && (Log() << Verbose(1) << "Using Identity for the permutation map." << endl);
                 if (!mol->LinearInterpolationBetweenConfiguration(atoi(argv[argptr]), atoi(argv[argptr+1]), argv[argptr+2], configuration, atoi(argv[argptr+3])) == 1 ? true : false)
-                  Log() << Verbose(2) << "Could not store " << argv[argptr+2] << " files." << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "Could not store " << argv[argptr+2] << " files." << endl);
                 else
-                  Log() << Verbose(2) << "Steps created and " << argv[argptr+2] << " files stored." << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "Steps created and " << argv[argptr+2] << " files stored." << endl);
                 argptr+=4;
               }
@@ -1787,13 +2158,13 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-')) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for parsing and integrating forces: -P <forces file>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for parsing and integrating forces: -P <forces file>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
-                Log() << Verbose(1) << "Parsing forces file and Verlet integrating." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Parsing forces file and Verlet integrating." << endl);
                 if (!mol->VerletForceIntegration(argv[argptr], configuration))
-                  Log() << Verbose(2) << "File not found." << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "File not found." << endl);
                 else
-                  Log() << Verbose(2) << "File found and parsed." << endl;
+                  DoLog(2) && (Log() << Verbose(2) << "File found and parsed." << endl);
                 argptr+=1;
               }
@@ -1803,9 +2174,9 @@
               if ((argptr+1 >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])))  {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for removing atoms: -R <id> <distance>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for removing atoms: -R <id> <distance>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
-                Log() << Verbose(1) << "Removing atoms around " << argv[argptr] << " with radius " << argv[argptr+1] << "." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Removing atoms around " << argv[argptr] << " with radius " << argv[argptr+1] << "." << endl);
                 double tmp1 = atof(argv[argptr+1]);
                 atom *third = mol->FindAtom(atoi(argv[argptr]));
@@ -1816,9 +2187,9 @@
                     first = second;
                     second = first->next;
-                    if (first->x.DistanceSquared((const Vector *)&third->x) > tmp1*tmp1) // distance to first above radius ...
+                    if (first->x.DistanceSquared(third->x) > tmp1*tmp1) // distance to first above radius ...
                       mol->RemoveAtom(first);
                   }
                 } else {
-                  eLog() << Verbose(1) << "Removal failed due to missing atoms on molecule or wrong id." << endl;
+                  DoeLog(1) && (eLog()<< Verbose(1) << "Removal failed due to missing atoms on molecule or wrong id." << endl);
                 }
                 argptr+=2;
@@ -1829,12 +2200,12 @@
               if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for translation: -t <x> <y> <z>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for translation: -t <x> <y> <z>" << endl);
                 performCriticalExit();
               } else {
                 if (ExitFlag == 0) ExitFlag = 1;
                 SaveFlag = true;
-                Log() << Verbose(1) << "Translating all ions by given vector." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Translating all ions by given vector." << endl);
                 for (int i=NDIM;i--;)
-                  x.x[i] = atof(argv[argptr+i]);
+                  x[i] = atof(argv[argptr+i]);
                 mol->Translate((const Vector *)&x);
                 argptr+=3;
@@ -1845,12 +2216,12 @@
               if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for periodic translation: -T <x> <y> <z>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for periodic translation: -T <x> <y> <z>" << endl);
                 performCriticalExit();
               } else {
                 if (ExitFlag == 0) ExitFlag = 1;
                 SaveFlag = true;
-                Log() << Verbose(1) << "Translating all ions periodically by given vector." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Translating all ions periodically by given vector." << endl);
                 for (int i=NDIM;i--;)
-                  x.x[i] = atof(argv[argptr+i]);
+                  x[i] = atof(argv[argptr+i]);
                 mol->TranslatePeriodically((const Vector *)&x);
                 argptr+=3;
@@ -1861,10 +2232,10 @@
               if ((argptr >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for scaling: -s <factor_x> [factor_y] [factor_z]" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for scaling: -s <factor_x> [factor_y] [factor_z]" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
                 j = -1;
-                Log() << Verbose(1) << "Scaling all ion positions by factor." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Scaling all ion positions by factor." << endl);
                 factor = new double[NDIM];
                 factor[0] = atof(argv[argptr]);
@@ -1872,8 +2243,9 @@
                 factor[2] = atof(argv[argptr+2]);
                 mol->Scale((const double ** const)&factor);
+                double * const cell_size = World::getInstance().getDomain();
                 for (int i=0;i<NDIM;i++) {
                   j += i+1;
-                  x.x[i] = atof(argv[NDIM+i]);
-                  mol->cell_size[j]*=factor[i];
+                  x[i] = atof(argv[NDIM+i]);
+                  cell_size[j]*=factor[i];
                 }
                 delete[](factor);
@@ -1885,12 +2257,13 @@
               if ((argptr+5 >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) || (!IsValidNumber(argv[argptr+3])) || (!IsValidNumber(argv[argptr+4])) || (!IsValidNumber(argv[argptr+5])) ) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for centering in box: -b <xx> <xy> <xz> <yy> <yz> <zz>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for centering in box: -b <xx> <xy> <xz> <yy> <yz> <zz>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
                 j = -1;
-                Log() << Verbose(1) << "Centering atoms in config file within given simulation box." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Centering atoms in config file within given simulation box." << endl);
+                double * const cell_size = World::getInstance().getDomain();
                 for (int i=0;i<6;i++) {
-                  mol->cell_size[i] = atof(argv[argptr+i]);
+                  cell_size[i] = atof(argv[argptr+i]);
                 }
                 // center
@@ -1903,12 +2276,13 @@
               if ((argptr+5 >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) || (!IsValidNumber(argv[argptr+3])) || (!IsValidNumber(argv[argptr+4])) || (!IsValidNumber(argv[argptr+5])) ) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for bounding in box: -B <xx> <xy> <xz> <yy> <yz> <zz>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for bounding in box: -B <xx> <xy> <xz> <yy> <yz> <zz>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
                 j = -1;
-                Log() << Verbose(1) << "Centering atoms in config file within given simulation box." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Centering atoms in config file within given simulation box." << endl);
+                double * const cell_size = World::getInstance().getDomain();
                 for (int i=0;i<6;i++) {
-                  mol->cell_size[i] = atof(argv[argptr+i]);
+                  cell_size[i] = atof(argv[argptr+i]);
                 }
                 // center
@@ -1921,10 +2295,10 @@
               if ((argptr+2 >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for centering with boundary: -c <boundary_x> <boundary_y> <boundary_z>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for centering with boundary: -c <boundary_x> <boundary_y> <boundary_z>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
                 j = -1;
-                Log() << Verbose(1) << "Centering atoms in config file within given additional boundary." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Centering atoms in config file within given additional boundary." << endl);
                 // make every coordinate positive
                 mol->CenterEdge(&x);
@@ -1932,9 +2306,10 @@
                 mol->SetBoxDimension(&x);
                 // translate each coordinate by boundary
+                double * const cell_size = World::getInstance().getDomain();
                 j=-1;
                 for (int i=0;i<NDIM;i++) {
                   j += i+1;
-                  x.x[i] = atof(argv[argptr+i]);
-                  mol->cell_size[j] += x.x[i]*2.;
+                  x[i] = atof(argv[argptr+i]);
+                  cell_size[j] += x[i]*2.;
                 }
                 mol->Translate((const Vector *)&x);
@@ -1945,5 +2320,5 @@
               if (ExitFlag == 0) ExitFlag = 1;
               SaveFlag = true;
-              Log() << Verbose(1) << "Centering atoms on edge and setting box dimensions." << endl;
+              DoLog(1) && (Log() << Verbose(1) << "Centering atoms on edge and setting box dimensions." << endl);
               x.Zero();
               mol->CenterEdge(&x);
@@ -1955,9 +2330,9 @@
               if ((argptr >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])))  {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for removing atoms: -r <id>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for removing atoms: -r <id>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
-                Log() << Verbose(1) << "Removing atom " << argv[argptr] << "." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Removing atom " << argv[argptr] << "." << endl);
                 atom *first = mol->FindAtom(atoi(argv[argptr]));
                 mol->RemoveAtom(first);
@@ -1969,17 +2344,17 @@
               if ((argptr+1 >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1]))) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments for fragmentation: -f <max. bond distance> <bond order>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments for fragmentation: -f <max. bond distance> <bond order>" << endl);
                 performCriticalExit();
               } else {
-                Log() << Verbose(0) << "Fragmenting molecule with bond distance " << argv[argptr] << " angstroem, order of " << argv[argptr+1] << "." << endl;
-                Log() << Verbose(0) << "Creating connection matrix..." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Fragmenting molecule with bond distance " << argv[argptr] << " angstroem, order of " << argv[argptr+1] << "." << endl);
+                DoLog(0) && (Log() << Verbose(0) << "Creating connection matrix..." << endl);
                 start = clock();
-                mol->CreateAdjacencyList(atof(argv[argptr++]), configuration.GetIsAngstroem(), &BondGraph::CovalentMinMaxDistance, NULL);
-                Log() << Verbose(0) << "Fragmenting molecule with current connection matrix ..." << endl;
+                mol->CreateAdjacencyList(atof(argv[argptr]), configuration.GetIsAngstroem(), &BondGraph::CovalentMinMaxDistance, NULL);
+                DoLog(0) && (Log() << Verbose(0) << "Fragmenting molecule with current connection matrix ..." << endl);
                 if (mol->first->next != mol->last) {
-                  ExitFlag = mol->FragmentMolecule(atoi(argv[argptr]), &configuration);
+                  ExitFlag = mol->FragmentMolecule(atoi(argv[argptr+1]), &configuration);
                 }
                 end = clock();
-                Log() << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl);
                 argptr+=2;
               }
@@ -1989,12 +2364,12 @@
               j = atoi(argv[argptr++]);
               if ((j<0) || (j>1)) {
-                eLog() << Verbose(1) << "Argument of '-m' should be either 0 for no-rotate or 1 for rotate." << endl;
+                DoeLog(1) && (eLog()<< Verbose(1) << "Argument of '-m' should be either 0 for no-rotate or 1 for rotate." << endl);
                 j = 0;
               }
               if (j) {
                 SaveFlag = true;
-                Log() << Verbose(0) << "Converting to prinicipal axis system." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Converting to prinicipal axis system." << endl);
               } else
-                Log() << Verbose(0) << "Evaluating prinicipal axis." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Evaluating prinicipal axis." << endl);
               mol->PrincipalAxisSystem((bool)j);
               break;
@@ -2003,12 +2378,12 @@
               if ((argptr+1 >= argc) || (argv[argptr][0] == '-')){
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for convex envelope: -o <convex output file> <non-convex output file>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for convex envelope: -o <convex output file> <non-convex output file>" << endl);
                 performCriticalExit();
               } else {
                 class Tesselation *TesselStruct = NULL;
                 const LinkedCell *LCList = NULL;
-                Log() << Verbose(0) << "Evaluating volume of the convex envelope.";
-                Log() << Verbose(1) << "Storing tecplot convex data in " << argv[argptr] << "." << endl;
-                Log() << Verbose(1) << "Storing tecplot non-convex data in " << argv[argptr+1] << "." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Evaluating volume of the convex envelope.");
+                DoLog(1) && (Log() << Verbose(1) << "Storing tecplot convex data in " << argv[argptr] << "." << endl);
+                DoLog(1) && (Log() << Verbose(1) << "Storing tecplot non-convex data in " << argv[argptr+1] << "." << endl);
                 LCList = new LinkedCell(mol, 10.);
                 //FindConvexBorder(mol, LCList, argv[argptr]);
@@ -2017,6 +2392,6 @@
                 double volumedifference = ConvexizeNonconvexEnvelope(TesselStruct, mol, argv[argptr]);
                 double clustervolume = VolumeOfConvexEnvelope(TesselStruct, &configuration);
-                Log() << Verbose(0) << "The tesselated volume area is " << clustervolume << " " << (configuration.GetIsAngstroem() ? "angstrom" : "atomiclength") << "^3." << endl;
-                Log() << Verbose(0) << "The non-convex tesselated volume area is " << clustervolume-volumedifference << " " << (configuration.GetIsAngstroem() ? "angstrom" : "atomiclength") << "^3." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "The tesselated volume area is " << clustervolume << " " << (configuration.GetIsAngstroem() ? "angstrom" : "atomiclength") << "^3." << endl);
+                DoLog(0) && (Log() << Verbose(0) << "The non-convex tesselated volume area is " << clustervolume-volumedifference << " " << (configuration.GetIsAngstroem() ? "angstrom" : "atomiclength") << "^3." << endl);
                 delete(TesselStruct);
                 delete(LCList);
@@ -2028,9 +2403,9 @@
               if ((argptr+1 >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) ) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for suspension with specified volume: -U <volume> <density>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for suspension with specified volume: -U <volume> <density>" << endl);
                 performCriticalExit();
               } else {
                 volume = atof(argv[argptr++]);
-                Log() << Verbose(0) << "Using " << volume << " angstrom^3 as the volume instead of convex envelope one's." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Using " << volume << " angstrom^3 as the volume instead of convex envelope one's." << endl);
               }
             case 'u':
@@ -2039,13 +2414,13 @@
                 if (volume != -1)
                   ExitFlag = 255;
-                  eLog() << Verbose(0) << "Not enough or invalid arguments given for suspension: -u <density>" << endl;
+                  DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for suspension: -u <density>" << endl);
                   performCriticalExit();
               } else {
                 double density;
                 SaveFlag = true;
-                Log() << Verbose(0) << "Evaluating necessary cell volume for a cluster suspended in water.";
+                DoLog(0) && (Log() << Verbose(0) << "Evaluating necessary cell volume for a cluster suspended in water.");
                 density = atof(argv[argptr++]);
                 if (density < 1.0) {
-                  eLog() << Verbose(1) << "Density must be greater than 1.0g/cm^3 !" << endl;
+                  DoeLog(1) && (eLog()<< Verbose(1) << "Density must be greater than 1.0g/cm^3 !" << endl);
                   density = 1.3;
                 }
@@ -2053,5 +2428,5 @@
 //                  repetition[i] = atoi(argv[argptr++]);
 //                  if (repetition[i] < 1)
-//                    eLog() << Verbose(1) << "repetition value must be greater 1!" << endl;
+//                    DoeLog(1) && (eLog()<< Verbose(1) << "repetition value must be greater 1!" << endl);
 //                  repetition[i] = 1;
 //                }
@@ -2063,15 +2438,16 @@
               if ((argptr+2 >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for repeating cells: -d <repeat_x> <repeat_y> <repeat_z>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for repeating cells: -d <repeat_x> <repeat_y> <repeat_z>" << endl);
                 performCriticalExit();
               } else {
                 SaveFlag = true;
+                double * const cell_size = World::getInstance().getDomain();
                 for (int axis = 1; axis <= NDIM; axis++) {
                   int faktor = atoi(argv[argptr++]);
                   int count;
-                  element ** Elements;
+                  const element ** Elements;
                   Vector ** vectors;
                   if (faktor < 1) {
-                    eLog() << Verbose(1) << "Repetition factor mus be greater than 1!" << endl;
+                    DoeLog(1) && (eLog()<< Verbose(1) << "Repetition factor mus be greater than 1!" << endl);
                     faktor = 1;
                   }
@@ -2079,5 +2455,5 @@
                   if (mol->AtomCount != 0) {  // if there is more than none
                     count = mol->AtomCount;   // is changed becausing of adding, thus has to be stored away beforehand
-                    Elements = new element *[count];
+                    Elements = new const element *[count];
                     vectors = new Vector *[count];
                     j = 0;
@@ -2090,14 +2466,13 @@
                     }
                     if (count != j)
-                      eLog() << Verbose(1) << "AtomCount " << count << " is not equal to number of atoms in molecule " << j << "!" << endl;
+                      DoeLog(1) && (eLog()<< Verbose(1) << "AtomCount " << count << " is not equal to number of atoms in molecule " << j << "!" << endl);
                     x.Zero();
                     y.Zero();
-                    y.x[abs(axis)-1] = mol->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] * abs(axis)/axis; // last term is for sign, first is for magnitude
+                    y[abs(axis)-1] = cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] * abs(axis)/axis; // last term is for sign, first is for magnitude
                     for (int i=1;i<faktor;i++) {  // then add this list with respective translation factor times
-                      x.AddVector(&y); // per factor one cell width further
+                      x += y; // per factor one cell width further
                       for (int k=count;k--;) { // go through every atom of the original cell
-                        first = new atom(); // create a new body
-                        first->x.CopyVector(vectors[k]);  // use coordinate of original atom
-                        first->x.AddVector(&x);      // translate the coordinates
+                        first = World::getInstance().createAtom(); // create a new body
+                        first->x = (*vectors[k]) + x;
                         first->type = Elements[k];  // insert original element
                         mol->AddAtom(first);        // and add to the molecule (which increments ElementsInMolecule, AtomCount, ...)
@@ -2109,10 +2484,8 @@
                     // correct cell size
                     if (axis < 0) { // if sign was negative, we have to translate everything
-                      x.Zero();
-                      x.AddVector(&y);
-                      x.Scale(-(faktor-1));
+                      x =(-(faktor-1)) * y;
                       mol->Translate(&x);
                     }
-                    mol->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor;
+                    cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor;
                   }
                 }
@@ -2131,7 +2504,7 @@
   } else {  // no arguments, hence scan the elements db
     if (periode->LoadPeriodentafel(configuration.databasepath))
-      Log() << Verbose(0) << "Element list loaded successfully." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Element list loaded successfully." << endl);
     else
-      Log() << Verbose(0) << "Element list loading failed." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Element list loading failed." << endl);
     configuration.RetrieveConfigPathAndName("main_pcp_linux");
   }
@@ -2139,35 +2512,9 @@
 };
 
-/***************************************** Functions used to build all menus **********************/
-
-void populateEditMoleculesMenu(Menu* editMoleculesMenu,MoleculeListClass *molecules, config *configuration, periodentafel *periode){
-  // build the EditMoleculesMenu
-  Action *createMoleculeAction = new MethodAction("createMoleculeAction",boost::bind(&MoleculeListClass::createNewMolecule,molecules,periode));
-  new ActionMenuItem('c',"create new molecule",editMoleculesMenu,createMoleculeAction);
-
-  Action *loadMoleculeAction = new MethodAction("loadMoleculeAction",boost::bind(&MoleculeListClass::loadFromXYZ,molecules,periode));
-  new ActionMenuItem('l',"load molecule from xyz file",editMoleculesMenu,loadMoleculeAction);
-
-  Action *changeFilenameAction = new ChangeMoleculeNameAction(molecules);
-  new ActionMenuItem('n',"change molecule's name",editMoleculesMenu,changeFilenameAction);
-
-  Action *giveFilenameAction = new MethodAction("giveFilenameAction",boost::bind(&MoleculeListClass::setMoleculeFilename,molecules));
-  new ActionMenuItem('N',"give molecules filename",editMoleculesMenu,giveFilenameAction);
-
-  Action *parseAtomsAction = new MethodAction("parseAtomsAction",boost::bind(&MoleculeListClass::parseXYZIntoMolecule,molecules));
-  new ActionMenuItem('p',"parse atoms in xyz file into molecule",editMoleculesMenu,parseAtomsAction);
-
-  Action *eraseMoleculeAction = new MethodAction("eraseMoleculeAction",boost::bind(&MoleculeListClass::eraseMolecule,molecules));
-  new ActionMenuItem('r',"remove a molecule",editMoleculesMenu,eraseMoleculeAction);
-
-}
-
-
 /********************************************** Main routine **************************************/
 
-void cleanUp(config *configuration){
+void cleanUp(){
   UIFactory::purgeInstance();
-  World::destroy();
-  delete(configuration);
+  World::purgeInstance();
   Log() << Verbose(0) <<  "Maximum of allocated memory: "
     << MemoryUsageObserver::getInstance()->getMaximumUsedMemory() << endl;
@@ -2177,56 +2524,44 @@
   logger::purgeInstance();
   errorLogger::purgeInstance();
-  ActionRegistry::purgeRegistry();
+  CommandLineParser::purgeInstance();
+  ActionRegistry::purgeInstance();
+  ActionHistory::purgeInstance();
 }
 
 int main(int argc, char **argv)
 {
-    molecule *mol = NULL;
-    config *configuration = new config;
+    config *configuration = World::getInstance().getConfig();
     Vector x, y, z, n;
     ifstream test;
     ofstream output;
     string line;
-    char *ConfigFileName = NULL;
-    int j;
+
+    cout << ESPACKVersion << endl;
+
     setVerbosity(0);
-    /* structure of ParseCommandLineOptions will be refactored later */
-    j = ParseCommandLineOptions(argc, argv,  World::get()->getMolecules(), World::get()->getPeriode(), *configuration, ConfigFileName);
-    switch (j){
-        case 255:
-        case 2:
-        case 1:
-            cleanUp(configuration);
-            return (j == 1 ? 0 : j);
-        default:
-            break;
+    // need to init the history before any action is created
+    ActionHistory::init();
+
+    {
+      // Parse command line options and if present create respective UI
+      CommandLineParser::getInstance().generic.add_options()
+          ("help,h", "produce help message")
+          ("version,v", "show version")
+          ("parse-xyz,p", po::value< vector<string> >(), "parse xyz file into World")
+          ;
+      CommandLineParser::getInstance().Run(argc,argv);
+      if (!CommandLineParser::getInstance().isEmpty())
+        UIFactory::makeUserInterface(UIFactory::CommandLine);
+      else
+        UIFactory::makeUserInterface(UIFactory::Text);
     }
-    if(World::get()->numMolecules() == 0){
-        mol = World::get()->createMolecule();
-        if(mol->cell_size[0] == 0.){
-            Log() << Verbose(0) << "enter lower tridiagonal form of basis matrix" << endl << endl;
-            for(int i = 0;i < 6;i++){
-                Log() << Verbose(1) << "Cell size" << i << ": ";
-                cin >> mol->cell_size[i];
-            }
-        }
-        mol->ActiveFlag = true;
-    }
 
     {
-      cout << ESPACKVersion << endl;
-
-      setVerbosity(0);
-
-      menuPopulaters populaters;
-      populaters.MakeEditMoleculesMenu = populateEditMoleculesMenu;
-
-      UIFactory::makeUserInterface(UIFactory::Text);
-      MainWindow *mainWindow = UIFactory::get()->makeMainWindow(populaters,World::get()->getMolecules(), configuration, World::get()->getPeriode(), ConfigFileName);
+      MainWindow *mainWindow = UIFactory::getInstance().makeMainWindow();
       mainWindow->display();
       delete mainWindow;
     }
 
-    if(World::get()->getPeriode()->StorePeriodentafel(configuration->databasepath))
+    if(World::getInstance().getPeriode()->StorePeriodentafel(configuration->databasepath))
         Log() << Verbose(0) << "Saving of elements.db successful." << endl;
 
@@ -2234,5 +2569,7 @@
         Log() << Verbose(0) << "Saving of elements.db failed." << endl;
 
-  cleanUp(configuration);
+  cleanUp();
+
+  Memory::getState();
   return (0);
 }
Index: src/config.cpp
===================================================================
--- src/config.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/config.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -8,4 +8,5 @@
 #include <cstring>
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
@@ -19,4 +20,5 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
+#include "World.hpp"
 
 /******************************** Functions for class ConfigFileBuffer **********************/
@@ -73,5 +75,5 @@
   file= new ifstream(filename);
   if (file == NULL) {
-    eLog() << Verbose(1) << "config file " << filename << " missing!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "config file " << filename << " missing!" << endl);
     return;
   }
@@ -84,9 +86,9 @@
   file->clear();
   file->seekg(file_position, ios::beg);
-  Log() << Verbose(1) << NoLines-1 << " lines were recognized." << endl;
+  DoLog(1) && (Log() << Verbose(1) << NoLines-1 << " lines were recognized." << endl);
 
   // allocate buffer's 1st dimension
   if (buffer != NULL) {
-    eLog() << Verbose(1) << "FileBuffer->buffer is not NULL!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "FileBuffer->buffer is not NULL!" << endl);
     return;
   } else
@@ -104,5 +106,5 @@
     lines++;
   } while((!file->eof()) && (lines < NoLines));
-  Log() << Verbose(1) << lines-1 << " lines were read into the buffer." << endl;
+  DoLog(1) && (Log() << Verbose(1) << lines-1 << " lines were read into the buffer." << endl);
 
   // close and exit
@@ -143,5 +145,5 @@
   map<const char *, int, IonTypeCompare> IonTypeLineMap;
   if (LineMapping == NULL) {
-    eLog() << Verbose(0) << "map pointer is NULL: " << LineMapping << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "map pointer is NULL: " << LineMapping << endl);
     performCriticalExit();
     return;
@@ -159,5 +161,5 @@
       LineMapping[CurrentLine+(nr++)] = runner->second;
     else {
-      eLog() << Verbose(0) << "config::MapIonTypesInBuffer - NoAtoms is wrong: We are past the end of the file!" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "config::MapIonTypesInBuffer - NoAtoms is wrong: We are past the end of the file!" << endl);
       performCriticalExit();
     }
@@ -249,5 +251,5 @@
         Thermostat = None;
       } else {
-        Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl);
         Thermostat = None;
       }
@@ -257,5 +259,5 @@
         ParseForParameter(verbose,fb,"Thermostat", 0, 2, 1, int_type, &ScaleTempStep, 1, critical); // read scaling frequency
       } else {
-        Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl);
         Thermostat = None;
       }
@@ -265,5 +267,5 @@
         ParseForParameter(verbose,fb,"Thermostat", 0, 2, 1, int_type, &ScaleTempStep, 1, critical); // read collision rate
       } else {
-        Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl);
         Thermostat = None;
       }
@@ -273,10 +275,10 @@
         ParseForParameter(verbose,fb,"Thermostat", 0, 2, 1, double_type, &TempFrequency, 1, critical); // read gamma
         if (ParseForParameter(verbose,fb,"Thermostat", 0, 3, 1, double_type, &alpha, 1, optional)) {
-          Log() << Verbose(2) << "Extended Stochastic Thermostat detected with interpolation coefficient " << alpha << "." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "Extended Stochastic Thermostat detected with interpolation coefficient " << alpha << "." << endl);
         } else {
           alpha = 1.;
         }
       } else {
-        Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl);
         Thermostat = None;
       }
@@ -286,5 +288,5 @@
         ParseForParameter(verbose,fb,"Thermostat", 0, 2, 1, double_type, &TempFrequency, 1, critical); // read \tau_T
       } else {
-        Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl);
         Thermostat = None;
       }
@@ -295,14 +297,14 @@
         alpha = 0.;
       } else {
-        Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl);
         Thermostat = None;
       }
     } else {
-      Log() << Verbose(1) << " Warning: thermostat name was not understood!" << endl;
+      DoLog(1) && (Log() << Verbose(1) << " Warning: thermostat name was not understood!" << endl);
       Thermostat = None;
     }
   } else {
     if ((MaxOuterStep > 0) && (TargetTemp != 0)) 
-      Log() << Verbose(2) <<  "No thermostat chosen despite finite temperature MD, falling back to None." << endl;
+      DoLog(2) && (Log() << Verbose(2) <<  "No thermostat chosen despite finite temperature MD, falling back to None." << endl);
     Thermostat = None;
   }
@@ -320,178 +322,178 @@
 
   do {
-    Log() << Verbose(0) << "===========EDIT CONFIGURATION============================" << endl;
-    Log() << Verbose(0) << " A - mainname (prefix for all runtime files)" << endl;
-    Log() << Verbose(0) << " B - Default path (for runtime files)" << endl;
-    Log() << Verbose(0) << " C - Path of pseudopotential files" << endl;
-    Log() << Verbose(0) << " D - Number of coefficient sharing processes" << endl;
-    Log() << Verbose(0) << " E - Number of wave function sharing processes" << endl;
-    Log() << Verbose(0) << " F - 0: Don't output density for OpenDX, 1: do" << endl;
-    Log() << Verbose(0) << " G - 0: Don't output physical data, 1: do" << endl;
-    Log() << Verbose(0) << " H - 0: Don't output densities of each unperturbed orbital for OpenDX, 1: do" << endl;
-    Log() << Verbose(0) << " I - 0: Don't output current density for OpenDX, 1: do" << endl;
-    Log() << Verbose(0) << " J - 0: Don't do the full current calculation, 1: do" << endl;
-    Log() << Verbose(0) << " K - 0: Don't do perturbation calculation to obtain susceptibility and shielding, 1: do" << endl;
-    Log() << Verbose(0) << " L - 0: Wannier centres as calculated, 1: common centre for all, 2: unite centres according to spread, 3: cell centre, 4: shifted to nearest grid point" << endl;
-    Log() << Verbose(0) << " M - Absolute begin of unphysical sawtooth transfer for position operator within cell" << endl;
-    Log() << Verbose(0) << " N - (0,1,2) x,y,z-plane to do two-dimensional current vector cut" << endl;
-    Log() << Verbose(0) << " O - Absolute position along vector cut axis for cut plane" << endl;
-    Log() << Verbose(0) << " P - Additional Gram-Schmidt-Orthonormalization to stabilize numerics" << endl;
-    Log() << Verbose(0) << " Q - Initial integer value of random number generator" << endl;
-    Log() << Verbose(0) << " R - for perturbation 0, for structure optimization defines upper limit of iterations" << endl;
-    Log() << Verbose(0) << " T - Output visual after ...th step" << endl;
-    Log() << Verbose(0) << " U - Output source densities of wave functions after ...th step" << endl;
-    Log() << Verbose(0) << " X - minimization iterations per wave function, if unsure leave at default value 0" << endl;
-    Log() << Verbose(0) << " Y - tolerance value for total spread in iterative Jacobi diagonalization" << endl;
-    Log() << Verbose(0) << " Z - Maximum number of minimization iterations" << endl;
-    Log() << Verbose(0) << " a - Relative change in total energy to stop min. iteration" << endl;
-    Log() << Verbose(0) << " b - Relative change in kinetic energy to stop min. iteration" << endl;
-    Log() << Verbose(0) << " c - Check stop conditions every ..th step during min. iteration" << endl;
-    Log() << Verbose(0) << " e - Maximum number of minimization iterations during initial level" << endl;
-    Log() << Verbose(0) << " f - Relative change in total energy to stop min. iteration during initial level" << endl;
-    Log() << Verbose(0) << " g - Relative change in kinetic energy to stop min. iteration during initial level" << endl;
-    Log() << Verbose(0) << " h - Check stop conditions every ..th step during min. iteration during initial level" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "===========EDIT CONFIGURATION============================" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " A - mainname (prefix for all runtime files)" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " B - Default path (for runtime files)" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " C - Path of pseudopotential files" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " D - Number of coefficient sharing processes" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " E - Number of wave function sharing processes" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " F - 0: Don't output density for OpenDX, 1: do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " G - 0: Don't output physical data, 1: do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " H - 0: Don't output densities of each unperturbed orbital for OpenDX, 1: do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " I - 0: Don't output current density for OpenDX, 1: do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " J - 0: Don't do the full current calculation, 1: do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " K - 0: Don't do perturbation calculation to obtain susceptibility and shielding, 1: do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " L - 0: Wannier centres as calculated, 1: common centre for all, 2: unite centres according to spread, 3: cell centre, 4: shifted to nearest grid point" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " M - Absolute begin of unphysical sawtooth transfer for position operator within cell" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " N - (0,1,2) x,y,z-plane to do two-dimensional current vector cut" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " O - Absolute position along vector cut axis for cut plane" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " P - Additional Gram-Schmidt-Orthonormalization to stabilize numerics" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " Q - Initial integer value of random number generator" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " R - for perturbation 0, for structure optimization defines upper limit of iterations" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " T - Output visual after ...th step" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " U - Output source densities of wave functions after ...th step" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " X - minimization iterations per wave function, if unsure leave at default value 0" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " Y - tolerance value for total spread in iterative Jacobi diagonalization" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " Z - Maximum number of minimization iterations" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " a - Relative change in total energy to stop min. iteration" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " b - Relative change in kinetic energy to stop min. iteration" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " c - Check stop conditions every ..th step during min. iteration" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " e - Maximum number of minimization iterations during initial level" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " f - Relative change in total energy to stop min. iteration during initial level" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " g - Relative change in kinetic energy to stop min. iteration during initial level" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " h - Check stop conditions every ..th step during min. iteration during initial level" << endl);
 //    Log() << Verbose(0) << " j - six lower diagonal entries of matrix, defining the unit cell" << endl;
-    Log() << Verbose(0) << " k - Energy cutoff of plane wave basis in Hartree" << endl;
-    Log() << Verbose(0) << " l - Maximum number of levels in multi-level-ansatz" << endl;
-    Log() << Verbose(0) << " m - Factor by which grid nodes increase between standard and upper level" << endl;
-    Log() << Verbose(0) << " n - 0: Don't use RiemannTensor, 1: Do" << endl;
-    Log() << Verbose(0) << " o - Factor by which grid nodes increase between Riemann and standard(?) level" << endl;
-    Log() << Verbose(0) << " p - Number of Riemann levels" << endl;
-    Log() << Verbose(0) << " r - 0: Don't Use RiemannTensor, 1: Do" << endl;
-    Log() << Verbose(0) << " s - 0: Doubly occupied orbitals, 1: Up-/Down-Orbitals" << endl;
-    Log() << Verbose(0) << " t - Number of orbitals (depends pn SpinType)" << endl;
-    Log() << Verbose(0) << " u - Number of SpinUp orbitals (depends on SpinType)" << endl;
-    Log() << Verbose(0) << " v - Number of SpinDown orbitals (depends on SpinType)" << endl;
-    Log() << Verbose(0) << " w - Number of additional, unoccupied orbitals" << endl;
-    Log() << Verbose(0) << " x - radial cutoff for ewald summation in Bohrradii" << endl;
-    Log() << Verbose(0) << " y - 0: Don't do structure optimization beforehand, 1: Do" << endl;
-    Log() << Verbose(0) << " z - 0: Units are in Bohr radii, 1: units are in Aengstrom" << endl;
-    Log() << Verbose(0) << " i - 0: Coordinates given in file are absolute, 1: ... are relative to unit cell" << endl;
-    Log() << Verbose(0) << "=========================================================" << endl;
-    Log() << Verbose(0) << "INPUT: ";
+    DoLog(0) && (Log() << Verbose(0) << " k - Energy cutoff of plane wave basis in Hartree" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " l - Maximum number of levels in multi-level-ansatz" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " m - Factor by which grid nodes increase between standard and upper level" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " n - 0: Don't use RiemannTensor, 1: Do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " o - Factor by which grid nodes increase between Riemann and standard(?) level" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " p - Number of Riemann levels" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " r - 0: Don't Use RiemannTensor, 1: Do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " s - 0: Doubly occupied orbitals, 1: Up-/Down-Orbitals" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " t - Number of orbitals (depends pn SpinType)" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " u - Number of SpinUp orbitals (depends on SpinType)" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " v - Number of SpinDown orbitals (depends on SpinType)" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " w - Number of additional, unoccupied orbitals" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " x - radial cutoff for ewald summation in Bohrradii" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " y - 0: Don't do structure optimization beforehand, 1: Do" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " z - 0: Units are in Bohr radii, 1: units are in Aengstrom" << endl);
+    DoLog(0) && (Log() << Verbose(0) << " i - 0: Coordinates given in file are absolute, 1: ... are relative to unit cell" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "=========================================================" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
     cin >> choice;
 
     switch (choice) {
         case 'A': // mainname
-          Log() << Verbose(0) << "Old: " << config::mainname << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::mainname << "\t new: ");
           cin >> config::mainname;
           break;
         case 'B': // defaultpath
-          Log() << Verbose(0) << "Old: " << config::defaultpath << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::defaultpath << "\t new: ");
           cin >> config::defaultpath;
           break;
         case 'C': // pseudopotpath
-          Log() << Verbose(0) << "Old: " << config::pseudopotpath << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::pseudopotpath << "\t new: ");
           cin >> config::pseudopotpath;
           break;
 
         case 'D': // ProcPEGamma
-          Log() << Verbose(0) << "Old: " << config::ProcPEGamma << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::ProcPEGamma << "\t new: ");
           cin >> config::ProcPEGamma;
           break;
         case 'E': // ProcPEPsi
-          Log() << Verbose(0) << "Old: " << config::ProcPEPsi << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::ProcPEPsi << "\t new: ");
           cin >> config::ProcPEPsi;
           break;
         case 'F': // DoOutVis
-          Log() << Verbose(0) << "Old: " << config::DoOutVis << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoOutVis << "\t new: ");
           cin >> config::DoOutVis;
           break;
         case 'G': // DoOutMes
-          Log() << Verbose(0) << "Old: " << config::DoOutMes << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoOutMes << "\t new: ");
           cin >> config::DoOutMes;
           break;
         case 'H': // DoOutOrbitals
-          Log() << Verbose(0) << "Old: " << config::DoOutOrbitals << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoOutOrbitals << "\t new: ");
           cin >> config::DoOutOrbitals;
           break;
         case 'I': // DoOutCurrent
-          Log() << Verbose(0) << "Old: " << config::DoOutCurrent << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoOutCurrent << "\t new: ");
           cin >> config::DoOutCurrent;
           break;
         case 'J': // DoFullCurrent
-          Log() << Verbose(0) << "Old: " << config::DoFullCurrent << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoFullCurrent << "\t new: ");
           cin >> config::DoFullCurrent;
           break;
         case 'K': // DoPerturbation
-          Log() << Verbose(0) << "Old: " << config::DoPerturbation << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoPerturbation << "\t new: ");
           cin >> config::DoPerturbation;
           break;
         case 'L': // CommonWannier
-          Log() << Verbose(0) << "Old: " << config::CommonWannier << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::CommonWannier << "\t new: ");
           cin >> config::CommonWannier;
           break;
         case 'M': // SawtoothStart
-          Log() << Verbose(0) << "Old: " << config::SawtoothStart << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::SawtoothStart << "\t new: ");
           cin >> config::SawtoothStart;
           break;
         case 'N': // VectorPlane
-          Log() << Verbose(0) << "Old: " << config::VectorPlane << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::VectorPlane << "\t new: ");
           cin >> config::VectorPlane;
           break;
         case 'O': // VectorCut
-          Log() << Verbose(0) << "Old: " << config::VectorCut << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::VectorCut << "\t new: ");
           cin >> config::VectorCut;
           break;
         case 'P': // UseAddGramSch
-          Log() << Verbose(0) << "Old: " << config::UseAddGramSch << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::UseAddGramSch << "\t new: ");
           cin >> config::UseAddGramSch;
           break;
         case 'Q': // Seed
-          Log() << Verbose(0) << "Old: " << config::Seed << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::Seed << "\t new: ");
           cin >> config::Seed;
           break;
 
         case 'R': // MaxOuterStep
-          Log() << Verbose(0) << "Old: " << config::MaxOuterStep << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxOuterStep << "\t new: ");
           cin >> config::MaxOuterStep;
           break;
         case 'T': // OutVisStep
-          Log() << Verbose(0) << "Old: " << config::OutVisStep << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::OutVisStep << "\t new: ");
           cin >> config::OutVisStep;
           break;
         case 'U': // OutSrcStep
-          Log() << Verbose(0) << "Old: " << config::OutSrcStep << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::OutSrcStep << "\t new: ");
           cin >> config::OutSrcStep;
           break;
         case 'X': // MaxPsiStep
-          Log() << Verbose(0) << "Old: " << config::MaxPsiStep << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxPsiStep << "\t new: ");
           cin >> config::MaxPsiStep;
           break;
         case 'Y': // EpsWannier
-          Log() << Verbose(0) << "Old: " << config::EpsWannier << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::EpsWannier << "\t new: ");
           cin >> config::EpsWannier;
           break;
 
         case 'Z': // MaxMinStep
-          Log() << Verbose(0) << "Old: " << config::MaxMinStep << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxMinStep << "\t new: ");
           cin >> config::MaxMinStep;
           break;
         case 'a': // RelEpsTotalEnergy
-          Log() << Verbose(0) << "Old: " << config::RelEpsTotalEnergy << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RelEpsTotalEnergy << "\t new: ");
           cin >> config::RelEpsTotalEnergy;
           break;
         case 'b': // RelEpsKineticEnergy
-          Log() << Verbose(0) << "Old: " << config::RelEpsKineticEnergy << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RelEpsKineticEnergy << "\t new: ");
           cin >> config::RelEpsKineticEnergy;
           break;
         case 'c': // MaxMinStopStep
-          Log() << Verbose(0) << "Old: " << config::MaxMinStopStep << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxMinStopStep << "\t new: ");
           cin >> config::MaxMinStopStep;
           break;
         case 'e': // MaxInitMinStep
-          Log() << Verbose(0) << "Old: " << config::MaxInitMinStep << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxInitMinStep << "\t new: ");
           cin >> config::MaxInitMinStep;
           break;
         case 'f': // InitRelEpsTotalEnergy
-          Log() << Verbose(0) << "Old: " << config::InitRelEpsTotalEnergy << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::InitRelEpsTotalEnergy << "\t new: ");
           cin >> config::InitRelEpsTotalEnergy;
           break;
         case 'g': // InitRelEpsKineticEnergy
-          Log() << Verbose(0) << "Old: " << config::InitRelEpsKineticEnergy << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::InitRelEpsKineticEnergy << "\t new: ");
           cin >> config::InitRelEpsKineticEnergy;
           break;
         case 'h': // InitMaxMinStopStep
-          Log() << Verbose(0) << "Old: " << config::InitMaxMinStopStep << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::InitMaxMinStopStep << "\t new: ");
           cin >> config::InitMaxMinStopStep;
           break;
@@ -499,73 +501,74 @@
 //        case 'j': // BoxLength
 //          Log() << Verbose(0) << "enter lower triadiagonalo form of basis matrix" << endl << endl;
+//          double * const cell_size = World::getInstance().getDomain();
 //          for (int i=0;i<6;i++) {
 //            Log() << Verbose(0) << "Cell size" << i << ": ";
-//            cin >> mol->cell_size[i];
+//            cin >> cell_size[i];
 //          }
 //          break;
 
         case 'k': // ECut
-          Log() << Verbose(0) << "Old: " << config::ECut << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::ECut << "\t new: ");
           cin >> config::ECut;
           break;
         case 'l': // MaxLevel
-          Log() << Verbose(0) << "Old: " << config::MaxLevel << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxLevel << "\t new: ");
           cin >> config::MaxLevel;
           break;
         case 'm': // RiemannTensor
-          Log() << Verbose(0) << "Old: " << config::RiemannTensor << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RiemannTensor << "\t new: ");
           cin >> config::RiemannTensor;
           break;
         case 'n': // LevRFactor
-          Log() << Verbose(0) << "Old: " << config::LevRFactor << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::LevRFactor << "\t new: ");
           cin >> config::LevRFactor;
           break;
         case 'o': // RiemannLevel
-          Log() << Verbose(0) << "Old: " << config::RiemannLevel << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RiemannLevel << "\t new: ");
           cin >> config::RiemannLevel;
           break;
         case 'p': // Lev0Factor
-          Log() << Verbose(0) << "Old: " << config::Lev0Factor << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::Lev0Factor << "\t new: ");
           cin >> config::Lev0Factor;
           break;
         case 'r': // RTActualUse
-          Log() << Verbose(0) << "Old: " << config::RTActualUse << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RTActualUse << "\t new: ");
           cin >> config::RTActualUse;
           break;
         case 's': // PsiType
-          Log() << Verbose(0) << "Old: " << config::PsiType << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::PsiType << "\t new: ");
           cin >> config::PsiType;
           break;
         case 't': // MaxPsiDouble
-          Log() << Verbose(0) << "Old: " << config::MaxPsiDouble << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxPsiDouble << "\t new: ");
           cin >> config::MaxPsiDouble;
           break;
         case 'u': // PsiMaxNoUp
-          Log() << Verbose(0) << "Old: " << config::PsiMaxNoUp << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::PsiMaxNoUp << "\t new: ");
           cin >> config::PsiMaxNoUp;
           break;
         case 'v': // PsiMaxNoDown
-          Log() << Verbose(0) << "Old: " << config::PsiMaxNoDown << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::PsiMaxNoDown << "\t new: ");
           cin >> config::PsiMaxNoDown;
           break;
         case 'w': // AddPsis
-          Log() << Verbose(0) << "Old: " << config::AddPsis << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::AddPsis << "\t new: ");
           cin >> config::AddPsis;
           break;
 
         case 'x': // RCut
-          Log() << Verbose(0) << "Old: " << config::RCut << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RCut << "\t new: ");
           cin >> config::RCut;
           break;
         case 'y': // StructOpt
-          Log() << Verbose(0) << "Old: " << config::StructOpt << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::StructOpt << "\t new: ");
           cin >> config::StructOpt;
           break;
         case 'z': // IsAngstroem
-          Log() << Verbose(0) << "Old: " << config::IsAngstroem << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::IsAngstroem << "\t new: ");
           cin >> config::IsAngstroem;
           break;
         case 'i': // RelativeCoord
-          Log() << Verbose(0) << "Old: " << config::RelativeCoord << "\t new: ";
+          DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RelativeCoord << "\t new: ");
           cin >> config::RelativeCoord;
           break;
@@ -646,5 +649,5 @@
   }
   strcpy(configname, ptr);
-  Log() << Verbose(0) << "Found configpath: " << configpath << ", dir slash was found at " << last << ", config name is " << configname << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Found configpath: " << configpath << ", dir slash was found at " << last << ", config name is " << configname << "." << endl);
   delete[](buffer);
 };
@@ -657,5 +660,5 @@
 {
   if (FileBuffer != NULL) {
-    eLog() << Verbose(2) << "deleting present FileBuffer in PrepareFileBuffer()." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "deleting present FileBuffer in PrepareFileBuffer()." << endl);
     delete(FileBuffer);
   }
@@ -674,5 +677,5 @@
 {
   int MaxTypes = 0;
-  element *elementhash[MAX_ELEMENTS];
+  const element *elementhash[MAX_ELEMENTS];
   char name[MAX_ELEMENTS];
   char keyword[MAX_ELEMENTS];
@@ -683,5 +686,5 @@
 
   if (mol == NULL) {
-    eLog() << Verbose(0) << "Molecule is not allocated in LoadMolecule(), exit.";
+    DoeLog(0) && (eLog()<< Verbose(0) << "Molecule is not allocated in LoadMolecule(), exit.");
     performCriticalExit();
   }
@@ -689,9 +692,9 @@
   ParseForParameter(verbose,FileBuffer,"MaxTypes", 0, 1, 1, int_type, &(MaxTypes), 1, critical);
   if (MaxTypes == 0) {
-    eLog() << Verbose(0) << "There are no atoms according to MaxTypes in this config file." << endl;
-    performCriticalExit();
+    DoeLog(1) && (eLog()<< Verbose(1) << "There are no atoms according to MaxTypes in this config file." << endl);
+    //performCriticalExit();
   } else {
     // prescan number of ions per type
-    Log() << Verbose(0) << "Prescanning ions per type: " << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Prescanning ions per type: " << endl);
     int NoAtoms = 0;
     for (int i=0; i < MaxTypes; i++) {
@@ -700,5 +703,5 @@
       ParseForParameter(verbose,FileBuffer, name, 0, 2, 1, int_type, &Z, 1, critical);
       elementhash[i] = periode->FindElement(Z);
-      Log() << Verbose(1) << i << ". Z = " << elementhash[i]->Z << " with " << No[i] << " ions." << endl;
+      DoLog(1) && (Log() << Verbose(1) << i << ". Z = " << elementhash[i]->Z << " with " << No[i] << " ions." << endl);
       NoAtoms += No[i];
     }
@@ -708,5 +711,5 @@
     sprintf(name,"Ion_Type%i",MaxTypes);
     if (!ParseForParameter(verbose,FileBuffer, (const char*)name, 1, 1, 1, int_type, &value[0], 1, critical)) {
-      eLog() << Verbose(0) << "There are no atoms in the config file!" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "There are no atoms in the config file!" << endl);
       performCriticalExit();
       return;
@@ -726,5 +729,5 @@
       bool status = true;
       while (status) {
-        Log() << Verbose(0) << "Currently parsing MD step " << repetition << "." << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Currently parsing MD step " << repetition << "." << endl);
         for (int i=0; i < MaxTypes; i++) {
           sprintf(name,"Ion_Type%i",i+1);
@@ -732,5 +735,5 @@
             sprintf(keyword,"%s_%i",name, j+1);
             if (repetition == 0) {
-              neues = new atom();
+              neues = World::getInstance().createAtom();
               AtomList[i][j] = neues;
               LinearList[ FileBuffer->LineMapping[FileBuffer->CurrentLine] ] = neues;
@@ -739,7 +742,7 @@
               neues = AtomList[i][j];
             status = (status &&
-                    ParseForParameter(verbose,FileBuffer, keyword, 0, 1, 1, double_type, &neues->x.x[0], 1, (repetition == 0) ? critical : optional) &&
-                    ParseForParameter(verbose,FileBuffer, keyword, 0, 2, 1, double_type, &neues->x.x[1], 1, (repetition == 0) ? critical : optional) &&
-                    ParseForParameter(verbose,FileBuffer, keyword, 0, 3, 1, double_type, &neues->x.x[2], 1, (repetition == 0) ? critical : optional) &&
+                    ParseForParameter(verbose,FileBuffer, keyword, 0, 1, 1, double_type, &neues->x[0], 1, (repetition == 0) ? critical : optional) &&
+                    ParseForParameter(verbose,FileBuffer, keyword, 0, 2, 1, double_type, &neues->x[1], 1, (repetition == 0) ? critical : optional) &&
+                    ParseForParameter(verbose,FileBuffer, keyword, 0, 3, 1, double_type, &neues->x[2], 1, (repetition == 0) ? critical : optional) &&
                     ParseForParameter(verbose,FileBuffer, keyword, 0, 4, 1, int_type, &neues->FixedIon, 1, (repetition == 0) ? critical : optional));
             if (!status) break;
@@ -755,15 +758,15 @@
             // put into trajectories list
             for (int d=0;d<NDIM;d++)
-              neues->Trajectory.R.at(repetition).x[d] = neues->x.x[d];
+              neues->Trajectory.R.at(repetition)[d] = neues->x[d];
 
             // parse velocities if present
-            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 5, 1, double_type, &neues->v.x[0], 1,optional))
-              neues->v.x[0] = 0.;
-            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 6, 1, double_type, &neues->v.x[1], 1,optional))
-              neues->v.x[1] = 0.;
-            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 7, 1, double_type, &neues->v.x[2], 1,optional))
-              neues->v.x[2] = 0.;
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 5, 1, double_type, &neues->v[0], 1,optional))
+              neues->v[0] = 0.;
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 6, 1, double_type, &neues->v[1], 1,optional))
+              neues->v[1] = 0.;
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 7, 1, double_type, &neues->v[2], 1,optional))
+              neues->v[2] = 0.;
             for (int d=0;d<NDIM;d++)
-              neues->Trajectory.U.at(repetition).x[d] = neues->v.x[d];
+              neues->Trajectory.U.at(repetition)[d] = neues->v[d];
 
             // parse forces if present
@@ -775,5 +778,5 @@
               value[2] = 0.;
             for (int d=0;d<NDIM;d++)
-              neues->Trajectory.F.at(repetition).x[d] = value[d];
+              neues->Trajectory.F.at(repetition)[d] = value[d];
 
   //            Log() << Verbose(0) << "Parsed position of step " << (repetition) << ": (";
@@ -792,5 +795,5 @@
       }
       repetition--;
-      Log() << Verbose(0) << "Found " << repetition << " trajectory steps." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Found " << repetition << " trajectory steps." << endl);
       if (repetition <= 1)  // if onyl one step, desactivate use of trajectories
         mol->MDSteps = 0;
@@ -804,5 +807,5 @@
               ParseForParameter(verbose,FileBuffer, "Ion_Type1_1", 0, 3, 1, double_type, &value[2], repetition, (repetition == 0) ? critical : optional))
         repetition++;
-      Log() << Verbose(0) << "I found " << repetition << " times the keyword Ion_Type1_1." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "I found " << repetition << " times the keyword Ion_Type1_1." << endl);
       // parse in molecule coordinates
       for (int i=0; i < MaxTypes; i++) {
@@ -811,5 +814,5 @@
           sprintf(keyword,"%s_%i",name, j+1);
           if (repetition == 0) {
-            neues = new atom();
+            neues = World::getInstance().createAtom();
             AtomList[i][j] = neues;
             LinearList[ FileBuffer->LineMapping[FileBuffer->CurrentLine] ] = neues;
@@ -818,14 +821,14 @@
             neues = AtomList[i][j];
           // then parse for each atom the coordinates as often as present
-          ParseForParameter(verbose,FileBuffer, keyword, 0, 1, 1, double_type, &neues->x.x[0], repetition,critical);
-          ParseForParameter(verbose,FileBuffer, keyword, 0, 2, 1, double_type, &neues->x.x[1], repetition,critical);
-          ParseForParameter(verbose,FileBuffer, keyword, 0, 3, 1, double_type, &neues->x.x[2], repetition,critical);
+          ParseForParameter(verbose,FileBuffer, keyword, 0, 1, 1, double_type, &neues->x[0], repetition,critical);
+          ParseForParameter(verbose,FileBuffer, keyword, 0, 2, 1, double_type, &neues->x[1], repetition,critical);
+          ParseForParameter(verbose,FileBuffer, keyword, 0, 3, 1, double_type, &neues->x[2], repetition,critical);
           ParseForParameter(verbose,FileBuffer, keyword, 0, 4, 1, int_type, &neues->FixedIon, repetition,critical);
-          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 5, 1, double_type, &neues->v.x[0], repetition,optional))
-            neues->v.x[0] = 0.;
-          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 6, 1, double_type, &neues->v.x[1], repetition,optional))
-            neues->v.x[1] = 0.;
-          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 7, 1, double_type, &neues->v.x[2], repetition,optional))
-            neues->v.x[2] = 0.;
+          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 5, 1, double_type, &neues->v[0], repetition,optional))
+            neues->v[0] = 0.;
+          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 6, 1, double_type, &neues->v[1], repetition,optional))
+            neues->v[1] = 0.;
+          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 7, 1, double_type, &neues->v[2], repetition,optional))
+            neues->v[2] = 0.;
           // here we don't care if forces are present (last in trajectories is always equal to current position)
           neues->type = elementhash[i]; // find element type
@@ -850,8 +853,8 @@
 void config::Load(const char * const filename, const string &BondGraphFileName, const periodentafel * const periode, MoleculeListClass * const &MolList)
 {
-  molecule *mol = new molecule(periode);
+  molecule *mol = World::getInstance().createMolecule();
   ifstream *file = new ifstream(filename);
   if (file == NULL) {
-    eLog() << Verbose(1) << "config file " << filename << " missing!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "config file " << filename << " missing!" << endl);
     return;
   }
@@ -965,10 +968,11 @@
   // Unit cell and magnetic field
   ParseForParameter(verbose,FileBuffer, "BoxLength", 0, 3, 3, lower_trigrid, BoxLength, 1, critical); /* Lattice->RealBasis */
-  mol->cell_size[0] = BoxLength[0];
-  mol->cell_size[1] = BoxLength[3];
-  mol->cell_size[2] = BoxLength[4];
-  mol->cell_size[3] = BoxLength[6];
-  mol->cell_size[4] = BoxLength[7];
-  mol->cell_size[5] = BoxLength[8];
+  double * const cell_size = World::getInstance().getDomain();
+  cell_size[0] = BoxLength[0];
+  cell_size[1] = BoxLength[3];
+  cell_size[2] = BoxLength[4];
+  cell_size[3] = BoxLength[6];
+  cell_size[4] = BoxLength[7];
+  cell_size[5] = BoxLength[8];
   //if (1) fprintf(stderr,"\n");
 
@@ -1060,7 +1064,7 @@
     BG = new BondGraph(IsAngstroem);
     if (BG->LoadBondLengthTable(BondGraphFileName)) {
-      Log() << Verbose(0) << "Bond length table loaded successfully." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Bond length table loaded successfully." << endl);
     } else {
-      eLog() << Verbose(1) << "Bond length table loading failed." << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << "Bond length table loading failed." << endl);
     }
   }
@@ -1088,8 +1092,8 @@
 void config::LoadOld(const char * const filename, const string &BondGraphFileName, const periodentafel * const periode, MoleculeListClass * const &MolList)
 {
-  molecule *mol = new molecule(periode);
+  molecule *mol = World::getInstance().createMolecule();
   ifstream *file = new ifstream(filename);
   if (file == NULL) {
-    eLog() << Verbose(1) << "config file " << filename << " missing!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "config file " << filename << " missing!" << endl);
     return;
   }
@@ -1106,5 +1110,5 @@
   string zeile;
   string dummy;
-  element *elementhash[128];
+  const element *elementhash[128];
   int Z = -1;
   int No = -1;
@@ -1169,10 +1173,11 @@
 
   ParseForParameter(verbose,file, "BoxLength", 0, 3, 3, lower_trigrid, BoxLength, 1, critical); /* Lattice->RealBasis */
-  mol->cell_size[0] = BoxLength[0];
-  mol->cell_size[1] = BoxLength[3];
-  mol->cell_size[2] = BoxLength[4];
-  mol->cell_size[3] = BoxLength[6];
-  mol->cell_size[4] = BoxLength[7];
-  mol->cell_size[5] = BoxLength[8];
+  double * const cell_size = World::getInstance().getDomain();
+  cell_size[0] = BoxLength[0];
+  cell_size[1] = BoxLength[3];
+  cell_size[2] = BoxLength[4];
+  cell_size[3] = BoxLength[6];
+  cell_size[4] = BoxLength[7];
+  cell_size[5] = BoxLength[8];
   if (1) fprintf(stderr,"\n");
   config::DoPerturbation = 0;
@@ -1250,7 +1255,7 @@
   BG = new BondGraph(IsAngstroem);
   if (BG->LoadBondLengthTable(BondGraphFileName)) {
-    Log() << Verbose(0) << "Bond length table loaded successfully." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Bond length table loaded successfully." << endl);
   } else {
-    Log() << Verbose(0) << "Bond length table loading failed." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Bond length table loading failed." << endl);
   }
 
@@ -1259,10 +1264,10 @@
   for (i=MAX_ELEMENTS;i--;)
     elementhash[i] = NULL;
-  Log() << Verbose(0) << "Parsing Ions ..." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Parsing Ions ..." << endl);
   No=0;
   found = 0;
   while (getline(*file,zeile,'\n')) {
     if (zeile.find("Ions_Data") == 0) {
-      Log() << Verbose(1) << "found Ions_Data...begin parsing" << endl;
+      DoLog(1) && (Log() << Verbose(1) << "found Ions_Data...begin parsing" << endl);
       found ++;
     }
@@ -1278,8 +1283,8 @@
       input >> b;     // element mass
       elementhash[No] = periode->FindElement(Z);
-      Log() << Verbose(1) << "AtomNo: " << AtomNo << "\tZ: " << Z << "\ta:" << a << "\tl:"  << l << "\b:" << b << "\tElement:" << elementhash[No] << "\t:" << endl;
+      DoLog(1) && (Log() << Verbose(1) << "AtomNo: " << AtomNo << "\tZ: " << Z << "\ta:" << a << "\tl:"  << l << "\b:" << b << "\tElement:" << elementhash[No] << "\t:" << endl);
       for(i=0;i<AtomNo;i++) {
         if (!getline(*file,zeile,'\n')) {// parse on and on
-          Log() << Verbose(2) << "Error: Too few items in ionic list of element" << elementhash[No] << "." << endl << "Exiting." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "Error: Too few items in ionic list of element" << elementhash[No] << "." << endl << "Exiting." << endl);
           // return 1;
         } else {
@@ -1287,8 +1292,8 @@
         }
         istringstream input2(zeile);
-        atom *neues = new atom();
-        input2 >> neues->x.x[0]; // x
-        input2 >> neues->x.x[1]; // y
-        input2 >> neues->x.x[2]; // z
+        atom *neues = World::getInstance().createAtom();
+        input2 >> neues->x[0]; // x
+        input2 >> neues->x[1]; // y
+        input2 >> neues->x[2]; // z
         input2 >> l;
         neues->type = elementhash[No]; // find element type
@@ -1312,4 +1317,5 @@
   // bring MaxTypes up to date
   mol->CountElements();
+  const double * const cell_size = World::getInstance().getDomain();
   ofstream * const output = new ofstream(filename, ios::out);
   if (output != NULL) {
@@ -1382,7 +1388,7 @@
     *output << endl;
     *output << "BoxLength\t\t\t# (Length of a unit cell)" << endl;
-    *output << mol->cell_size[0] << "\t" << endl;
-    *output << mol->cell_size[1] << "\t" << mol->cell_size[2] << "\t" << endl;
-    *output << mol->cell_size[3] << "\t" << mol->cell_size[4] << "\t" << mol->cell_size[5] << "\t" << endl;
+    *output << cell_size[0] << "\t" << endl;
+    *output << cell_size[1] << "\t" << cell_size[2] << "\t" << endl;
+    *output << cell_size[3] << "\t" << cell_size[4] << "\t" << cell_size[5] << "\t" << endl;
     // FIXME
     *output << endl;
@@ -1428,5 +1434,5 @@
     return result;
   } else {
-    eLog() << Verbose(1) << "Cannot open output file:" << filename << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open output file:" << filename << endl);
     return false;
   }
@@ -1450,5 +1456,5 @@
     output = new ofstream(fname->str().c_str(), ios::out);
     if (output == NULL) {
-      eLog() << Verbose(1) << "Cannot open mpqc output file:" << fname << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open mpqc output file:" << fname << endl);
       delete(fname);
       return false;
@@ -1493,5 +1499,5 @@
     output = new ofstream(fname->str().c_str(), ios::out);
     if (output == NULL) {
-      eLog() << Verbose(1) << "Cannot open mpqc hessian output file:" << fname << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open mpqc hessian output file:" << fname << endl);
       delete(fname);
       return false;
@@ -1549,5 +1555,5 @@
   f = fopen(name, "w" );
   if (f == NULL) {
-    eLog() << Verbose(1) << "Cannot open pdb output file:" << name << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open pdb output file:" << name << endl);
     return false;
   }
@@ -1569,7 +1575,7 @@
              'a'+(unsigned char)(AtomNo % 26),           /* letter for chain */
              MolNo,         /* residue sequence number */
-             Walker->node->x[0],                 /* position X in Angstroem */
-             Walker->node->x[1],                 /* position Y in Angstroem */
-             Walker->node->x[2],                 /* position Z in Angstroem */
+             Walker->node->at(0),                 /* position X in Angstroem */
+             Walker->node->at(1),                 /* position Y in Angstroem */
+             Walker->node->at(2),                 /* position Z in Angstroem */
              (double)Walker->type->Valence,         /* occupancy */
              (double)Walker->type->NoValenceOrbitals,          /* temperature factor */
@@ -1604,5 +1610,5 @@
   f = fopen(name, "w" );
   if (f == NULL) {
-    eLog() << Verbose(1) << "Cannot open pdb output file:" << name << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open pdb output file:" << name << endl);
     Free(&elementNo);
     return false;
@@ -1623,7 +1629,7 @@
            'a'+(unsigned char)(AtomNo % 26),           /* letter for chain */
            0,         /* residue sequence number */
-           Walker->node->x[0],                 /* position X in Angstroem */
-           Walker->node->x[1],                 /* position Y in Angstroem */
-           Walker->node->x[2],                 /* position Z in Angstroem */
+           Walker->node->at(0),                 /* position X in Angstroem */
+           Walker->node->at(1),                 /* position Y in Angstroem */
+           Walker->node->at(2),                 /* position Z in Angstroem */
            (double)Walker->type->Valence,         /* occupancy */
            (double)Walker->type->NoValenceOrbitals,          /* temperature factor */
@@ -1641,4 +1647,5 @@
 /** Stores all atoms in a TREMOLO data input file.
  * Note that this format cannot be parsed again.
+ * Note that TREMOLO does not like Id starting at 0, but at 1. Atoms with Id 0 are discarded!
  * \param *filename name of file (without ".in" suffix!)
  * \param *mol pointer to molecule
@@ -1653,5 +1660,5 @@
   output = new ofstream(fname->str().c_str(), ios::out);
   if (output == NULL) {
-    eLog() << Verbose(1) << "Cannot open tremolo output file:" << fname << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open tremolo output file:" << fname << endl);
     delete(fname);
     return false;
@@ -1676,6 +1683,6 @@
     *output << mol->name << "\t";
     *output << 0 << "\t";
-    *output << Walker->node->x[0] << "\t" << Walker->node->x[1] << "\t" << Walker->node->x[2] << "\t";
-    *output << (double)Walker->type->Valence << "\t";
+    *output << Walker->node->at(0) << "\t" << Walker->node->at(1) << "\t" << Walker->node->at(2) << "\t";
+    *output << static_cast<double>(Walker->type->Valence) << "\t";
     *output << Walker->type->symbol << "\t";
     for (BondList::iterator runner = Walker->ListOfBonds.begin(); runner != Walker->ListOfBonds.end(); runner++)
@@ -1695,4 +1702,5 @@
 /** Stores all atoms from all molecules in a TREMOLO data input file.
  * Note that this format cannot be parsed again.
+ * Note that TREMOLO does not like Id starting at 0, but at 1. Atoms with Id 0 are discarded!
  * \param *filename name of file (without ".in" suffix!)
  * \param *MolList pointer to MoleculeListClass containing all atoms
@@ -1707,5 +1715,5 @@
   output = new ofstream(fname->str().c_str(), ios::out);
   if (output == NULL) {
-    eLog() << Verbose(1) << "Cannot open tremolo output file:" << fname << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open tremolo output file:" << fname << endl);
     delete(fname);
     return false;
@@ -1747,13 +1755,13 @@
       while (Walker->next != (*MolWalker)->end) {
         Walker = Walker->next;
-        *output << AtomNo << "\t";
+        *output << AtomNo+1 << "\t";
         *output << Walker->Name << "\t";
         *output << (*MolWalker)->name << "\t";
-        *output << MolCounter << "\t";
-        *output << Walker->node->x[0] << "\t" << Walker->node->x[1] << "\t" << Walker->node->x[2] << "\t";
+        *output << MolCounter+1 << "\t";
+        *output << Walker->node->at(0) << "\t" << Walker->node->at(1) << "\t" << Walker->node->at(2) << "\t";
         *output << (double)Walker->type->Valence << "\t";
         *output << Walker->type->symbol << "\t";
         for (BondList::iterator runner = Walker->ListOfBonds.begin(); runner != Walker->ListOfBonds.end(); runner++)
-          *output << LocalNotoGlobalNoMap[MolCounter][ (*runner)->GetOtherAtom(Walker)->nr ] << "\t";
+          *output << LocalNotoGlobalNoMap[MolCounter][ (*runner)->GetOtherAtom(Walker)->nr ]+1 << "\t";
         for(int i=Walker->ListOfBonds.size(); i < MaxNeighbours; i++)
           *output << "-\t";
@@ -1787,5 +1795,5 @@
   char filename[MAXSTRINGSIZE];
   ofstream output;
-  molecule *mol = new molecule(periode);
+  molecule *mol = World::getInstance().createMolecule();
   mol->SetNameFromFilename(ConfigFileName);
 
@@ -1898,5 +1906,5 @@
   }
 
-  delete(mol);
+  World::getInstance().destroyMolecule(mol);
 };
 
Index: src/datacreator.cpp
===================================================================
--- src/datacreator.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/datacreator.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -25,5 +25,5 @@
   output.open(name.str().c_str(), ios::out);
   if (output == NULL) {
-    Log() << Verbose(0) << "Unable to open " << name.str() << " for writing, is directory correct?" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Unable to open " << name.str() << " for writing, is directory correct?" << endl);
     return false;
   }
@@ -43,5 +43,5 @@
   output.open(name.str().c_str(), ios::app);
   if (output == NULL) {
-    Log() << Verbose(0) << "Unable to open " << name.str() << " for writing, is directory correct?" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Unable to open " << name.str() << " for writing, is directory correct?" << endl);
     return false;
   }
@@ -63,5 +63,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "#Order\tFrag.No.\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
@@ -96,5 +96,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "#Order\tFrag.No.\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
@@ -133,5 +133,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "# Order\tFrag.No.\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
@@ -165,5 +165,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "# Order\tFrag.No.\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
@@ -198,5 +198,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "# AtomNo\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
@@ -244,5 +244,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "# AtomNo\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
@@ -281,5 +281,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "# AtomNo\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
@@ -321,5 +321,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "# AtomNo\t";
@@ -363,5 +363,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "# AtomNo\t" << Fragments.Header[ Fragments.MatrixCounter ] << endl;
@@ -393,5 +393,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum << endl;
   output << "#Order\tFrag.No.\t" << Fragment.Header[ Fragment.MatrixCounter ] << endl;
@@ -458,5 +458,5 @@
   filename << prefix << ".dat";
   if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-  Log() << Verbose(0) << msg << endl;
+  DoLog(0) && (Log() << Verbose(0) << msg << endl);
   output << "# " << msg << ", created on " << datum;
   output << "#Order\tFrag.No.\t" << Fragment.Header[ Fragment.MatrixCounter ] << endl;
@@ -771,5 +771,5 @@
 {
   stringstream line(Force.Header[Force.MatrixCounter]);
-  char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
+  const char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
   string token;
 
@@ -803,5 +803,5 @@
 {
   stringstream line(Force.Header[Force.MatrixCounter]);
-  char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
+  const char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
   string token;
 
Index: src/defs.hpp
===================================================================
--- src/defs.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/defs.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -12,5 +12,4 @@
 #define MAX_ELEMENTS 128  //!< maximum number of elements for certain lookup tables 
 #define AtomicLengthToAngstroem  0.52917721 //!< conversion factor from atomic length/bohrradius to angstroem
-#define BONDTHRESHOLD 0.5   //!< CSD threshold in bond check which is the width of the interval whose center is the sum of the covalent radii 
 #define AtomicEnergyToKelvin 315774.67  //!< conversion factor from atomic energy to kelvin via boltzmann factor
 #define KelvinToAtomicTemperature 3.1668152e-06    //!< conversion factor for Kelvin to atomic temperature (Hartree over k_B)
@@ -32,4 +31,6 @@
 
 enum Shading { white, lightgray, darkgray, black };  //!< color in Breadth-First-Search analysis
+
+
 
 //enum CutCyclicBond { KeepBond,  SaturateBond }; //!< Saturation scheme either atom- or bondwise 
Index: src/element.cpp
===================================================================
--- src/element.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/element.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,14 +10,22 @@
 #include "element.hpp"
 
+using namespace std;
+
 /************************************* Functions for class element **********************************/
 
 /** Constructor of class element.
  */
-element::element() {
-  Z = -1;
-  No = -1;
-  previous = NULL;
-  next = NULL;
-  sort = NULL;
+element::element() :
+  mass(0),
+  CovalentRadius(0),
+  VanDerWaalsRadius(0),
+	Z(-1),
+	previous(NULL),
+	next(NULL),
+	sort(NULL),
+	No(-1),
+	Valence(0),
+	NoValenceOrbitals(0)
+{
 };
 
@@ -29,5 +37,5 @@
  * \param *out outstream
  */
-bool element::Output(ofstream * const out) const
+bool element::Output(ostream * const out) const
 { 
   if (out != NULL) {
@@ -44,5 +52,5 @@
  * \param NoOfAtoms total number of atom of this element type
  */
-bool element::Checkout(ofstream * const out, const int Number, const int NoOfAtoms) const
+bool element::Checkout(ostream * const out, const int Number, const int NoOfAtoms) const
 { 
   if (out != NULL) {
@@ -52,2 +60,10 @@
     return false;
 };
+
+atomicNumber_t element::getNumber() const{
+  return Z;
+}
+
+string element::getSymbol() const{
+  return string(symbol);
+}
Index: src/element.hpp
===================================================================
--- src/element.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/element.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,6 +9,4 @@
 #define ELEMENT_HPP_
 
-using namespace std;
-
 /*********************************************** includes ***********************************/
 
@@ -19,6 +17,8 @@
 
 #include <iostream>
+#include <string>
 
 #include "defs.hpp"
+#include "types.hpp"
 
 /********************************************** declarations *******************************/
@@ -50,7 +50,11 @@
   ~element();
 
+  // accessor functions
+  atomicNumber_t getNumber() const;
+  std::string getSymbol() const;
+
   //> print element entries to screen
-  bool Output(ofstream * const out) const;
-  bool Checkout(ofstream * const out, const int No, const int NoOfAtoms) const;
+  bool Output(std::ostream * const out) const;
+  bool Checkout(std::ostream * const out, const int No, const int NoOfAtoms) const;
 
   private:
Index: src/ellipsoid.cpp
===================================================================
--- src/ellipsoid.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/ellipsoid.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -42,7 +42,5 @@
 
   // 1. translate coordinate system so that ellipsoid center is in origin
-  helper.CopyVector(&x);
-  helper.SubtractVector(&EllipsoidCenter);
-  RefPoint.CopyVector(&helper);
+  RefPoint = helper = x - EllipsoidCenter;
   //Log() << Verbose(4) << "Translated given point is at " << RefPoint << "." << endl;
 
@@ -61,5 +59,5 @@
   Matrix[8] = cos(theta);
   helper.MatrixMultiplication(Matrix);
-  helper.Scale(InverseLength);
+  helper.ScaleAll(InverseLength);
   //Log() << Verbose(4) << "Transformed RefPoint is at " << helper << "." << endl;
 
@@ -72,5 +70,5 @@
   theta = -EllipsoidAngle[1];
   phi = -EllipsoidAngle[2];
-  helper.Scale(EllipsoidLength);
+  helper.ScaleAll(EllipsoidLength);
   Matrix[0] = cos(psi)*cos(phi) - sin(psi)*cos(theta)*sin(phi);
   Matrix[1] = -cos(psi)*sin(phi) - sin(psi)*cos(theta)*cos(phi);
@@ -86,5 +84,5 @@
 
   // 5. determine distance between backtransformed point and x
-  distance = RefPoint.DistanceSquared(&helper);
+  distance = RefPoint.DistanceSquared(helper);
   //Log() << Verbose(4) << "Squared distance between intersection and RefPoint is " << distance << "." << endl;
 
@@ -116,5 +114,5 @@
   // put parameters into suitable ellipsoid form
   for (int i=0;i<3;i++) {
-    Center.x[i] = gsl_vector_get(x, i+0);
+    Center[i] = gsl_vector_get(x, i+0);
     EllipsoidLength[i] = gsl_vector_get(x, i+3);
     EllipsoidAngle[i] = gsl_vector_get(x, i+6);
@@ -146,5 +144,5 @@
 {
   int status = GSL_SUCCESS;
-  Log() << Verbose(2) << "Begin of FitPointSetToEllipsoid " << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Begin of FitPointSetToEllipsoid " << endl);
   if (N >= 3) { // check that enough points are given (9 d.o.f.)
     struct EllipsoidMinimisation par;
@@ -160,5 +158,5 @@
     x = gsl_vector_alloc (9);
     for (int i=0;i<3;i++) {
-      gsl_vector_set (x, i+0, EllipsoidCenter->x[i]);
+      gsl_vector_set (x, i+0, EllipsoidCenter->at(i));
       gsl_vector_set (x, i+3, EllipsoidLength[i]);
       gsl_vector_set (x, i+6, EllipsoidAngle[i]);
@@ -195,9 +193,9 @@
       if (status == GSL_SUCCESS) {
         for (int i=0;i<3;i++) {
-          EllipsoidCenter->x[i] = gsl_vector_get (s->x,i+0);
+          EllipsoidCenter->at(i) = gsl_vector_get (s->x,i+0);
           EllipsoidLength[i] = gsl_vector_get (s->x, i+3);
           EllipsoidAngle[i] = gsl_vector_get (s->x, i+6);
         }
-        Log() << Verbose(4) << setprecision(3) << "Converged fit at: " << *EllipsoidCenter << ", lengths " << EllipsoidLength[0] << ", " << EllipsoidLength[1] << ", " << EllipsoidLength[2] << ", angles " << EllipsoidAngle[0] << ", " << EllipsoidAngle[1] << ", " << EllipsoidAngle[2] << " with summed distance " << s->fval << "." << endl;
+        DoLog(4) && (Log() << Verbose(4) << setprecision(3) << "Converged fit at: " << *EllipsoidCenter << ", lengths " << EllipsoidLength[0] << ", " << EllipsoidLength[1] << ", " << EllipsoidLength[2] << ", angles " << EllipsoidAngle[0] << ", " << EllipsoidAngle[1] << ", " << EllipsoidAngle[2] << " with summed distance " << s->fval << "." << endl);
       }
 
@@ -209,8 +207,8 @@
 
   } else {
-    Log() << Verbose(3) << "Not enough points provided for fit to ellipsoid." << endl;
+    DoLog(3) && (Log() << Verbose(3) << "Not enough points provided for fit to ellipsoid." << endl);
     return false;
   }
-  Log() << Verbose(2) << "End of FitPointSetToEllipsoid" << endl;
+  DoLog(2) && (Log() << Verbose(2) << "End of FitPointSetToEllipsoid" << endl);
   if (status == GSL_SUCCESS)
     return true;
@@ -235,5 +233,5 @@
   int index;
   TesselPoint *Candidate = NULL;
-  Log() << Verbose(2) << "Begin of PickRandomPointSet" << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Begin of PickRandomPointSet" << endl);
 
   // allocate array
@@ -241,5 +239,5 @@
     x = new Vector[PointsToPick];
   } else {
-    eLog() << Verbose(2) << "Given pointer to vector array seems already allocated." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "Given pointer to vector array seems already allocated." << endl);
   }
 
@@ -247,19 +245,19 @@
     for(int i=0;i<NDIM;i++) // pick three random indices
       LC->n[i] = (rand() % LC->N[i]);
-    Log() << Verbose(2) << "INFO: Center cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " ... ";
+    DoLog(2) && (Log() << Verbose(2) << "INFO: Center cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " ... ");
     // get random cell
-    const LinkedNodes *List = LC->GetCurrentCell();
+    const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
     if (List == NULL) {  // set index to it
       continue;
     }
-    Log() << Verbose(2) << "with No. " << LC->index << "." << endl;
-
-    Log() << Verbose(2) << "LC Intervals:";
+    DoLog(2) && (Log() << Verbose(2) << "with No. " << LC->index << "." << endl);
+
+    DoLog(2) && (Log() << Verbose(2) << "LC Intervals:");
     for (int i=0;i<NDIM;i++) {
       Nlower[i] = ((LC->n[i]-1) >= 0) ? LC->n[i]-1 : 0;
       Nupper[i] = ((LC->n[i]+1) < LC->N[i]) ? LC->n[i]+1 : LC->N[i]-1;
-      Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
-    }
-    Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ");
+    }
+    DoLog(0) && (Log() << Verbose(0) << endl);
 
     // count whether there are sufficient atoms in this cell+neighbors
@@ -268,8 +266,8 @@
       for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
         for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-          const LinkedNodes *List = LC->GetCurrentCell();
+          const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
           PointsLeft += List->size();
         }
-    Log() << Verbose(2) << "There are " << PointsLeft << " atoms in this neighbourhood." << endl;
+    DoLog(2) && (Log() << Verbose(2) << "There are " << PointsLeft << " atoms in this neighbourhood." << endl);
     if (PointsLeft < PointsToPick) {  // ensure that we can pick enough points in its neighbourhood at all.
       continue;
@@ -293,5 +291,5 @@
       for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
         for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-          const LinkedNodes *List = LC->GetCurrentCell();
+          const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
 //          Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << " containing " << List->size() << " points." << endl;
           if (List != NULL) {
@@ -300,9 +298,9 @@
 //            else
 //              Log() << Verbose(2) << "Cell is empty ... " << endl;
-            for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+            for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
               if ((current != PickedAtomNrs.end()) && (*current == index)) {
                 Candidate = (*Runner);
-                Log() << Verbose(2) << "Current picked node is " << **Runner << " with index " << index << "." << endl;
-                x[PointsPicked++].CopyVector(Candidate->node);    // we have one more atom picked
+                DoLog(2) && (Log() << Verbose(2) << "Current picked node is " << **Runner << " with index " << index << "." << endl);
+                x[PointsPicked++] = *Candidate->node;    // we have one more atom picked
                 current++;    // next pre-picked atom
               }
@@ -313,12 +311,12 @@
           }
         }
-    Log() << Verbose(2) << "The following points were picked: " << endl;
+    DoLog(2) && (Log() << Verbose(2) << "The following points were picked: " << endl);
     for (size_t i=0;i<PointsPicked;i++)
-      Log() << Verbose(2) << x[i] << endl;
+      DoLog(2) && (Log() << Verbose(2) << x[i] << endl);
     if (PointsPicked == PointsToPick)  // break out of loop if we have all
       break;
   } while(1);
 
-  Log() << Verbose(2) << "End of PickRandomPointSet" << endl;
+  DoLog(2) && (Log() << Verbose(2) << "End of PickRandomPointSet" << endl);
 };
 
@@ -335,5 +333,5 @@
   double value, threshold;
   PointMap *List = &T->PointsOnBoundary;
-  Log() << Verbose(2) << "Begin of PickRandomPointSet" << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Begin of PickRandomPointSet" << endl);
 
   // allocate array
@@ -341,5 +339,5 @@
     x = new Vector[PointsToPick];
   } else {
-    eLog() << Verbose(2) << "Given pointer to vector array seems already allocated." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "Given pointer to vector array seems already allocated." << endl);
   }
 
@@ -350,5 +348,5 @@
       //Log() << Verbose(3) << "Current node is " << *Runner->second->node << " with " << value << " ... " << threshold << ": ";
       if (value > threshold) {
-        x[PointsPicked].CopyVector(Runner->second->node->node);
+        x[PointsPicked] = (*Runner->second->node->node);
         PointsPicked++;
         //Log() << Verbose(0) << "IN." << endl;
@@ -358,9 +356,9 @@
       PointsLeft--;
     }
-  Log() << Verbose(2) << "The following points were picked: " << endl;
+  DoLog(2) && (Log() << Verbose(2) << "The following points were picked: " << endl);
   for (size_t i=0;i<PointsPicked;i++)
-    Log() << Verbose(3) << x[i] << endl;
-
-  Log() << Verbose(2) << "End of PickRandomPointSet" << endl;
+    DoLog(3) && (Log() << Verbose(3) << x[i] << endl);
+
+  DoLog(2) && (Log() << Verbose(2) << "End of PickRandomPointSet" << endl);
 };
 
@@ -382,12 +380,12 @@
   double EllipsoidAngle[3];
   double distance, MaxDistance, MinDistance;
-  Log() << Verbose(0) << "Begin of FindDistributionOfEllipsoids" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Begin of FindDistributionOfEllipsoids" << endl);
 
   // construct center of gravity of boundary point set for initial ellipsoid center
   Center.Zero();
   for (PointMap::iterator Runner = T->PointsOnBoundary.begin(); Runner != T->PointsOnBoundary.end(); Runner++)
-    Center.AddVector(Runner->second->node->node);
+    Center += (*Runner->second->node->node);
   Center.Scale(1./T->PointsOnBoundaryCount);
-  Log() << Verbose(1) << "Center is at " << Center << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Center is at " << Center << "." << endl);
 
   // Output header
@@ -397,5 +395,5 @@
   // loop over desired number of parameter sets
   for (;number >0;number--) {
-    Log() << Verbose(1) << "Determining data set " << number << " ... " << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Determining data set " << number << " ... " << endl);
     // pick the point set
     x = NULL;
@@ -405,7 +403,7 @@
     // calculate some sensible starting values for parameter fit
     MaxDistance = 0.;
-    MinDistance = x[0].ScalarProduct(&x[0]);
+    MinDistance = x[0].ScalarProduct(x[0]);
     for (int i=0;i<N;i++) {
-      distance = x[i].ScalarProduct(&x[i]);
+      distance = x[i].ScalarProduct(x[i]);
       if (distance > MaxDistance)
         MaxDistance = distance;
@@ -414,5 +412,5 @@
     }
     //Log() << Verbose(2) << "MinDistance " << MinDistance << ", MaxDistance " << MaxDistance << "." << endl;
-    EllipsoidCenter.CopyVector(&Center);  // use Center of Gravity as initial center of ellipsoid
+    EllipsoidCenter = Center;  // use Center of Gravity as initial center of ellipsoid
     for (int i=0;i<3;i++)
       EllipsoidAngle[i] = 0.;
@@ -423,9 +421,9 @@
     // fit the parameters
     if (FitPointSetToEllipsoid(x, N, &EllipsoidCenter, &EllipsoidLength[0], &EllipsoidAngle[0])) {
-      Log() << Verbose(1) << "Picking succeeded!" << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Picking succeeded!" << endl);
       // output obtained parameter set
       output << number << "\t";
       for (int i=0;i<3;i++)
-        output << setprecision(9) << EllipsoidCenter.x[i] << "\t";
+        output << setprecision(9) << EllipsoidCenter[i] << "\t";
       for (int i=0;i<3;i++)
         output << setprecision(9) << EllipsoidLength[i] << "\t";
@@ -434,5 +432,5 @@
       output << endl;
     } else { // increase N to pick one more
-      Log() << Verbose(1) << "Picking failed!" << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Picking failed!" << endl);
       number++;
     }
@@ -442,4 +440,4 @@
   output.close();
 
-  Log() << Verbose(0) << "End of FindDistributionOfEllipsoids" << endl;
-};
+  DoLog(0) && (Log() << Verbose(0) << "End of FindDistributionOfEllipsoids" << endl);
+};
Index: src/errorlogger.cpp
===================================================================
--- src/errorlogger.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/errorlogger.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,8 +9,7 @@
 #include "errorlogger.hpp"
 #include "verbose.hpp"
+#include "Patterns/Singleton_impl.hpp"
 
 ofstream null("/dev/null");
-
-errorLogger* errorLogger::instance = NULL;
 int errorLogger::verbosity = 2;
 ostream* errorLogger::nix = &null;
@@ -23,5 +22,4 @@
 errorLogger::errorLogger()
 {
-  instance = NULL;
   verbosity = 2;
 };
@@ -34,28 +32,5 @@
 }
 
-/**
- * Returns the singleton errorLogger instance.
- *
- * \return errorLogger instance
- */
-errorLogger* errorLogger::getInstance() {
-  if (instance == NULL) {
-    instance = new errorLogger();
-  }
-
-  return instance;
-}
-
-
-/**
- * Purges the current errorLogger instance.
- */
-void errorLogger::purgeInstance() {
-  if (instance != NULL) {
-    delete instance;
-  }
-
-  instance = NULL;
-}
+CONSTRUCT_SINGLETON(errorLogger)
 
 /**
@@ -81,5 +56,5 @@
   int verbosityLevel = l.verbosity;
   l.nix->clear();
-  if (v.DoOutput(verbosityLevel)) {
+  if (v.DoErrorOutput(verbosityLevel)) {
     switch(v.Verbosity) {
       case 0:
@@ -104,5 +79,5 @@
   int verbosityLevel = l->verbosity;
   l->nix->clear();
-  if (v.DoOutput(verbosityLevel)) {
+  if (v.DoErrorOutput(verbosityLevel)) {
     switch(v.Verbosity) {
       case 0:
@@ -113,7 +88,6 @@
         break;
       case 2:
+      default:
         cerr << "WARNING: ";
-        break;
-      default:
         break;
     }
Index: src/errorlogger.hpp
===================================================================
--- src/errorlogger.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/errorlogger.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -11,15 +11,16 @@
 #include <iostream>
 
+#include "Patterns/Singleton.hpp"
+
 using namespace std;
 
 class Verbose;
 
-class errorLogger {
+class errorLogger : public Singleton<errorLogger>{
+  friend class Singleton<errorLogger>;
 public :
   static ostream *nix;
   static int verbosity;
 
-  static errorLogger* getInstance();
-  static void purgeInstance();
   static bool DoOutput();
   static void setVerbosity(int verbosityLevel);
@@ -31,6 +32,4 @@
   ~errorLogger();
 
-private:
-  static errorLogger* instance;
 };
 
Index: src/graph.cpp
===================================================================
--- src/graph.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/graph.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -85,10 +85,10 @@
   testGraphInsert = Fragment->Leaflet->insert(GraphPair (*Fragment->FragmentSet,pair<int,double>(Fragment->FragmentCounter,Fragment->TEFactor)));  // store fragment number and current factor
   if (testGraphInsert.second) {
-    Log() << Verbose(2) << "KeySet " << Fragment->FragmentCounter << " successfully inserted." << endl;
+    DoLog(2) && (Log() << Verbose(2) << "KeySet " << Fragment->FragmentCounter << " successfully inserted." << endl);
     Fragment->FragmentCounter++;
   } else {
-    Log() << Verbose(2) << "KeySet " << Fragment->FragmentCounter << " failed to insert, present fragment is " << ((*(testGraphInsert.first)).second).first << endl;
+    DoLog(2) && (Log() << Verbose(2) << "KeySet " << Fragment->FragmentCounter << " failed to insert, present fragment is " << ((*(testGraphInsert.first)).second).first << endl);
     ((*(testGraphInsert.first)).second).second += Fragment->TEFactor;  // increase the "created" counter
-    Log() << Verbose(2) << "New factor is " << ((*(testGraphInsert.first)).second).second << "." << endl;
+    DoLog(2) && (Log() << Verbose(2) << "New factor is " << ((*(testGraphInsert.first)).second).second << "." << endl);
   }
 };
@@ -115,9 +115,9 @@
     testGraphInsert = graph1.insert(GraphPair ((*runner).first,pair<int,double>((*counter)++,((*runner).second).second)));  // store fragment number and current factor
     if (testGraphInsert.second) {
-      Log() << Verbose(2) << "KeySet " << (*counter)-1 << " successfully inserted." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "KeySet " << (*counter)-1 << " successfully inserted." << endl);
     } else {
-      Log() << Verbose(2) << "KeySet " << (*counter)-1 << " failed to insert, present fragment is " << ((*(testGraphInsert.first)).second).first << endl;
+      DoLog(2) && (Log() << Verbose(2) << "KeySet " << (*counter)-1 << " failed to insert, present fragment is " << ((*(testGraphInsert.first)).second).first << endl);
       ((*(testGraphInsert.first)).second).second += (*runner).second.second;
-      Log() << Verbose(2) << "New factor is " << (*(testGraphInsert.first)).second.second << "." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "New factor is " << (*(testGraphInsert.first)).second.second << "." << endl);
     }
   }
Index: src/gslmatrix.cpp
===================================================================
--- src/gslmatrix.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/gslmatrix.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,4 +10,5 @@
 #include "gslmatrix.hpp"
 #include "helpers.hpp"
+#include "Helpers/fast_functions.hpp"
 
 #include <cassert>
@@ -178,5 +179,5 @@
         gsl_matrix_set(dest, j,i, gsl_matrix_get(matrix, i,j) );
       }
-    delete(matrix);
+    gsl_matrix_free(matrix);
     matrix = dest;
     flip(rows, columns);
Index: src/gslvector.cpp
===================================================================
--- src/gslvector.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/gslvector.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -6,5 +6,9 @@
  */
 
+#include <cassert>
+#include <cmath>
+
 #include "gslvector.hpp"
+#include "defs.hpp"
 
 /** Constructor of class GSLVector.
@@ -27,4 +31,14 @@
 };
 
+/** Copy constructor of class GSLVector.
+ * Allocates GSL structures and copies components from \a *src.
+ * \param *src source vector
+ */
+GSLVector::GSLVector(const GSLVector & src) : dimension(src.dimension)
+{
+  vector = gsl_vector_alloc(dimension);
+  gsl_vector_memcpy (vector, src.vector);
+};
+
 /** Destructor of class GSLVector.
  * Frees GSL structures
@@ -33,5 +47,4 @@
 {
   gsl_vector_free(vector);
-  dimension = 0;
 };
 
@@ -52,5 +65,5 @@
  * \return  m-th element of vector
  */
-double GSLVector::Get(size_t m)
+double GSLVector::Get(size_t m) const
 {
   return gsl_vector_get (vector, m);
@@ -72,5 +85,5 @@
  * \return pointer to \a m-th element
  */
-double *GSLVector::Pointer(size_t m)
+double *GSLVector::Pointer(size_t m) const
 {
   return gsl_vector_ptr (vector, m);
@@ -82,7 +95,18 @@
  * \return const pointer to \a m-th element
  */
-const double *GSLVector::const_Pointer(size_t m)
+const double *GSLVector::const_Pointer(size_t m) const
 {
   return gsl_vector_const_ptr (vector, m);
+};
+
+/** Returns the dimension of the vector.
+ * \return dimension of vector
+ */
+#ifdef HAVE_INLINE
+inline
+#endif
+size_t GSLVector::GetDimension() const
+{
+  return dimension;
 };
 
@@ -128,2 +152,142 @@
   return gsl_vector_reverse (vector);
 };
+
+
+/* ========================== Operators =============================== */
+/** Compares GSLVector \a to GSLVector \a b component-wise.
+ * \param a base GSLVector
+ * \param b GSLVector components to add
+ * \return a == b
+ */
+bool operator==(const GSLVector& a, const GSLVector& b)
+{
+  bool status = true;
+  assert(a.GetDimension() == b.GetDimension() && "Dimenions of GSLVectors to compare differ");
+  for (size_t i=0;i<a.GetDimension();i++)
+    status = status && (fabs(a.Get(i) - b.Get(i)) < MYEPSILON);
+  return status;
+};
+
+/** Sums GSLVector \a to this lhs component-wise.
+ * \param a base GSLVector
+ * \param b GSLVector components to add
+ * \return lhs + a
+ */
+const GSLVector& operator+=(GSLVector& a, const GSLVector& b)
+{
+  assert(a.GetDimension() == b.GetDimension() && "Dimenions of GSLVectors to compare differ");
+  for (size_t i=0;i<a.GetDimension();i++)
+    a.Set(i,a.Get(i)+b.Get(i));
+  return a;
+};
+
+/** Subtracts GSLVector \a from this lhs component-wise.
+ * \param a base GSLVector
+ * \param b GSLVector components to add
+ * \return lhs - a
+ */
+const GSLVector& operator-=(GSLVector& a, const GSLVector& b)
+{
+  assert(a.GetDimension() == b.GetDimension() && "Dimenions of GSLVectors to compare differ");
+  for (size_t i=0;i<a.GetDimension();i++)
+    a.Set(i,a.Get(i)-b.Get(i));
+  return a;
+};
+
+/** factor each component of \a a times a double \a m.
+ * \param a base GSLVector
+ * \param m factor
+ * \return lhs.Get(i) * m
+ */
+const GSLVector& operator*=(GSLVector& a, const double m)
+{
+  for (size_t i=0;i<a.GetDimension();i++)
+    a.Set(i,a.Get(i)*m);
+  return a;
+};
+
+/** Sums two GSLVectors \a  and \b component-wise.
+ * \param a first GSLVector
+ * \param b second GSLVector
+ * \return a + b
+ */
+GSLVector const operator+(const GSLVector& a, const GSLVector& b)
+{
+  GSLVector x(a);
+  for (size_t i=0;i<a.GetDimension();i++)
+    x.Set(i,a.Get(i)+b.Get(i));
+  return x;
+};
+
+/** Subtracts GSLVector \a from \b component-wise.
+ * \param a first GSLVector
+ * \param b second GSLVector
+ * \return a - b
+ */
+GSLVector const operator-(const GSLVector& a, const GSLVector& b)
+{
+  assert(a.GetDimension() == b.GetDimension() && "Dimenions of GSLVectors to compare differ");
+  GSLVector x(a);
+  for (size_t i=0;i<a.GetDimension();i++)
+    x.Set(i,a.Get(i)-b.Get(i));
+  return x;
+};
+
+/** Factors given GSLVector \a a times \a m.
+ * \param a GSLVector
+ * \param m factor
+ * \return m * a
+ */
+GSLVector const operator*(const GSLVector& a, const double m)
+{
+  GSLVector x(a);
+  for (size_t i=0;i<a.GetDimension();i++)
+    x.Set(i,a.Get(i)*m);
+  return x;
+};
+
+/** Factors given GSLVector \a a times \a m.
+ * \param m factor
+ * \param a GSLVector
+ * \return m * a
+ */
+GSLVector const operator*(const double m, const GSLVector& a )
+{
+  GSLVector x(a);
+  for (size_t i=0;i<a.GetDimension();i++)
+    x.Set(i,a.Get(i)*m);
+  return x;
+};
+
+ostream& operator<<(ostream& ost, const GSLVector& m)
+{
+  ost << "(";
+  for (size_t i=0;i<m.GetDimension();i++) {
+    ost << m.Get(i);
+    if (i != 2)
+      ost << ",";
+  }
+  ost << ")";
+  return ost;
+};
+
+/* ====================== Checking State ============================ */
+/** Checks whether vector has all components zero.
+ * @return true - vector is zero, false - vector is not
+ */
+bool GSLVector::IsZero() const
+{
+  return (fabs(Get(0))+fabs(Get(1))+fabs(Get(2)) < MYEPSILON);
+};
+
+/** Checks whether vector has length of 1.
+ * @return true - vector is normalized, false - vector is not
+ */
+bool GSLVector::IsOne() const
+{
+  double NormValue = 0.;
+  for (size_t i=dimension;--i;)
+    NormValue += Get(i)*Get(i);
+  return (fabs(NormValue - 1.) < MYEPSILON);
+};
+
Index: src/gslvector.hpp
===================================================================
--- src/gslvector.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/gslvector.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -18,4 +18,5 @@
 #endif
 
+#include <iostream>
 #include <gsl/gsl_vector.h>
 
@@ -32,12 +33,14 @@
   GSLVector(size_t m);
   GSLVector(const GSLVector * const src);
+  GSLVector(const GSLVector & src);
   ~GSLVector();
 
   // Accessing
   void SetFromDoubleArray(double *x);
-  double Get(size_t m);
+  double Get(size_t m) const;
   void Set(size_t m, double x);
-  double *Pointer(size_t m);
-  const double *const_Pointer(size_t m);
+  double *Pointer(size_t m) const;
+  const double *const_Pointer(size_t m) const;
+  size_t GetDimension() const;
 
   // Initializing
@@ -50,9 +53,24 @@
   int Reverse();
 
+  // checking state
+  bool IsZero() const;
+  bool IsOne() const;
+
 private:
   gsl_vector *vector;
 
-  size_t dimension;
+  const size_t dimension;
 };
+
+ostream & operator << (ostream& ost, const GSLVector &m);
+bool operator==(const GSLVector& a, const GSLVector& b);
+const GSLVector& operator+=(GSLVector& a, const GSLVector& b);
+const GSLVector& operator-=(GSLVector& a, const GSLVector& b);
+const GSLVector& operator*=(GSLVector& a, const double m);
+GSLVector const operator*(const GSLVector& a, const double m);
+GSLVector const operator*(const double m, const GSLVector& a);
+GSLVector const operator+(const GSLVector& a, const GSLVector& b);
+GSLVector const operator-(const GSLVector& a, const GSLVector& b);
+
 
 
Index: src/helpers.cpp
===================================================================
--- src/helpers.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/helpers.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -6,4 +6,5 @@
 
 #include "helpers.hpp"
+#include "Helpers/fast_functions.hpp"
 #include "log.hpp"
 #include "memoryusageobserver.hpp"
@@ -19,5 +20,5 @@
   double test = 0.1439851348959832147598734598273456723948652983045928346598365;
   do {
-    Log() << Verbose(0) << text;
+    DoLog(0) && (Log() << Verbose(0) << text);
     cin >> test;
   } while (test == 0.1439851348959832147598734598273456723948652983045928346598365);
@@ -49,18 +50,4 @@
   while (*b < lower_bound)
     *b += step;
-};
-
-/** Returns the power of \a n with respect to \a base.
- * \param base basis
- * \param n power
- * \return \f$base^n\f$
- */
-int pot(int base, int n)
-{
-  int res = 1;
-  int j;
-  for (j=n;j--;)
-    res *= base;
-  return res;
 };
 
@@ -175,33 +162,5 @@
 };
 
-/** hard-coded determinant of a 3x3 matrix.
- * \param a[9] matrix
- * \return \f$det(a)\f$
- */
-double RDET3(const double a[NDIM*NDIM])
-{
-  return ((a)[0]*(a)[4]*(a)[8] + (a)[3]*(a)[7]*(a)[2] + (a)[6]*(a)[1]*(a)[5] - (a)[2]*(a)[4]*(a)[6] - (a)[5]*(a)[7]*(a)[0] - (a)[8]*(a)[1]*(a)[3]);
-};
-
-/** hard-coded determinant of a 2x2 matrix.
- * \param a[4] matrix
- * \return \f$det(a)\f$
- */
-double RDET2(const double a[4])
-{
-  return ((a[0])*(a[3])-(a[1])*(a[2]));
-};
-
-/** hard-coded determinant of a 2x2 matrix.
- * \param a0 (0,0) entry of matrix
- * \param a1 (0,1) entry of matrix
- * \param a2 (1,0) entry of matrix
- * \param a3 (1,1) entry of matrix
- * \return \f$det(a)\f$
- */
-double RDET2(const double a0, const double a1, const double a2, const double a3)
-{
-  return ((a0)*(a3)-(a1)*(a2));
-};
+
 
 /** Comparison function for GSL heapsort on distances in two molecules.
Index: src/helpers.hpp
===================================================================
--- src/helpers.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/helpers.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -24,9 +24,4 @@
 /********************************************** definitions *********************************/
 
-// some algebraic matrix stuff
-double RDET3(const double a[NDIM*NDIM]);
-double RDET2(const double a[4]);
-double RDET2(const double a0, const double a1, const double a2, const double a3);
-
 /********************************************** helpful functions *********************************/
 
@@ -53,5 +48,4 @@
 bool check_bounds(double *x, double *cell_size);
 void bound(double *b, double lower_bound, double upper_bound);
-int pot(int base, int n);
 int CountLinesinFile(ifstream &InputFile);
 char *FixedDigitNumber(const int FragmentNumber, const int digits);
@@ -64,15 +58,4 @@
 /********************************************** helpful template functions *********************************/
 
-/** Flips two values.
- * \param x first value
- * \param y second value
- */
-template <typename T> void flip(T &x, T &y)
-{
-  T tmp;
-  tmp = x;
-  x = y;
-  y = tmp;
-};
 
 /** returns greater of the two values.
@@ -114,5 +97,5 @@
 
   if (LookupTable != NULL) {
-    Log() << Verbose(0) << "Pointer for Lookup table is not NULL! Aborting ..." <<endl;
+    DoLog(0) && (Log() << Verbose(0) << "Pointer for Lookup table is not NULL! Aborting ..." <<endl);
     return false;
   }
@@ -127,5 +110,5 @@
   }
   if (count <= 0) {
-    Log() << Verbose(0) << "Count of lookup list is 0 or less." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Count of lookup list is 0 or less." << endl);
     return false;
   }
@@ -134,5 +117,5 @@
   LookupTable = Calloc<T*>(count, "CreateFatherLookupTable - **LookupTable");
   if (LookupTable == NULL) {
-    eLog() << Verbose(0) << "LookupTable memory allocation failed!" << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "LookupTable memory allocation failed!" << endl);
     performCriticalExit();
     status = false;
@@ -146,5 +129,5 @@
         LookupTable[AtomNo] = Walker;
       } else {
-        Log() << Verbose(0) << "Walker " << *Walker << " exceeded range of nuclear ids [0, " << count << ")." << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Walker " << *Walker << " exceeded range of nuclear ids [0, " << count << ")." << endl);
         status = false;
         break;
@@ -189,3 +172,27 @@
 #define PLURAL_S(v) (((v)==1)?"":"s")
 
+// this is to allow different modes of access for
+// maps and sets
+template<typename Res,typename T>
+struct _take{
+  Res get(T value) const;
+};
+
+// if we have a set,vector etc we can directly access the result
+template<typename Res>
+struct _take<Res,Res>{
+  static inline Res get(Res value){
+    return value;
+  }
+};
+
+// if we have a map we have to access the second part of
+// the pair
+template<typename Res,typename T1>
+struct _take<Res,std::pair<T1,Res> >{
+  static inline Res get(std::pair<T1,Res> value){
+    return value.second;
+  }
+};
+
 #endif /*HELPERS_HPP_*/
Index: src/info.cpp
===================================================================
--- src/info.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/info.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -21,5 +21,5 @@
   verbosity++;
   FunctionName = msg;
-  Log() << Verbose(0) << "Begin of " << FunctionName << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Begin of " << FunctionName << endl);
 };
 
@@ -28,5 +28,5 @@
  */
 Info::~Info() {
-  Log() << Verbose(0) << "End of " << FunctionName << endl;
+  DoLog(0) && (Log() << Verbose(0) << "End of " << FunctionName << endl);
   verbosity--;
 }
Index: src/joiner.cpp
===================================================================
--- src/joiner.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/joiner.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -47,13 +47,13 @@
   bool NoHessian = false;
 
-  Log() << Verbose(0) << "Joiner" << endl;
-  Log() << Verbose(0) << "======" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Joiner" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "======" << endl);
 
   // Get the command line options
   if (argc < 3) {
-    Log() << Verbose(0) << "Usage: " << argv[0] << " <inputdir> <prefix> [elementsdb]" << endl;
-    Log() << Verbose(0) << "<inputdir>\ttherein the output of a molecuilder fragmentation is expected, each fragment with a subdir containing an energy.all and a forces.all file." << endl;
-    Log() << Verbose(0) << "<prefix>\tprefix of energy and forces file." << endl;
-    Log() << Verbose(0) << "[elementsdb]\tpath to elements database, needed for shieldings." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Usage: " << argv[0] << " <inputdir> <prefix> [elementsdb]" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "<inputdir>\ttherein the output of a molecuilder fragmentation is expected, each fragment with a subdir containing an energy.all and a forces.all file." << endl);
+    DoLog(0) && (Log() << Verbose(0) << "<prefix>\tprefix of energy and forces file." << endl);
+    DoLog(0) && (Log() << Verbose(0) << "[elementsdb]\tpath to elements database, needed for shieldings." << endl);
     return 1;
   } else {
@@ -77,10 +77,10 @@
   if (!Hcorrection.ParseFragmentMatrix(argv[1], "", HCORRECTIONSUFFIX, 0,0)) {
     NoHCorrection = true;
-    Log() << Verbose(0) << "No HCorrection matrices found, skipping these." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "No HCorrection matrices found, skipping these." << endl);
   }
   if (!Force.ParseFragmentMatrix(argv[1], dir, ForcesSuffix, 0,0)) return 1;
   if (!Hessian.ParseFragmentMatrix(argv[1], dir, HessianSuffix, 0,0)) {
     NoHessian = true;
-    Log() << Verbose(0) << "No hessian matrices found, skipping these." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "No hessian matrices found, skipping these." << endl);
   }
   if (periode != NULL) { // also look for PAS values
@@ -146,5 +146,5 @@
   for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
     // --------- sum up energy --------------------
-    Log() << Verbose(0) << "Summing energy of order " << BondOrder+1 << " ..." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Summing energy of order " << BondOrder+1 << " ..." << endl);
     if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return 1;
     if (!NoHCorrection) { 
@@ -155,15 +155,15 @@
       if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) return 1;
     // --------- sum up Forces --------------------
-    Log() << Verbose(0) << "Summing forces of order " << BondOrder+1 << " ..." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Summing forces of order " << BondOrder+1 << " ..." << endl);
     if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return 1;
     if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder, 1.)) return 1;
     // --------- sum up Hessian --------------------
     if (!NoHessian) {
-      Log() << Verbose(0) << "Summing Hessian of order " << BondOrder+1 << " ..." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Summing Hessian of order " << BondOrder+1 << " ..." << endl);
       if (!HessianFragments.SumSubManyBodyTerms(Hessian, KeySet, BondOrder)) return 1;
       if (!Hessian.SumSubHessians(HessianFragments, KeySet, BondOrder, 1.)) return 1;
     }
     if (periode != NULL) { // also look for PAS values
-      Log() << Verbose(0) << "Summing shieldings and susceptibilities of order " << BondOrder+1 << " ..." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Summing shieldings and susceptibilities of order " << BondOrder+1 << " ..." << endl);
       if (!ShieldingFragments.SumSubManyBodyTerms(Shielding, KeySet, BondOrder)) return 1;
       if (!Shielding.SumSubForces(ShieldingFragments, KeySet, BondOrder, 1.)) return 1;
@@ -179,5 +179,5 @@
     prefix.str(" ");
     prefix << dir << OrderSuffix << (BondOrder+1);
-    Log() << Verbose(0) << "Writing files " << argv[1] << prefix.str() << ". ..." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Writing files " << argv[1] << prefix.str() << ". ..." << endl);
     // energy
     if (!Energy.WriteLastMatrix(argv[1], (prefix.str()).c_str(), EnergySuffix)) return 1;
@@ -244,5 +244,5 @@
   delete(periode);
   Free(&dir);
-  Log() << Verbose(0) << "done." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done." << endl);
   return 0;
 };
Index: src/leastsquaremin.cpp
===================================================================
--- src/leastsquaremin.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/leastsquaremin.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -25,5 +25,5 @@
   for (int i=num;i--;) {
     for(int j=NDIM;j--;)
-      sum += (gsl_vector_get(x,j) - (vectors[i])->x[j])*(gsl_vector_get(x,j) - (vectors[i])->x[j]);
+      sum += (gsl_vector_get(x,j) - (vectors[i])->at(j))*(gsl_vector_get(x,j) - (vectors[i])->at(j));
   }
 
Index: src/leastsquaremin.hpp
===================================================================
--- src/leastsquaremin.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/leastsquaremin.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -42,5 +42,5 @@
   gsl_vector *x;
   const molecule *mol;
-  element *type;
+  const element *type;
 };
 
Index: src/linearsystemofequations.cpp
===================================================================
--- src/linearsystemofequations.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/linearsystemofequations.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -54,5 +54,5 @@
 {
   assert ( columns == NDIM && "Vector class is always three-dimensional, unlike this LEqS!");
-  b->SetFromDoubleArray(x->x);
+  b->SetFromDoubleArray(x->get());
 };
 
@@ -100,5 +100,5 @@
   // copy solution
   for (size_t i=0;i<x->dimension;i++)
-    v.x[i] = x->Get(i);
+    v[i] = x->Get(i);
   return status;
 };
Index: src/linkedcell.cpp
===================================================================
--- src/linkedcell.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/linkedcell.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -45,7 +45,7 @@
   max.Zero();
   min.Zero();
-  Log() << Verbose(1) << "Begin of LinkedCell" << endl;
-  if (set->IsEmpty()) {
-    eLog() << Verbose(1) << "set contains no linked cell nodes!" << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Begin of LinkedCell" << endl);
+  if ((set == NULL) || (set->IsEmpty())) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "set is NULL or contains no linked cell nodes!" << endl);
     return;
   }
@@ -54,6 +54,6 @@
   Walker = set->GetPoint();
   for (int i=0;i<NDIM;i++) {
-    max.x[i] = Walker->node->x[i];
-    min.x[i] = Walker->node->x[i];
+    max[i] = Walker->node->at(i);
+    min[i] = Walker->node->at(i);
   }
   set->GoToFirst();
@@ -61,23 +61,23 @@
     Walker = set->GetPoint();
     for (int i=0;i<NDIM;i++) {
-      if (max.x[i] < Walker->node->x[i])
-        max.x[i] = Walker->node->x[i];
-      if (min.x[i] > Walker->node->x[i])
-        min.x[i] = Walker->node->x[i];
+      if (max[i] < Walker->node->at(i))
+        max[i] = Walker->node->at(i);
+      if (min[i] > Walker->node->at(i))
+        min[i] = Walker->node->at(i);
     }
     set->GoToNext();
   }
-  Log() << Verbose(2) << "Bounding box is " << min << " and " << max << "." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Bounding box is " << min << " and " << max << "." << endl);
 
   // 2. find then number of cells per axis
   for (int i=0;i<NDIM;i++) {
-    N[i] = (int)floor((max.x[i] - min.x[i])/RADIUS)+1;
-  }
-  Log() << Verbose(2) << "Number of cells per axis are " << N[0] << ", " << N[1] << " and " << N[2] << "." << endl;
+    N[i] = static_cast<int>(floor((max[i] - min[i])/RADIUS)+1);
+  }
+  DoLog(2) && (Log() << Verbose(2) << "Number of cells per axis are " << N[0] << ", " << N[1] << " and " << N[2] << "." << endl);
 
   // 3. allocate the lists
-  Log() << Verbose(2) << "Allocating cells ... ";
+  DoLog(2) && (Log() << Verbose(2) << "Allocating cells ... ");
   if (LC != NULL) {
-    eLog() << Verbose(1) << "Linked Cell list is already allocated, I do nothing." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Linked Cell list is already allocated, I do nothing." << endl);
     return;
   }
@@ -86,13 +86,13 @@
     LC [index].clear();
   }
-  Log() << Verbose(0) << "done."  << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done."  << endl);
 
   // 4. put each atom into its respective cell
-  Log() << Verbose(2) << "Filling cells ... ";
+  DoLog(2) && (Log() << Verbose(2) << "Filling cells ... ");
   set->GoToFirst();
   while (!set->IsEnd()) {
     Walker = set->GetPoint();
     for (int i=0;i<NDIM;i++) {
-      n[i] = (int)floor((Walker->node->x[i] - min.x[i])/RADIUS);
+      n[i] = static_cast<int>(floor((Walker->node->at(i) - min[i])/RADIUS));
     }
     index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
@@ -101,6 +101,6 @@
     set->GoToNext();
   }
-  Log() << Verbose(0) << "done."  << endl;
-  Log() << Verbose(1) << "End of LinkedCell" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done."  << endl);
+  DoLog(1) && (Log() << Verbose(1) << "End of LinkedCell" << endl);
 };
 
@@ -120,7 +120,7 @@
   max.Zero();
   min.Zero();
-  Log() << Verbose(1) << "Begin of LinkedCell" << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Begin of LinkedCell" << endl);
   if (set->empty()) {
-    eLog() << Verbose(1) << "set contains no linked cell nodes!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "set contains no linked cell nodes!" << endl);
     return;
   }
@@ -128,28 +128,28 @@
   LinkedNodes::iterator Runner = set->begin();
   for (int i=0;i<NDIM;i++) {
-    max.x[i] = (*Runner)->node->x[i];
-    min.x[i] = (*Runner)->node->x[i];
+    max[i] = (*Runner)->node->at(i);
+    min[i] = (*Runner)->node->at(i);
   }
   for (LinkedNodes::iterator Runner = set->begin(); Runner != set->end(); Runner++) {
     Walker = *Runner;
     for (int i=0;i<NDIM;i++) {
-      if (max.x[i] < Walker->node->x[i])
-        max.x[i] = Walker->node->x[i];
-      if (min.x[i] > Walker->node->x[i])
-        min.x[i] = Walker->node->x[i];
+      if (max[i] < Walker->node->at(i))
+        max[i] = Walker->node->at(i);
+      if (min[i] > Walker->node->at(i))
+        min[i] = Walker->node->at(i);
     }
   }
-  Log() << Verbose(2) << "Bounding box is " << min << " and " << max << "." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Bounding box is " << min << " and " << max << "." << endl);
 
   // 2. find then number of cells per axis
   for (int i=0;i<NDIM;i++) {
-    N[i] = (int)floor((max.x[i] - min.x[i])/RADIUS)+1;
-  }
-  Log() << Verbose(2) << "Number of cells per axis are " << N[0] << ", " << N[1] << " and " << N[2] << "." << endl;
+    N[i] = static_cast<int>(floor((max[i] - min[i])/RADIUS)+1);
+  }
+  DoLog(2) && (Log() << Verbose(2) << "Number of cells per axis are " << N[0] << ", " << N[1] << " and " << N[2] << "." << endl);
 
   // 3. allocate the lists
-  Log() << Verbose(2) << "Allocating cells ... ";
+  DoLog(2) && (Log() << Verbose(2) << "Allocating cells ... ");
   if (LC != NULL) {
-    eLog() << Verbose(1) << "Linked Cell list is already allocated, I do nothing." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Linked Cell list is already allocated, I do nothing." << endl);
     return;
   }
@@ -158,12 +158,12 @@
     LC [index].clear();
   }
-  Log() << Verbose(0) << "done."  << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done."  << endl);
 
   // 4. put each atom into its respective cell
-  Log() << Verbose(2) << "Filling cells ... ";
+  DoLog(2) && (Log() << Verbose(2) << "Filling cells ... ");
   for (LinkedNodes::iterator Runner = set->begin(); Runner != set->end(); Runner++) {
     Walker = *Runner;
     for (int i=0;i<NDIM;i++) {
-      n[i] = (int)floor((Walker->node->x[i] - min.x[i])/RADIUS);
+      n[i] = static_cast<int>(floor((Walker->node->at(i) - min[i])/RADIUS));
     }
     index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
@@ -171,6 +171,6 @@
     //Log() << Verbose(2) << *Walker << " goes into cell " << n[0] << ", " << n[1] << ", " << n[2] << " with No. " << index << "." << endl;
   }
-  Log() << Verbose(0) << "done."  << endl;
-  Log() << Verbose(1) << "End of LinkedCell" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done."  << endl);
+  DoLog(1) && (Log() << Verbose(1) << "End of LinkedCell" << endl);
 };
 
@@ -199,5 +199,5 @@
     status = status && ((n[i] >=0) && (n[i] < N[i]));
   if (!status)
-  eLog() << Verbose(1) << "indices are out of bounds!" << endl;
+  DoeLog(1) && (eLog()<< Verbose(1) << "indices are out of bounds!" << endl);
   return status;
 };
@@ -220,5 +220,5 @@
  * \return LinkedAtoms pointer to current cell, NULL if LinkedCell::n[] are out of bounds.
  */
-const LinkedNodes* LinkedCell::GetCurrentCell() const
+const LinkedCell::LinkedNodes* LinkedCell::GetCurrentCell() const
 {
   if (CheckBounds()) {
@@ -234,5 +234,5 @@
  * \return LinkedAtoms pointer to current cell, NULL if LinkedCell::n[]+relative[] are out of bounds.
  */
-const LinkedNodes* LinkedCell::GetRelativeToCurrentCell(const int relative[NDIM]) const
+const LinkedCell::LinkedNodes* LinkedCell::GetRelativeToCurrentCell(const int relative[NDIM]) const
 {
   if (CheckBounds(relative)) {
@@ -244,4 +244,16 @@
 };
 
+/** Set the index to the cell containing a given Vector *x.
+ * \param *x Vector with coordinates
+ * \return Vector is inside bounding box - true, else - false
+ */
+bool LinkedCell::SetIndexToVector(const Vector * const x) const
+{
+  for (int i=0;i<NDIM;i++)
+    n[i] = (int)floor((x->at(i) - min[i])/RADIUS);
+
+  return CheckBounds();
+};
+
 /** Calculates the index for a given LCNode *Walker.
  * \param *Walker LCNode to set index tos
@@ -252,5 +264,5 @@
   bool status = false;
   for (int i=0;i<NDIM;i++) {
-    n[i] = (int)floor((Walker->node->x[i] - min.x[i])/RADIUS);
+    n[i] = static_cast<int>(floor((Walker->node->at(i) - min[i])/RADIUS));
   }
   index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
@@ -260,5 +272,5 @@
     return status;
   } else {
-    eLog() << Verbose(1) << "Node at " << *Walker << " is out of bounds." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Node at " << *Walker << " is out of bounds." << endl);
     return false;
   }
@@ -268,36 +280,137 @@
  * \param *lower lower bounds
  * \param *upper upper bounds
- */
-void LinkedCell::GetNeighbourBounds(int lower[NDIM], int upper[NDIM]) const
-{
-  for (int i=0;i<NDIM;i++) {
-    lower[i] = ((n[i]-1) >= 0) ? n[i]-1 : 0;
-    upper[i] = ((n[i]+1) < N[i]) ? n[i]+1 : N[i]-1;
-    //Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
-    // check for this axis whether the point is outside of our grid
+ * \param step how deep to check the neighbouring cells (i.e. number of layers to check)
+ */
+void LinkedCell::GetNeighbourBounds(int lower[NDIM], int upper[NDIM], int step) const
+{
+  for (int i=0;i<NDIM;i++) {
+    lower[i] = n[i];
+    for (int s=step; s>0;--s)
+      if ((n[i]-s) >= 0) {
+        lower[i] = n[i]-s;
+        break;
+      }
+    upper[i] = n[i];
+    for (int s=step; s>0;--s)
+      if ((n[i]+s) < N[i]) {
+        upper[i] = n[i]+s;
+        break;
+      }
+    //Log() << Verbose(0) << "axis " << i << " has bounds [" << lower[i] << "," << upper[i] << "]" << endl;
+  }
+};
+
+/** Returns a list with all neighbours from the current LinkedCell::index.
+ * \param distance (if no distance, then adjacent cells are taken)
+ * \return list of tesselpoints
+ */
+LinkedCell::LinkedNodes* LinkedCell::GetallNeighbours(const double distance) const
+{
+  int Nlower[NDIM], Nupper[NDIM];
+  TesselPoint *Walker = NULL;
+  LinkedNodes *TesselList = new LinkedNodes;
+
+  // then go through the current and all neighbouring cells and check the contained points for possible candidates
+  const int step = (distance == 0) ? 1 : (int)floor(distance/RADIUS + 1.);
+  GetNeighbourBounds(Nlower, Nupper, step);
+
+  //Log() << Verbose(0) << endl;
+  for (n[0] = Nlower[0]; n[0] <= Nupper[0]; n[0]++)
+    for (n[1] = Nlower[1]; n[1] <= Nupper[1]; n[1]++)
+      for (n[2] = Nlower[2]; n[2] <= Nupper[2]; n[2]++) {
+        const LinkedNodes *List = GetCurrentCell();
+        //Log() << Verbose(1) << "Current cell is " << n[0] << ", " << n[1] << ", " << n[2] << " with No. " << index << "." << endl;
+        if (List != NULL) {
+          for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+            Walker = *Runner;
+            TesselList->push_back(Walker);
+          }
+        }
+      }
+  return TesselList;
+};
+
+/** Set the index to the cell containing a given Vector *x, which is not inside the LinkedCell's domain
+ * Note that as we have to check distance from every corner of the closest cell, this function is faw more
+ * expensive and if Vector is known to be inside LinkedCell's domain, then SetIndexToVector() should be used.
+ * \param *x Vector with coordinates
+ * \return minimum squared distance of cell to given vector (if inside of domain, distance is 0)
+ */
+double LinkedCell::SetClosestIndexToOutsideVector(const Vector * const x) const
+{
+  for (int i=0;i<NDIM;i++) {
+    n[i] = (int)floor((x->at(i) - min[i])/RADIUS);
     if (n[i] < 0)
-      upper[i] = lower[i];
-    if (n[i] > N[i])
-      lower[i] = upper[i];
-
-    //Log() << Verbose(0) << "axis " << i << " has bounds [" << lower[i] << "," << upper[i] << "]" << endl;
-  }
-};
-
-/** Calculates the index for a given Vector *x.
- * \param *x Vector with coordinates
- * \return Vector is inside bounding box - true, else - false
- */
-bool LinkedCell::SetIndexToVector(const Vector * const x) const
-{
-  bool status = true;
-  for (int i=0;i<NDIM;i++) {
-    n[i] = (int)floor((x->x[i] - min.x[i])/RADIUS);
-    if (max.x[i] < x->x[i])
-      status = false;
-    if (min.x[i] > x->x[i])
-      status = false;
-  }
-  return status;
-};
-
+      n[i] = 0;
+    if (n[i] >= N[i])
+      n[i] = N[i]-1;
+  }
+
+  // calculate distance of cell to vector
+  double distanceSquared = 0.;
+  bool outside = true;  // flag whether x is found in- or outside of LinkedCell's domain/closest cell
+  Vector corner; // current corner of closest cell
+  Vector tester; // Vector pointing from corner to center of closest cell
+  Vector Distance;  // Vector from corner of closest cell to x
+
+  Vector center;  // center of the closest cell
+  for (int i=0;i<NDIM;i++)
+    center[i] = min[i]+((double)n[i]+.5)*RADIUS;
+
+  int c[NDIM];
+  for (c[0]=0;c[0]<=1;c[0]++)
+    for (c[1]=0; c[1]<=1;c[1]++)
+      for (c[2]=0; c[2]<=1;c[2]++) {
+        // set up corner
+        for (int i=0;i<NDIM;i++)
+          corner[i] = min[i]+RADIUS*((double)n[i]+c[i]);
+        // set up distance vector
+        Distance = (*x) - corner;
+        const double dist = Distance.NormSquared();
+        // check whether distance is smaller
+        if (dist< distanceSquared)
+          distanceSquared = dist;
+        // check whether distance vector goes inside or outside
+        tester = center -corner;
+        if (tester.ScalarProduct(Distance) < 0)
+          outside = false;
+      }
+  return (outside ? distanceSquared : 0.);
+};
+
+/** Returns a list of all TesselPoint with distance less than \a radius to \a *Center.
+ * \param radius radius of sphere
+ * \param *center center of sphere
+ * \return list of all points inside sphere
+ */
+LinkedCell::LinkedNodes* LinkedCell::GetPointsInsideSphere(const double radius, const Vector * const center) const
+{
+  const double radiusSquared = radius*radius;
+  TesselPoint *Walker = NULL;
+  LinkedNodes *TesselList = new LinkedNodes;
+  LinkedNodes *NeighbourList = NULL;
+
+  // set index of LC to center of sphere
+  const double dist = SetClosestIndexToOutsideVector(center);
+  if (dist > 2.*radius) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Vector " << *center << " is too far away from any atom in LinkedCell's bounding box." << endl);
+    return TesselList;
+  } else
+    DoLog(1) && (Log() << Verbose(1) << "Distance of closest cell to center of sphere with radius " << radius << " is " << dist << "." << endl);
+
+  // gather all neighbours first, then look who fulfills distance criteria
+  NeighbourList = GetallNeighbours(2.*radius-dist);
+  //Log() << Verbose(1) << "I found " << NeighbourList->size() << " neighbours to check." << endl;
+  if (NeighbourList != NULL) {
+    for (LinkedNodes::const_iterator Runner = NeighbourList->begin(); Runner != NeighbourList->end(); Runner++) {
+      Walker = *Runner;
+      //Log() << Verbose(1) << "Current neighbour is at " << *Walker->node << "." << endl;
+      if ((center->DistanceSquared(*Walker->node) - radiusSquared) < MYEPSILON) {
+        TesselList->push_back(Walker);
+      }
+    }
+    delete(NeighbourList);
+  } else
+    DoeLog(2) && (eLog()<< Verbose(2) << "Around vector " << *center << " there are no atoms." << endl);
+  return TesselList;
+};
Index: src/linkedcell.hpp
===================================================================
--- src/linkedcell.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/linkedcell.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -33,5 +33,4 @@
 /********************************************** definitions *********************************/
 
-#define LinkedNodes list<TesselPoint *>
 
 /********************************************** declarations *******************************/
@@ -40,5 +39,10 @@
  */
 class LinkedCell {
-  public:
+private:
+
+public:
+  typedef list<TesselPoint *> LinkedNodes;
+
+
     Vector max;       // upper boundary
     Vector min;       // lower boundary
@@ -53,12 +57,15 @@
     LinkedCell(LinkedNodes *set, const double radius);
     ~LinkedCell();
-    const LinkedNodes* GetCurrentCell()const ;
-    const LinkedNodes* GetRelativeToCurrentCell(const int relative[NDIM])const ;
+    const LinkedCell::LinkedNodes* GetCurrentCell()const ;
+    const LinkedCell::LinkedNodes* GetRelativeToCurrentCell(const int relative[NDIM])const ;
     bool SetIndexToNode(const TesselPoint * const Walker)const ;
     bool SetIndexToVector(const Vector * const x)const ;
+    double SetClosestIndexToOutsideVector(const Vector * const x) const;
     bool CheckBounds()const ;
     bool CheckBounds(const int relative[NDIM])const ;
-    void GetNeighbourBounds(int lower[NDIM], int upper[NDIM])const ;
+    void GetNeighbourBounds(int lower[NDIM], int upper[NDIM], int step = 1)const ;
 
+    LinkedCell::LinkedNodes* GetallNeighbours(const double distance = 0) const;
+    LinkedCell::LinkedNodes* GetPointsInsideSphere(const double radius, const Vector * const center) const;
     // not implemented yet
     bool AddNode(Vector *Walker);
Index: src/lists.cpp
===================================================================
--- src/lists.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/lists.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,21 @@
+/*
+ * lists.cpp
+ *
+ *  Created on: Feb 24, 2010
+ *      Author: crueger
+ */
+
+#include "lists.hpp"
+#include "World.hpp"
+#include "atom.hpp"
+
+// specialized templates for lists
+// can be directly compiled since no further templatization is needed
+template <> void removewithoutcheck<atom>(atom *walker)
+{
+  if (walker != 0) {
+    unlink(walker);
+    walker->getWorld()->destroyAtom(walker);
+    walker = 0;
+  }
+};
Index: src/lists.hpp
===================================================================
--- src/lists.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/lists.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,4 +9,6 @@
 #define LISTS_HPP_
 
+class atom;
+
 /******************************** Some templates for list management ***********************************/
 
@@ -18,5 +20,5 @@
 {
   X *vorher = end->previous;
-  if (vorher != NULL)
+  if (vorher != 0)
     vorher->next = walker;
   end->previous = walker;
@@ -31,10 +33,10 @@
 template <typename X> void unlink(X *walker)
 {
-  if (walker->next != NULL)
+  if (walker->next != 0)
     walker->next->previous = walker->previous;
-  if (walker->previous != NULL)
+  if (walker->previous != 0)
     walker->previous->next = walker->next;
-  walker->next = NULL;
-  walker->previous= NULL;
+  walker->next = 0;
+  walker->previous= 0;
 };
 
@@ -46,9 +48,9 @@
 template <typename X>  bool add(X *pointer, X *end)
 {
-  if (end != NULL) {
+  if (end != 0) {
     link(pointer, end);
   } else {
-    pointer->previous = NULL;
-    pointer->next = NULL;
+    pointer->previous = 0;
+    pointer->next = 0;
   }
   return true;
@@ -59,5 +61,5 @@
  * \param *start  begin of list
  * \param *end  end of list
- * \return X - if found, NULL - if not found
+ * \return X - if found, 0 - if not found
  */
 template <typename X, typename Y> X * find(Y *suche, X *start, X *end)
@@ -68,5 +70,5 @@
     if (*walker->sort == *suche) return (walker);
   }
-  return NULL;
+  return 0;
 };
 
@@ -77,10 +79,18 @@
 template <typename X> void removewithoutcheck(X *walker)
 {
-  if (walker != NULL) {
+  if (walker != 0) {
     unlink(walker);
     delete(walker);
-    walker = NULL;
+    walker = 0;
   }
 };
+
+/** Removes an item from the list without check.
+ *  specialized for atoms, because these have to be removed from the world as well
+ *  the implementation for this declaration is in lists.cpp
+ * \param *walker item to be removed
+ * \return true - removing succeeded, false - given item not found in list
+ */
+template <> void removewithoutcheck<atom>(atom *walker);
 
 /** Removes an item from the list, checks if exists.
@@ -99,5 +109,5 @@
   }*/
   // atom found, now unlink
-  if (walker != NULL)
+  if (walker != 0)
     removewithoutcheck(walker);
   else
@@ -114,5 +124,5 @@
 {
   X *pointer = start->next;
-  X *walker = NULL;
+  X *walker = 0;
   while (pointer != end) { // go through list
     walker = pointer; // mark current
@@ -131,5 +141,5 @@
 {
   X *Binder = me;
-  while(Binder->previous != NULL)
+  while(Binder->previous != 0)
     Binder = Binder->previous;
   return Binder;
@@ -143,5 +153,5 @@
 {
   X *Binder = me;
-  while(Binder->next != NULL)
+  while(Binder->next != 0)
     Binder = Binder->next;
   return Binder;
Index: src/log.cpp
===================================================================
--- src/log.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/log.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -15,6 +15,5 @@
  */
 void setVerbosity(int verbosityLevel) {
-  logger::getInstance()->setVerbosity(verbosityLevel);
-  errorLogger::getInstance()->setVerbosity(verbosityLevel);
+  logger::getInstance().setVerbosity(verbosityLevel);
 }
 
@@ -24,6 +23,28 @@
  * \param indentation level of the message to log
  */
-class logger * Log() {
+class logger& Log() {
   return logger::getInstance();
+}
+
+/** Checks verbosity for logger.
+ * Is supposed to be used in construct as this:
+ * DoLog(2) && (Log() << Verbose(2) << "message." << endl);
+ * If DoLog does not return true, the right-hand side is not evaluated and we save some time.
+ * \param verbose verbosity level of this message
+ * \return true - print, false - don't
+ */
+bool DoLog(int verbose) {
+  return (verbose <= logger::getInstance().verbosity);
+}
+
+/** Checks verbosity for errorlogger.
+ * Is supposed to be used in construct as this:
+ * DoLog(2) && (Log() << Verbose(2) << "message." << endl);
+ * If DoLog does not return true, the right-hand side is not evaluated and we save some time.
+ * \param verbose verbosity level of this message
+ * \return true - print, false - don't
+ */
+bool DoeLog(int verbose) {
+  return (verbose <= errorLogger::getInstance().verbosity);
 }
 
@@ -33,5 +54,5 @@
  * \param indentation level of the message to log
  */
-class errorLogger * eLog() {
+class errorLogger & eLog() {
   return errorLogger::getInstance();
 }
Index: src/log.hpp
===================================================================
--- src/log.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/log.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -15,4 +15,6 @@
 class errorLogger * eLog();
 void setVerbosity(int verbosityLevel);
+bool DoLog(int verbose);
+bool DoeLog(int verbose);
 
 #endif /* LOG_HPP_ */
Index: src/logger.cpp
===================================================================
--- src/logger.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/logger.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -9,8 +9,8 @@
 #include "logger.hpp"
 #include "verbose.hpp"
+#include "Patterns/Singleton_impl.hpp"
 
 ofstream nullStream("/dev/null");
 
-logger* logger::instance = NULL;
 int logger::verbosity = 2;
 ostream* logger::nix = &nullStream;
@@ -23,5 +23,4 @@
 logger::logger()
 {
-  instance = NULL;
   verbosity = 2;
 };
@@ -34,28 +33,5 @@
 }
 
-/**
- * Returns the singleton logger instance.
- *
- * \return logger instance
- */
-logger* logger::getInstance() {
-  if (instance == NULL) {
-    instance = new logger();
-  }
-
-  return instance;
-}
-
-
-/**
- * Purges the current logger instance.
- */
-void logger::purgeInstance() {
-  if (instance != NULL) {
-    delete instance;
-  }
-
-  instance = NULL;
-}
+CONSTRUCT_SINGLETON(logger)
 
 /**
Index: src/logger.hpp
===================================================================
--- src/logger.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/logger.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -11,15 +11,16 @@
 #include <iostream>
 
+#include "Patterns/Singleton.hpp"
+
 using namespace std;
 
 class Verbose;
 
-class logger {
+class logger : public Singleton<logger> {
+  friend class Singleton<logger>;
 public :
   static ostream *nix;
   static int verbosity;
 
-  static logger* getInstance();
-  static void purgeInstance();
   static bool DoOutput();
   static void setVerbosity(int verbosityLevel);
@@ -30,7 +31,4 @@
   /** Do not call this destructor directly, use purgeInstance() instead. */
   ~logger();
-
-private:
-  static logger* instance;
 };
 
Index: src/memoryusageobserver.cpp
===================================================================
--- src/memoryusageobserver.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/memoryusageobserver.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -93,6 +93,6 @@
       << pointer << " is not registered by MemoryUsageObserver: ";
     if (msg != NULL)
-      Log() << Verbose(0) << *msg;
-    Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << *msg);
+    DoLog(0) && (Log() << Verbose(0) << endl);
     return;
   }
Index: src/molecule.cpp
===================================================================
--- src/molecule.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/molecule.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -8,4 +8,5 @@
 #include <boost/bind.hpp>
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
@@ -24,4 +25,8 @@
 #include "tesselation.hpp"
 #include "vector.hpp"
+#include "World.hpp"
+#include "Plane.hpp"
+#include "Exceptions/LinearDependenceException.hpp"
+
 
 /************************************* Functions for class molecule *********************************/
@@ -30,9 +35,11 @@
  * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
  */
-molecule::molecule(const periodentafel * const teil) : elemente(teil), start(new atom), end(new atom), 
+molecule::molecule(const periodentafel * const teil) : elemente(teil), start(World::getInstance().createAtom()), end(World::getInstance().createAtom()),
   first(new bond(start, end, 1, -1)), last(new bond(start, end, 1, -1)), MDSteps(0), AtomCount(0), 
   BondCount(0), ElementCount(0), NoNonHydrogen(0), NoNonBonds(0), NoCyclicBonds(0), BondDistance(0.), 
-  ActiveFlag(false), IndexNr(-1), last_atom(0), InternalPointer(start),
-  formula(this,boost::bind(&molecule::calcFormula,this))
+  ActiveFlag(false), IndexNr(-1),
+  formula(this,boost::bind(&molecule::calcFormula,this)),
+  last_atom(0),
+  InternalPointer(start)
 {
   // init atom chain list
@@ -47,8 +54,10 @@
   for(int i=MAX_ELEMENTS;i--;)
     ElementsInMolecule[i] = 0;
-  cell_size[0] = cell_size[2] = cell_size[5]= 20.;
-  cell_size[1] = cell_size[3] = cell_size[4]= 0.;
-  strcpy(name,"none");
-};
+  strcpy(name,World::getInstance().getDefaultName());
+};
+
+molecule *NewMolecule(){
+  return new molecule(World::getInstance().getPeriode());
+}
 
 /** Destructor of class molecule.
@@ -60,8 +69,12 @@
   delete(first);
   delete(last);
-  delete(end);
-  delete(start);
-};
-
+  end->getWorld()->destroyAtom(end);
+  start->getWorld()->destroyAtom(start);
+};
+
+
+void DeleteMolecule(molecule *mol){
+  delete mol;
+}
 
 // getter and setter
@@ -75,4 +88,12 @@
 }
 
+moleculeId_t molecule::getId(){
+  return id;
+}
+
+void molecule::setId(moleculeId_t _id){
+  id =_id;
+}
+
 const std::string molecule::getFormula(){
   return *formula;
@@ -80,14 +101,14 @@
 
 std::string molecule::calcFormula(){
-  int Counts[MAX_ELEMENTS];
+  std::map<atomicNumber_t,unsigned int> counts;
   stringstream sstr;
-  for (int j = 0; j<MAX_ELEMENTS;j++)
-    Counts[j] = 0;
+  periodentafel *periode = World::getInstance().getPeriode();
   for(atom *Walker = start; Walker != end; Walker = Walker->next) {
-    Counts[Walker->type->Z]++;
-  }
-  for(element* Elemental = elemente->end; Elemental != elemente->start; Elemental = Elemental->previous) {
-    if (Counts[Elemental->Z] != 0)
-      sstr << Elemental->symbol << Counts[Elemental->Z];
+    counts[Walker->type->getNumber()]++;
+  }
+  std::map<atomicNumber_t,unsigned int>::reverse_iterator iter;
+  for(iter = counts.rbegin(); iter != counts.rend(); ++iter) {
+    atomicNumber_t Z = (*iter).first;
+    sstr << periode->FindElement(Z)->symbol << (*iter).second;
   }
   return sstr.str();
@@ -135,5 +156,5 @@
   OBSERVE;
   if (pointer != NULL) {
-    atom *walker = new atom(pointer);
+    atom *walker = pointer->clone();
     walker->Name = Malloc<char>(strlen(pointer->Name) + 1, "atom::atom: *Name");
     strcpy (walker->Name, pointer->Name);
@@ -196,9 +217,9 @@
   double *matrix = NULL;
   bond *Binder = NULL;
+  double * const cell_size = World::getInstance().getDomain();
 
 //  Log() << Verbose(3) << "Begin of AddHydrogenReplacementAtom." << endl;
   // create vector in direction of bond
-  InBondvector.CopyVector(&TopReplacement->x);
-  InBondvector.SubtractVector(&TopOrigin->x);
+  InBondvector = TopReplacement->x - TopOrigin->x;
   bondlength = InBondvector.Norm();
 
@@ -212,12 +233,12 @@
     Orthovector1.Zero();
     for (int i=NDIM;i--;) {
-      l = TopReplacement->x.x[i] - TopOrigin->x.x[i];
+      l = TopReplacement->x[i] - TopOrigin->x[i];
       if (fabs(l) > BondDistance) { // is component greater than bond distance
-        Orthovector1.x[i] = (l < 0) ? -1. : +1.;
+        Orthovector1[i] = (l < 0) ? -1. : +1.;
       } // (signs are correct, was tested!)
     }
     matrix = ReturnFullMatrixforSymmetric(cell_size);
     Orthovector1.MatrixMultiplication(matrix);
-    InBondvector.SubtractVector(&Orthovector1); // subtract just the additional translation
+    InBondvector -= Orthovector1; // subtract just the additional translation
     Free(&matrix);
     bondlength = InBondvector.Norm();
@@ -231,5 +252,5 @@
   BondRescale = TopOrigin->type->HBondDistance[TopBond->BondDegree-1];
   if (BondRescale == -1) {
-    eLog() << Verbose(1) << "There is no typical hydrogen bond distance in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "There is no typical hydrogen bond distance in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl);
     return false;
     BondRescale = bondlength;
@@ -242,7 +263,7 @@
   switch(TopBond->BondDegree) {
     case 1:
-      FirstOtherAtom = new atom();    // new atom
+      FirstOtherAtom = World::getInstance().createAtom();    // new atom
       FirstOtherAtom->type = elemente->FindElement(1);  // element is Hydrogen
-      FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      FirstOtherAtom->v = TopReplacement->v; // copy velocity
       FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
       if (TopReplacement->type->Z == 1) { // neither rescale nor replace if it's already hydrogen
@@ -252,7 +273,7 @@
         FirstOtherAtom->father = NULL;  // if we replace hydrogen, we mark it as our father, otherwise we are just an added hydrogen with no father
       }
-      InBondvector.Scale(&BondRescale);   // rescale the distance vector to Hydrogen bond length
-      FirstOtherAtom->x.CopyVector(&TopOrigin->x); // set coordination to origin ...
-      FirstOtherAtom->x.AddVector(&InBondvector);  // ... and add distance vector to replacement atom
+      InBondvector *= BondRescale;   // rescale the distance vector to Hydrogen bond length
+      FirstOtherAtom->x = TopOrigin->x; // set coordination to origin ...
+      FirstOtherAtom->x = InBondvector;  // ... and add distance vector to replacement atom
       AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
 //      Log() << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
@@ -274,5 +295,5 @@
             SecondOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
           } else {
-            eLog() << Verbose(2) << "Detected more than four bonds for atom " << TopOrigin->Name;
+            DoeLog(2) && (eLog()<< Verbose(2) << "Detected more than four bonds for atom " << TopOrigin->Name);
           }
         }
@@ -286,7 +307,14 @@
 
         // determine the plane of these two with the *origin
-        AllWentWell = AllWentWell && Orthovector1.MakeNormalVector(&TopOrigin->x, &FirstOtherAtom->x, &SecondOtherAtom->x);
+        try {
+          Orthovector1 =Plane(TopOrigin->x, FirstOtherAtom->x, SecondOtherAtom->x).getNormal();
+        }
+        catch(LinearDependenceException &excp){
+          Log() << Verbose(0) << excp;
+          // TODO: figure out what to do with the Orthovector in this case
+          AllWentWell = false;
+        }
       } else {
-        Orthovector1.GetOneNormalVector(&InBondvector);
+        Orthovector1.GetOneNormalVector(InBondvector);
       }
       //Log() << Verbose(3)<< "Orthovector1: ";
@@ -294,16 +322,16 @@
       //Log() << Verbose(0) << endl;
       // orthogonal vector and bond vector between origin and replacement form the new plane
-      Orthovector1.MakeNormalVector(&InBondvector);
+      Orthovector1.MakeNormalTo(InBondvector);
       Orthovector1.Normalize();
       //Log() << Verbose(3) << "ReScaleCheck: " << Orthovector1.Norm() << " and " << InBondvector.Norm() << "." << endl;
 
       // create the two Hydrogens ...
-      FirstOtherAtom = new atom();
-      SecondOtherAtom = new atom();
+      FirstOtherAtom = World::getInstance().createAtom();
+      SecondOtherAtom = World::getInstance().createAtom();
       FirstOtherAtom->type = elemente->FindElement(1);
       SecondOtherAtom->type = elemente->FindElement(1);
-      FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      FirstOtherAtom->v = TopReplacement->v; // copy velocity
       FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
-      SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      SecondOtherAtom->v = TopReplacement->v; // copy velocity
       SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
       FirstOtherAtom->father = NULL;  // we are just an added hydrogen with no father
@@ -311,5 +339,5 @@
       bondangle = TopOrigin->type->HBondAngle[1];
       if (bondangle == -1) {
-        eLog() << Verbose(1) << "There is no typical hydrogen bond angle in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
+        DoeLog(1) && (eLog()<< Verbose(1) << "There is no typical hydrogen bond angle in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl);
         return false;
         bondangle = 0;
@@ -326,13 +354,13 @@
       SecondOtherAtom->x.Zero();
       for(int i=NDIM;i--;) { // rotate by half the bond angle in both directions (InBondvector is bondangle = 0 direction)
-        FirstOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (sin(bondangle));
-        SecondOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (-sin(bondangle));
-      }
-      FirstOtherAtom->x.Scale(&BondRescale);  // rescale by correct BondDistance
-      SecondOtherAtom->x.Scale(&BondRescale);
+        FirstOtherAtom->x[i] = InBondvector[i] * cos(bondangle) + Orthovector1[i] * (sin(bondangle));
+        SecondOtherAtom->x[i] = InBondvector[i] * cos(bondangle) + Orthovector1[i] * (-sin(bondangle));
+      }
+      FirstOtherAtom->x *= BondRescale;  // rescale by correct BondDistance
+      SecondOtherAtom->x *= BondRescale;
       //Log() << Verbose(3) << "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << "." << endl;
       for(int i=NDIM;i--;) { // and make relative to origin atom
-        FirstOtherAtom->x.x[i] += TopOrigin->x.x[i];
-        SecondOtherAtom->x.x[i] += TopOrigin->x.x[i];
+        FirstOtherAtom->x[i] += TopOrigin->x[i];
+        SecondOtherAtom->x[i] += TopOrigin->x[i];
       }
       // ... and add to molecule
@@ -354,15 +382,15 @@
     case 3:
       // take the "usual" tetraoidal angle and add the three Hydrogen in direction of the bond (height of the tetraoid)
-      FirstOtherAtom = new atom();
-      SecondOtherAtom = new atom();
-      ThirdOtherAtom = new atom();
+      FirstOtherAtom = World::getInstance().createAtom();
+      SecondOtherAtom = World::getInstance().createAtom();
+      ThirdOtherAtom = World::getInstance().createAtom();
       FirstOtherAtom->type = elemente->FindElement(1);
       SecondOtherAtom->type = elemente->FindElement(1);
       ThirdOtherAtom->type = elemente->FindElement(1);
-      FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      FirstOtherAtom->v = TopReplacement->v; // copy velocity
       FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
-      SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      SecondOtherAtom->v = TopReplacement->v; // copy velocity
       SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
-      ThirdOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      ThirdOtherAtom->v = TopReplacement->v; // copy velocity
       ThirdOtherAtom->FixedIon = TopReplacement->FixedIon;
       FirstOtherAtom->father = NULL;  //  we are just an added hydrogen with no father
@@ -371,9 +399,15 @@
 
       // we need to vectors orthonormal the InBondvector
-      AllWentWell = AllWentWell && Orthovector1.GetOneNormalVector(&InBondvector);
+      AllWentWell = AllWentWell && Orthovector1.GetOneNormalVector(InBondvector);
 //      Log() << Verbose(3) << "Orthovector1: ";
 //      Orthovector1.Output(out);
 //      Log() << Verbose(0) << endl;
-      AllWentWell = AllWentWell && Orthovector2.MakeNormalVector(&InBondvector, &Orthovector1);
+      try{
+        Orthovector2 = Plane(InBondvector, Orthovector1,0).getNormal();
+      }
+      catch(LinearDependenceException &excp) {
+        Log() << Verbose(0) << excp;
+        AllWentWell = false;
+      }
 //      Log() << Verbose(3) << "Orthovector2: ";
 //      Orthovector2.Output(out);
@@ -392,10 +426,10 @@
       factors[1] = f;
       factors[2] = 0.;
-      FirstOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
+      FirstOtherAtom->x.LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
       factors[1] = -0.5*f;
       factors[2] = g;
-      SecondOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
+      SecondOtherAtom->x.LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
       factors[2] = -g;
-      ThirdOtherAtom->x.LinearCombinationOfVectors(&InBondvector, &Orthovector1, &Orthovector2, factors);
+      ThirdOtherAtom->x.LinearCombinationOfVectors(InBondvector, Orthovector1, Orthovector2, factors);
 
       // rescale each to correct BondDistance
@@ -405,7 +439,7 @@
 
       // and relative to *origin atom
-      FirstOtherAtom->x.AddVector(&TopOrigin->x);
-      SecondOtherAtom->x.AddVector(&TopOrigin->x);
-      ThirdOtherAtom->x.AddVector(&TopOrigin->x);
+      FirstOtherAtom->x += TopOrigin->x;
+      SecondOtherAtom->x += TopOrigin->x;
+      ThirdOtherAtom->x += TopOrigin->x;
 
       // ... and add to molecule
@@ -433,5 +467,5 @@
       break;
     default:
-      eLog() << Verbose(1) << "BondDegree does not state single, double or triple bond!" << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << "BondDegree does not state single, double or triple bond!" << endl);
       AllWentWell = false;
       break;
@@ -468,12 +502,12 @@
   input = new istringstream(line);
   *input >> NumberOfAtoms;
-  Log() << Verbose(0) << "Parsing " << NumberOfAtoms << " atoms in file." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Parsing " << NumberOfAtoms << " atoms in file." << endl);
   getline(xyzfile,line,'\n'); // Read comment
-  Log() << Verbose(1) << "Comment: " << line << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Comment: " << line << endl);
 
   if (MDSteps == 0) // no atoms yet present
     MDSteps++;
   for(i=0;i<NumberOfAtoms;i++){
-    Walker = new atom;
+    Walker = World::getInstance().createAtom();
     getline(xyzfile,line,'\n');
     istringstream *item = new istringstream(line);
@@ -486,5 +520,5 @@
     Walker->type = elemente->FindElement(shorthand);
     if (Walker->type == NULL) {
-      eLog() << Verbose(1) << "Could not parse the element at line: '" << line << "', setting to H.";
+      DoeLog(1) && (eLog()<< Verbose(1) << "Could not parse the element at line: '" << line << "', setting to H.");
       Walker->type = elemente->FindElement(1);
     }
@@ -495,8 +529,8 @@
     }
     for(j=NDIM;j--;) {
-      Walker->x.x[j] = x[j];
-      Walker->Trajectory.R.at(MDSteps-1).x[j] = x[j];
-      Walker->Trajectory.U.at(MDSteps-1).x[j] = 0;
-      Walker->Trajectory.F.at(MDSteps-1).x[j] = 0;
+      Walker->x[j] = x[j];
+      Walker->Trajectory.R.at(MDSteps-1)[j] = x[j];
+      Walker->Trajectory.U.at(MDSteps-1)[j] = 0;
+      Walker->Trajectory.F.at(MDSteps-1)[j] = 0;
     }
     AddAtom(Walker);  // add to molecule
@@ -513,5 +547,5 @@
 molecule *molecule::CopyMolecule()
 {
-  molecule *copy = new molecule(elemente);
+  molecule *copy = World::getInstance().createMolecule();
   atom *LeftAtom = NULL, *RightAtom = NULL;
 
@@ -556,5 +590,5 @@
  */
 molecule* molecule::CopyMoleculeFromSubRegion(const Vector offset, const double *parallelepiped) const {
-  molecule *copy = new molecule(elemente);
+  molecule *copy = World::getInstance().createMolecule();
 
   ActOnCopyWithEachAtomIfTrue ( &molecule::AddCopyAtom, copy, &atom::IsInParallelepiped, offset, parallelepiped );
@@ -582,5 +616,5 @@
     add(Binder, last);
   } else {
-    eLog() << Verbose(1) << "Could not add bond between " << atom1->Name << " and " << atom2->Name << " as one or both are not present in the molecule." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Could not add bond between " << atom1->Name << " and " << atom2->Name << " as one or both are not present in the molecule." << endl);
   }
   return Binder;
@@ -594,5 +628,5 @@
 bool molecule::RemoveBond(bond *pointer)
 {
-  //eLog() << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
+  //DoeLog(1) && (eLog()<< Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl);
   pointer->leftatom->RegisterBond(pointer);
   pointer->rightatom->RegisterBond(pointer);
@@ -608,5 +642,5 @@
 bool molecule::RemoveBonds(atom *BondPartner)
 {
-  //eLog() << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
+  //DoeLog(1) && (eLog()<< Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl);
   BondList::const_iterator ForeRunner;
   while (!BondPartner->ListOfBonds.empty()) {
@@ -642,10 +676,11 @@
 void molecule::SetBoxDimension(Vector *dim)
 {
-  cell_size[0] = dim->x[0];
+  double * const cell_size = World::getInstance().getDomain();
+  cell_size[0] = dim->at(0);
   cell_size[1] = 0.;
-  cell_size[2] = dim->x[1];
+  cell_size[2] = dim->at(1);
   cell_size[3] = 0.;
   cell_size[4] = 0.;
-  cell_size[5] = dim->x[2];
+  cell_size[5] = dim->at(2);
 };
 
@@ -660,5 +695,5 @@
     AtomCount--;
   } else
-    eLog() << Verbose(1) << "Atom " << pointer->Name << " is of element " << pointer->type->Z << " but the entry in the table of the molecule is 0!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Atom " << pointer->Name << " is of element " << pointer->type->Z << " but the entry in the table of the molecule is 0!" << endl);
   if (ElementsInMolecule[pointer->type->Z] == 0)  // was last atom of this element?
     ElementCount--;
@@ -678,5 +713,5 @@
     ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
   else
-    eLog() << Verbose(1) << "Atom " << pointer->Name << " is of element " << pointer->type->Z << " but the entry in the table of the molecule is 0!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Atom " << pointer->Name << " is of element " << pointer->type->Z << " but the entry in the table of the molecule is 0!" << endl);
   if (ElementsInMolecule[pointer->type->Z] == 0)  // was last atom of this element?
     ElementCount--;
@@ -703,5 +738,5 @@
     return walker;
   } else {
-    Log() << Verbose(0) << "Atom not found in list." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Atom not found in list." << endl);
     return NULL;
   }
@@ -719,5 +754,5 @@
     //mol->Output((ofstream *)&cout);
     //Log() << Verbose(0) << "===============================================" << endl;
-    Log() << Verbose(0) << text;
+    DoLog(0) && (Log() << Verbose(0) << text);
     cin >> No;
     ion = this->FindAtom(No);
@@ -732,9 +767,10 @@
 bool molecule::CheckBounds(const Vector *x) const
 {
+  double * const cell_size = World::getInstance().getDomain();
   bool result = true;
   int j =-1;
   for (int i=0;i<NDIM;i++) {
     j += i+1;
-    result = result && ((x->x[i] >= 0) && (x->x[i] < cell_size[j]));
+    result = result && ((x->at(i) >= 0) && (x->at(i) < cell_size[j]));
   }
   //return result;
@@ -807,7 +843,7 @@
 void molecule::OutputListOfBonds() const
 {
-  Log() << Verbose(2) << endl << "From Contents of ListOfBonds, all non-hydrogen atoms:" << endl;
+  DoLog(2) && (Log() << Verbose(2) << endl << "From Contents of ListOfBonds, all non-hydrogen atoms:" << endl);
   ActOnAllAtoms (&atom::OutputBondOfAtom );
-  Log() << Verbose(0) << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
 };
 
@@ -866,5 +902,5 @@
   }
   if ((AtomCount == 0) || (i != AtomCount)) {
-    Log() << Verbose(3) << "Mismatch in AtomCount " << AtomCount << " and recounted number " << i << ", renaming all." << endl;
+    DoLog(3) && (Log() << Verbose(3) << "Mismatch in AtomCount " << AtomCount << " and recounted number " << i << ", renaming all." << endl);
     AtomCount = i;
 
@@ -882,9 +918,9 @@
         Walker->Name = Malloc<char>(6, "molecule::CountAtoms: *walker->Name");
         sprintf(Walker->Name, "%2s%02d", Walker->type->symbol, Walker->nr+1);
-        Log() << Verbose(3) << "Naming atom nr. " << Walker->nr << " " << Walker->Name << "." << endl;
+        DoLog(3) && (Log() << Verbose(3) << "Naming atom nr. " << Walker->nr << " " << Walker->Name << "." << endl);
         i++;
       }
     } else
-      Log() << Verbose(3) << "AtomCount is still " << AtomCount << ", thus counting nothing." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "AtomCount is still " << AtomCount << ", thus counting nothing." << endl);
   }
 };
@@ -946,5 +982,5 @@
   bool result = true; // status of comparison
 
-  Log() << Verbose(3) << "Begin of IsEqualToWithinThreshold." << endl;
+  DoLog(3) && (Log() << Verbose(3) << "Begin of IsEqualToWithinThreshold." << endl);
   /// first count both their atoms and elements and update lists thereby ...
   //Log() << Verbose(0) << "Counting atoms, updating list" << endl;
@@ -958,5 +994,5 @@
   if (result) {
     if (AtomCount != OtherMolecule->AtomCount) {
-      Log() << Verbose(4) << "AtomCounts don't match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
+      DoLog(4) && (Log() << Verbose(4) << "AtomCounts don't match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl);
       result = false;
     } else Log() << Verbose(4) << "AtomCounts match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
@@ -965,5 +1001,5 @@
   if (result) {
     if (ElementCount != OtherMolecule->ElementCount) {
-      Log() << Verbose(4) << "ElementCount don't match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
+      DoLog(4) && (Log() << Verbose(4) << "ElementCount don't match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl);
       result = false;
     } else Log() << Verbose(4) << "ElementCount match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
@@ -977,5 +1013,5 @@
     }
     if (flag < MAX_ELEMENTS) {
-      Log() << Verbose(4) << "ElementsInMolecule don't match." << endl;
+      DoLog(4) && (Log() << Verbose(4) << "ElementsInMolecule don't match." << endl);
       result = false;
     } else Log() << Verbose(4) << "ElementsInMolecule match." << endl;
@@ -983,14 +1019,11 @@
   /// then determine and compare center of gravity for each molecule ...
   if (result) {
-    Log() << Verbose(5) << "Calculating Centers of Gravity" << endl;
+    DoLog(5) && (Log() << Verbose(5) << "Calculating Centers of Gravity" << endl);
     DeterminePeriodicCenter(CenterOfGravity);
     OtherMolecule->DeterminePeriodicCenter(OtherCenterOfGravity);
-    Log() << Verbose(5) << "Center of Gravity: ";
-    CenterOfGravity.Output();
-    Log() << Verbose(0) << endl << Verbose(5) << "Other Center of Gravity: ";
-    OtherCenterOfGravity.Output();
-    Log() << Verbose(0) << endl;
-    if (CenterOfGravity.DistanceSquared(&OtherCenterOfGravity) > threshold*threshold) {
-      Log() << Verbose(4) << "Centers of gravity don't match." << endl;
+    DoLog(5) && (Log() << Verbose(5) << "Center of Gravity: " << CenterOfGravity << endl);
+    DoLog(5) && (Log() << Verbose(5) << "Other Center of Gravity: " << OtherCenterOfGravity << endl);
+    if (CenterOfGravity.DistanceSquared(OtherCenterOfGravity) > threshold*threshold) {
+      DoLog(4) && (Log() << Verbose(4) << "Centers of gravity don't match." << endl);
       result = false;
     }
@@ -999,5 +1032,5 @@
   /// ... then make a list with the euclidian distance to this center for each atom of both molecules
   if (result) {
-    Log() << Verbose(5) << "Calculating distances" << endl;
+    DoLog(5) && (Log() << Verbose(5) << "Calculating distances" << endl);
     Distances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: Distances");
     OtherDistances = Calloc<double>(AtomCount, "molecule::IsEqualToWithinThreshold: OtherDistances");
@@ -1006,5 +1039,5 @@
 
     /// ... sort each list (using heapsort (o(N log N)) from GSL)
-    Log() << Verbose(5) << "Sorting distances" << endl;
+    DoLog(5) && (Log() << Verbose(5) << "Sorting distances" << endl);
     PermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermMap");
     OtherPermMap = Calloc<size_t>(AtomCount, "molecule::IsEqualToWithinThreshold: *OtherPermMap");
@@ -1012,13 +1045,13 @@
     gsl_heapsort_index (OtherPermMap, OtherDistances, AtomCount, sizeof(double), CompareDoubles);
     PermutationMap = Calloc<int>(AtomCount, "molecule::IsEqualToWithinThreshold: *PermutationMap");
-    Log() << Verbose(5) << "Combining Permutation Maps" << endl;
+    DoLog(5) && (Log() << Verbose(5) << "Combining Permutation Maps" << endl);
     for(int i=AtomCount;i--;)
       PermutationMap[PermMap[i]] = (int) OtherPermMap[i];
 
     /// ... and compare them step by step, whether the difference is individually(!) below \a threshold for all
-    Log() << Verbose(4) << "Comparing distances" << endl;
+    DoLog(4) && (Log() << Verbose(4) << "Comparing distances" << endl);
     flag = 0;
     for (int i=0;i<AtomCount;i++) {
-      Log() << Verbose(5) << "Distances squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " <<  threshold << endl;
+      DoLog(5) && (Log() << Verbose(5) << "Distances squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " <<  threshold << endl);
       if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold*threshold)
         flag = 1;
@@ -1036,10 +1069,10 @@
   }
   /// return pointer to map if all distances were below \a threshold
-  Log() << Verbose(3) << "End of IsEqualToWithinThreshold." << endl;
+  DoLog(3) && (Log() << Verbose(3) << "End of IsEqualToWithinThreshold." << endl);
   if (result) {
-    Log() << Verbose(3) << "Result: Equal." << endl;
+    DoLog(3) && (Log() << Verbose(3) << "Result: Equal." << endl);
     return PermutationMap;
   } else {
-    Log() << Verbose(3) << "Result: Not equal." << endl;
+    DoLog(3) && (Log() << Verbose(3) << "Result: Not equal." << endl);
     return NULL;
   }
@@ -1056,5 +1089,5 @@
 {
   atom *Walker = NULL, *OtherWalker = NULL;
-  Log() << Verbose(3) << "Begin of GetFatherAtomicMap." << endl;
+  DoLog(3) && (Log() << Verbose(3) << "Begin of GetFatherAtomicMap." << endl);
   int *AtomicMap = Malloc<int>(AtomCount, "molecule::GetAtomicMap: *AtomicMap");
   for (int i=AtomCount;i--;)
@@ -1063,7 +1096,7 @@
     for (int i=AtomCount;i--;) // no need as -1 means already that there is trivial correspondence
       AtomicMap[i] = i;
-    Log() << Verbose(4) << "Map is trivial." << endl;
+    DoLog(4) && (Log() << Verbose(4) << "Map is trivial." << endl);
   } else {
-    Log() << Verbose(4) << "Map is ";
+    DoLog(4) && (Log() << Verbose(4) << "Map is ");
     Walker = start;
     while (Walker->next != end) {
@@ -1082,9 +1115,9 @@
         }
       }
-      Log() << Verbose(0) << AtomicMap[Walker->nr] << "\t";
-    }
-    Log() << Verbose(0) << endl;
-  }
-  Log() << Verbose(3) << "End of GetFatherAtomicMap." << endl;
+      DoLog(0) && (Log() << Verbose(0) << AtomicMap[Walker->nr] << "\t");
+    }
+    DoLog(0) && (Log() << Verbose(0) << endl);
+  }
+  DoLog(3) && (Log() << Verbose(3) << "End of GetFatherAtomicMap." << endl);
   return AtomicMap;
 };
Index: src/molecule.hpp
===================================================================
--- src/molecule.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/molecule.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -29,4 +29,5 @@
 #include <string>
 
+#include "defs.hpp"
 #include "graph.hpp"
 #include "stackclass.hpp"
@@ -85,6 +86,7 @@
  */
 class molecule : public PointCloud , public Observable {
+  friend molecule *NewMolecule();
+  friend void DeleteMolecule(molecule *);
   public:
-    double cell_size[6];//!< cell size
     const periodentafel * const elemente; //!< periodic table with each element
     atom *start;        //!< start of atom list
@@ -108,14 +110,19 @@
   private:
     Cacheable<string> formula;
+    moleculeId_t id;
+  protected:
+    molecule(const periodentafel * const teil);
+    virtual ~molecule();
+
 
 public:
-  molecule(const periodentafel * const teil);
-  virtual ~molecule();
-
   //getter and setter
   const std::string getName();
+  moleculeId_t getId();
+  void setId(moleculeId_t);
   void setName(const std::string);
   const std::string getFormula();
   std::string calcFormula();
+
 
   // re-definition of virtual functions from PointCloud
@@ -137,4 +144,6 @@
   template <typename res, typename T> void ActOnAllVectors( res (Vector::*f)(T), T t ) const;
   template <typename res, typename T> void ActOnAllVectors( res (Vector::*f)(T) const, T t ) const;
+  template <typename res, typename T> void ActOnAllVectors( res (Vector::*f)(T&), T &t ) const;
+  template <typename res, typename T> void ActOnAllVectors( res (Vector::*f)(T&) const, T &t ) const;
   template <typename res, typename T, typename U> void ActOnAllVectors( res (Vector::*f)(T, U), T t, U u ) const;
   template <typename res, typename T, typename U> void ActOnAllVectors( res (Vector::*f)(T, U) const, T t, U u ) const;
@@ -283,6 +292,6 @@
   int FragmentMolecule(int Order, config *configuration);
   bool CheckOrderAtSite(bool *AtomMask, Graph *GlobalKeySetList, int Order, int *MinimumRingSize, char *path = NULL);
-  bool StoreBondsToFile(char *path);
-  bool StoreAdjacencyToFile(char *path);
+  bool StoreBondsToFile(char *path, char *filename);
+  bool StoreAdjacencyToFile(char *path, char *filename);
   bool CheckAdjacencyFileAgainstMolecule(char *path, atom **ListOfAtoms);
   bool ParseOrderAtSiteFromFile(char *path);
@@ -321,4 +330,7 @@
 };
 
+molecule *NewMolecule();
+void DeleteMolecule(molecule* mol);
+
 #include "molecule_template.hpp"
 
@@ -330,5 +342,5 @@
     int MaxIndex;
 
-  MoleculeListClass();
+  MoleculeListClass(World *world);
   ~MoleculeListClass();
 
@@ -339,5 +351,5 @@
   bool OutputConfigForListOfFragments(config *configuration, int *SortIndex);
   int NumberOfActiveMolecules();
-  void Enumerate(ofstream *out);
+  void Enumerate(ostream *out);
   void Output(ofstream *out);
   void DissectMoleculeIntoConnectedSubgraphs(const periodentafel * const periode, config * const configuration);
@@ -363,4 +375,5 @@
 
   private:
+  World *world; //!< The world this List belongs to. Needed to avoid deadlocks in the destructor
 };
 
Index: src/molecule_dynamics.cpp
===================================================================
--- src/molecule_dynamics.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/molecule_dynamics.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -6,4 +6,5 @@
  */
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "config.hpp"
@@ -13,4 +14,5 @@
 #include "molecule.hpp"
 #include "parser.hpp"
+#include "Plane.hpp"
 
 /************************************* Functions for class molecule *********************************/
@@ -37,36 +39,32 @@
     // determine normalized trajectories direction vector (n1, n2)
     Sprinter = Params.PermutationMap[Walker->nr];   // find first target point
-    trajectory1.CopyVector(&Sprinter->Trajectory.R.at(Params.endstep));
-    trajectory1.SubtractVector(&Walker->Trajectory.R.at(Params.startstep));
+    trajectory1 = Sprinter->Trajectory.R.at(Params.endstep) - Walker->Trajectory.R.at(Params.startstep);
     trajectory1.Normalize();
     Norm1 = trajectory1.Norm();
     Sprinter = Params.PermutationMap[Runner->nr];   // find second target point
-    trajectory2.CopyVector(&Sprinter->Trajectory.R.at(Params.endstep));
-    trajectory2.SubtractVector(&Runner->Trajectory.R.at(Params.startstep));
+    trajectory2 = Sprinter->Trajectory.R.at(Params.endstep) - Runner->Trajectory.R.at(Params.startstep);
     trajectory2.Normalize();
     Norm2 = trajectory1.Norm();
     // check whether either is zero()
     if ((Norm1 < MYEPSILON) && (Norm2 < MYEPSILON)) {
-      tmp = Walker->Trajectory.R.at(Params.startstep).Distance(&Runner->Trajectory.R.at(Params.startstep));
+      tmp = Walker->Trajectory.R.at(Params.startstep).distance(Runner->Trajectory.R.at(Params.startstep));
     } else if (Norm1 < MYEPSILON) {
       Sprinter = Params.PermutationMap[Walker->nr];   // find first target point
-      trajectory1.CopyVector(&Sprinter->Trajectory.R.at(Params.endstep));  // copy first offset
-      trajectory1.SubtractVector(&Runner->Trajectory.R.at(Params.startstep));  // subtract second offset
-      trajectory2.Scale( trajectory1.ScalarProduct(&trajectory2) ); // trajectory2 is scaled to unity, hence we don't need to divide by anything
-      trajectory1.SubtractVector(&trajectory2);   // project the part in norm direction away
+      trajectory1 = Sprinter->Trajectory.R.at(Params.endstep) - Runner->Trajectory.R.at(Params.startstep);
+      trajectory2 *= trajectory1.ScalarProduct(trajectory2); // trajectory2 is scaled to unity, hence we don't need to divide by anything
+      trajectory1 -= trajectory2;   // project the part in norm direction away
       tmp = trajectory1.Norm();  // remaining norm is distance
     } else if (Norm2 < MYEPSILON) {
       Sprinter = Params.PermutationMap[Runner->nr];   // find second target point
-      trajectory2.CopyVector(&Sprinter->Trajectory.R.at(Params.endstep));  // copy second offset
-      trajectory2.SubtractVector(&Walker->Trajectory.R.at(Params.startstep));  // subtract first offset
-      trajectory1.Scale( trajectory2.ScalarProduct(&trajectory1) ); // trajectory1 is scaled to unity, hence we don't need to divide by anything
-      trajectory2.SubtractVector(&trajectory1);   // project the part in norm direction away
+      trajectory2 = Sprinter->Trajectory.R.at(Params.endstep) - Walker->Trajectory.R.at(Params.startstep);  // copy second offset
+      trajectory1 *= trajectory2.ScalarProduct(trajectory1); // trajectory1 is scaled to unity, hence we don't need to divide by anything
+      trajectory2 -= trajectory1;   // project the part in norm direction away
       tmp = trajectory2.Norm();  // remaining norm is distance
-    } else if ((fabs(trajectory1.ScalarProduct(&trajectory2)/Norm1/Norm2) - 1.) < MYEPSILON) { // check whether they're linear dependent
+    } else if ((fabs(trajectory1.ScalarProduct(trajectory2)/Norm1/Norm2) - 1.) < MYEPSILON) { // check whether they're linear dependent
   //        Log() << Verbose(3) << "Both trajectories of " << *Walker << " and " << *Runner << " are linear dependent: ";
   //        Log() << Verbose(0) << trajectory1;
   //        Log() << Verbose(0) << " and ";
   //        Log() << Verbose(0) << trajectory2;
-      tmp = Walker->Trajectory.R.at(Params.startstep).Distance(&Runner->Trajectory.R.at(Params.startstep));
+      tmp = Walker->Trajectory.R.at(Params.startstep).distance(Runner->Trajectory.R.at(Params.startstep));
   //        Log() << Verbose(0) << " with distance " << tmp << "." << endl;
     } else { // determine distance by finding minimum distance
@@ -78,5 +76,5 @@
   //        Log() << Verbose(0) << trajectory2 << endl;
       // determine normal vector for both
-      normal.MakeNormalVector(&trajectory1, &trajectory2);
+      normal = Plane(trajectory1, trajectory2,0).getNormal();
       // print all vectors for debugging
   //        Log() << Verbose(0) << "Normal vector in between: ";
@@ -84,8 +82,8 @@
       // setup matrix
       for (int i=NDIM;i--;) {
-        gsl_matrix_set(A, 0, i, trajectory1.x[i]);
-        gsl_matrix_set(A, 1, i, trajectory2.x[i]);
-        gsl_matrix_set(A, 2, i, normal.x[i]);
-        gsl_vector_set(x,i, (Walker->Trajectory.R.at(Params.startstep).x[i] - Runner->Trajectory.R.at(Params.startstep).x[i]));
+        gsl_matrix_set(A, 0, i, trajectory1[i]);
+        gsl_matrix_set(A, 1, i, trajectory2[i]);
+        gsl_matrix_set(A, 2, i, normal[i]);
+        gsl_vector_set(x,i, (Walker->Trajectory.R.at(Params.startstep)[i] - Runner->Trajectory.R.at(Params.startstep)[i]));
       }
       // solve the linear system by Householder transformations
@@ -95,12 +93,9 @@
   //        Log() << Verbose(0) << " with distance " << tmp << "." << endl;
       // test whether we really have the intersection (by checking on c_1 and c_2)
-      TestVector.CopyVector(&Runner->Trajectory.R.at(Params.startstep));
+      trajectory1.Scale(gsl_vector_get(x,0));
       trajectory2.Scale(gsl_vector_get(x,1));
-      TestVector.AddVector(&trajectory2);
       normal.Scale(gsl_vector_get(x,2));
-      TestVector.AddVector(&normal);
-      TestVector.SubtractVector(&Walker->Trajectory.R.at(Params.startstep));
-      trajectory1.Scale(gsl_vector_get(x,0));
-      TestVector.SubtractVector(&trajectory1);
+      TestVector = Runner->Trajectory.R.at(Params.startstep) + trajectory2 + normal
+                   - (Walker->Trajectory.R.at(Params.startstep) + trajectory1);
       if (TestVector.Norm() < MYEPSILON) {
   //          Log() << Verbose(2) << "Test: ok.\tDistance of " << tmp << " is correct." << endl;
@@ -162,6 +157,6 @@
 double molecule::ConstrainedPotential(struct EvaluatePotential &Params)
 {
-  double tmp, result;
-
+  double tmp = 0.;
+  double result = 0.;
   // go through every atom
   atom *Runner = NULL;
@@ -171,5 +166,5 @@
     // first term: distance to target
     Runner = Params.PermutationMap[Walker->nr];   // find target point
-    tmp = (Walker->Trajectory.R.at(Params.startstep).Distance(&Runner->Trajectory.R.at(Params.endstep)));
+    tmp = (Walker->Trajectory.R.at(Params.startstep).distance(Runner->Trajectory.R.at(Params.endstep)));
     tmp *= Params.IsAngstroem ? 1. : 1./AtomicLengthToAngstroem;
     result += Params.PenaltyConstants[0] * tmp;
@@ -207,5 +202,5 @@
     doubles++;
   if (doubles >0)
-    Log() << Verbose(2) << "Found " << doubles << " Doubles." << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Found " << doubles << " Doubles." << endl);
   Free(&DoubleList);
 //  Log() << Verbose(2) << zeile1.str() << endl << zeile2.str() << endl;
@@ -230,5 +225,5 @@
     while(Runner->next != mol->end) {
       Runner = Runner->next;
-      Params.DistanceList[Walker->nr]->insert( DistancePair(Walker->Trajectory.R.at(Params.startstep).Distance(&Runner->Trajectory.R.at(Params.endstep)), Runner) );
+      Params.DistanceList[Walker->nr]->insert( DistancePair(Walker->Trajectory.R.at(Params.startstep).distance(Runner->Trajectory.R.at(Params.endstep)), Runner) );
     }
   }
@@ -249,5 +244,5 @@
     Params.DoubleList[Params.DistanceList[Walker->nr]->begin()->second->nr]++;            // increase this target's source count (>1? not injective)
     Params.DistanceIterators[Walker->nr] = Params.DistanceList[Walker->nr]->begin();    // and remember which one we picked
-    Log() << Verbose(2) << *Walker << " starts with distance " << Params.DistanceList[Walker->nr]->begin()->first << "." << endl;
+    DoLog(2) && (Log() << Verbose(2) << *Walker << " starts with distance " << Params.DistanceList[Walker->nr]->begin()->first << "." << endl);
   }
 };
@@ -277,5 +272,5 @@
       Params.DistanceIterators[Walker->nr] = NewBase;
       OldPotential = Potential;
-      Log() << Verbose(3) << "Found a new permutation, new potential is " << OldPotential << "." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "Found a new permutation, new potential is " << OldPotential << "." << endl);
     }
   }
@@ -306,8 +301,8 @@
   for (int i=mol->AtomCount; i--;) // now each single entry in the DoubleList should be <=1
     if (Params.DoubleList[i] > 1) {
-      eLog() << Verbose(0) << "Failed to create an injective PermutationMap!" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Failed to create an injective PermutationMap!" << endl);
       performCriticalExit();
     }
-  Log() << Verbose(1) << "done." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "done." << endl);
 };
 
@@ -358,5 +353,5 @@
   Params.PenaltyConstants[2] = 1e+7;    // just a huge penalty
   // generate the distance list
-  Log() << Verbose(1) << "Allocating, initializting and filling the distance list ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Allocating, initializting and filling the distance list ... " << endl);
   FillDistanceList(this, Params);
 
@@ -365,14 +360,14 @@
 
   // make the PermutationMap injective by checking whether we have a non-zero constants[2] term in it
-  Log() << Verbose(1) << "Making the PermutationMap injective ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Making the PermutationMap injective ... " << endl);
   MakeInjectivePermutation(this, Params);
   Free(&Params.DoubleList);
 
   // argument minimise the constrained potential in this injective PermutationMap
-  Log() << Verbose(1) << "Argument minimising the PermutationMap." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Argument minimising the PermutationMap." << endl);
   OldPotential = 1e+10;
   round = 0;
   do {
-    Log() << Verbose(2) << "Starting round " << ++round << ", at current potential " << OldPotential << " ... " << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Starting round " << ++round << ", at current potential " << OldPotential << " ... " << endl);
     OlderPotential = OldPotential;
     do {
@@ -424,14 +419,14 @@
             } else {
               Params.DistanceIterators[Runner->nr] = Rider;  // if successful also move the pointer in the iterator list
-              Log() << Verbose(3) << "Found a better permutation, new potential is " << Potential << " vs." << OldPotential << "." << endl;
+              DoLog(3) && (Log() << Verbose(3) << "Found a better permutation, new potential is " << Potential << " vs." << OldPotential << "." << endl);
               OldPotential = Potential;
             }
             if (Potential > Params.PenaltyConstants[2]) {
-              eLog() << Verbose(1) << "The two-step permutation procedure did not maintain injectivity!" << endl;
+              DoeLog(1) && (eLog()<< Verbose(1) << "The two-step permutation procedure did not maintain injectivity!" << endl);
               exit(255);
             }
             //Log() << Verbose(0) << endl;
           } else {
-            eLog() << Verbose(1) << *Runner << " was not the owner of " << *Sprinter << "!" << endl;
+            DoeLog(1) && (eLog()<< Verbose(1) << *Runner << " was not the owner of " << *Sprinter << "!" << endl);
             exit(255);
           }
@@ -443,5 +438,5 @@
     } while (Walker->next != end);
   } while ((OlderPotential - OldPotential) > 1e-3);
-  Log() << Verbose(1) << "done." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "done." << endl);
 
 
@@ -466,7 +461,7 @@
 {
   /// evaluate forces (only the distance to target dependent part) with the final PermutationMap
-  Log() << Verbose(1) << "Calculating forces and adding onto ForceMatrix ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Calculating forces and adding onto ForceMatrix ... " << endl);
   ActOnAllAtoms( &atom::EvaluateConstrainedForce, startstep, endstep, PermutationMap, Force );
-  Log() << Verbose(1) << "done." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "done." << endl);
 };
 
@@ -485,5 +480,5 @@
   bool status = true;
   int MaxSteps = configuration.MaxOuterStep;
-  MoleculeListClass *MoleculePerStep = new MoleculeListClass();
+  MoleculeListClass *MoleculePerStep = new MoleculeListClass(World::getPointer());
   // Get the Permutation Map by MinimiseConstrainedPotential
   atom **PermutationMap = NULL;
@@ -503,7 +498,7 @@
 
   // go through all steps and add the molecular configuration to the list and to the Trajectories of \a this molecule
-  Log() << Verbose(1) << "Filling intermediate " << MaxSteps << " steps with MDSteps of " << MDSteps << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Filling intermediate " << MaxSteps << " steps with MDSteps of " << MDSteps << "." << endl);
   for (int step = 0; step <= MaxSteps; step++) {
-    mol = new molecule(elemente);
+    mol = World::getInstance().createMolecule();
     MoleculePerStep->insert(mol);
     Walker = start;
@@ -513,11 +508,11 @@
       Sprinter = mol->AddCopyAtom(Walker);
       for (int n=NDIM;n--;) {
-        Sprinter->x.x[n] = Walker->Trajectory.R.at(startstep).x[n] + (PermutationMap[Walker->nr]->Trajectory.R.at(endstep).x[n] - Walker->Trajectory.R.at(startstep).x[n])*((double)step/(double)MaxSteps);
+        Sprinter->x[n] = Walker->Trajectory.R.at(startstep)[n] + (PermutationMap[Walker->nr]->Trajectory.R.at(endstep)[n] - Walker->Trajectory.R.at(startstep)[n])*((double)step/(double)MaxSteps);
         // add to Trajectories
         //Log() << Verbose(3) << step << ">=" << MDSteps-1 << endl;
         if (step < MaxSteps) {
-          Walker->Trajectory.R.at(step).x[n] = Walker->Trajectory.R.at(startstep).x[n] + (PermutationMap[Walker->nr]->Trajectory.R.at(endstep).x[n] - Walker->Trajectory.R.at(startstep).x[n])*((double)step/(double)MaxSteps);
-          Walker->Trajectory.U.at(step).x[n] = 0.;
-          Walker->Trajectory.F.at(step).x[n] = 0.;
+          Walker->Trajectory.R.at(step)[n] = Walker->Trajectory.R.at(startstep)[n] + (PermutationMap[Walker->nr]->Trajectory.R.at(endstep)[n] - Walker->Trajectory.R.at(startstep)[n])*((double)step/(double)MaxSteps);
+          Walker->Trajectory.U.at(step)[n] = 0.;
+          Walker->Trajectory.F.at(step)[n] = 0.;
         }
       }
@@ -568,10 +563,10 @@
     // parse file into ForceMatrix
     if (!Force.ParseMatrix(file, 0,0,0)) {
-      eLog() << Verbose(0) << "Could not parse Force Matrix file " << file << "." << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Could not parse Force Matrix file " << file << "." << endl);
       performCriticalExit();
       return false;
     }
     if (Force.RowCounter[0] != AtomCount) {
-      eLog() << Verbose(0) << "Mismatch between number of atoms in file " << Force.RowCounter[0] << " and in molecule " << AtomCount << "." << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Mismatch between number of atoms in file " << Force.RowCounter[0] << " and in molecule " << AtomCount << "." << endl);
       performCriticalExit();
       return false;
@@ -581,9 +576,9 @@
     for(int i=0;i<AtomCount;i++)
       for(int d=0;d<NDIM;d++) {
-        Velocity.x[d] += Force.Matrix[0][i][d+5];
+        Velocity[d] += Force.Matrix[0][i][d+5];
       }
     for(int i=0;i<AtomCount;i++)
       for(int d=0;d<NDIM;d++) {
-        Force.Matrix[0][i][d+5] -= Velocity.x[d]/(double)AtomCount;
+        Force.Matrix[0][i][d+5] -= Velocity[d]/(double)AtomCount;
       }
     // solve a constrained potential if we are meant to
@@ -652,22 +647,22 @@
   switch(Thermostat) {
      case None:
-      Log() << Verbose(2) <<  "Applying no thermostat..." << endl;
+      DoLog(2) && (Log() << Verbose(2) <<  "Applying no thermostat..." << endl);
       break;
      case Woodcock:
       if ((configuration.ScaleTempStep > 0) && ((MDSteps-1) % configuration.ScaleTempStep == 0)) {
-        Log() << Verbose(2) <<  "Applying Woodcock thermostat..." << endl;
+        DoLog(2) && (Log() << Verbose(2) <<  "Applying Woodcock thermostat..." << endl);
         ActOnAllAtoms( &atom::Thermostat_Woodcock, sqrt(ScaleTempFactor), MDSteps, &ekin );
       }
       break;
      case Gaussian:
-      Log() << Verbose(2) <<  "Applying Gaussian thermostat..." << endl;
+      DoLog(2) && (Log() << Verbose(2) <<  "Applying Gaussian thermostat..." << endl);
       ActOnAllAtoms( &atom::Thermostat_Gaussian_init, MDSteps, &G, &E );
 
-      Log() << Verbose(1) << "Gaussian Least Constraint constant is " << G/E << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Gaussian Least Constraint constant is " << G/E << "." << endl);
       ActOnAllAtoms( &atom::Thermostat_Gaussian_least_constraint, MDSteps, G/E, &ekin, &configuration);
 
       break;
      case Langevin:
-      Log() << Verbose(2) <<  "Applying Langevin thermostat..." << endl;
+      DoLog(2) && (Log() << Verbose(2) <<  "Applying Langevin thermostat..." << endl);
       // init random number generator
       gsl_rng_env_setup();
@@ -679,10 +674,10 @@
 
      case Berendsen:
-      Log() << Verbose(2) <<  "Applying Berendsen-VanGunsteren thermostat..." << endl;
+      DoLog(2) && (Log() << Verbose(2) <<  "Applying Berendsen-VanGunsteren thermostat..." << endl);
       ActOnAllAtoms( &atom::Thermostat_Berendsen, MDSteps, ScaleTempFactor, &ekin, &configuration );
       break;
 
      case NoseHoover:
-      Log() << Verbose(2) <<  "Applying Nose-Hoover thermostat..." << endl;
+      DoLog(2) && (Log() << Verbose(2) <<  "Applying Nose-Hoover thermostat..." << endl);
       // dynamically evolve alpha (the additional degree of freedom)
       delta_alpha = 0.;
@@ -690,9 +685,9 @@
       delta_alpha = (delta_alpha - (3.*AtomCount+1.) * configuration.TargetTemp)/(configuration.HooverMass*Units2Electronmass);
       configuration.alpha += delta_alpha*configuration.Deltat;
-      Log() << Verbose(3) << "alpha = " << delta_alpha << " * " << configuration.Deltat << " = " << configuration.alpha << "." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "alpha = " << delta_alpha << " * " << configuration.Deltat << " = " << configuration.alpha << "." << endl);
       // apply updated alpha as additional force
       ActOnAllAtoms( &atom::Thermostat_NoseHoover_scale, MDSteps, &ekin, &configuration );
       break;
   }
-  Log() << Verbose(1) << "Kinetic energy is " << ekin << "." << endl;
-};
+  DoLog(1) && (Log() << Verbose(1) << "Kinetic energy is " << ekin << "." << endl);
+};
Index: src/molecule_fragmentation.cpp
===================================================================
--- src/molecule_fragmentation.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/molecule_fragmentation.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -8,4 +8,5 @@
 #include <cstring>
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
@@ -18,4 +19,5 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
+#include "World.hpp"
 
 /************************************* Functions for class molecule *********************************/
@@ -43,5 +45,5 @@
   }
   FragmentCount = NoNonHydrogen*(1 << (c*order));
-  Log() << Verbose(1) << "Upper limit for this subgraph is " << FragmentCount << " for " << NoNonHydrogen << " non-H atoms with maximum bond degree of " << c << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Upper limit for this subgraph is " << FragmentCount << " for " << NoNonHydrogen << " non-H atoms with maximum bond degree of " << c << "." << endl);
   return FragmentCount;
 };
@@ -67,9 +69,9 @@
     } // else it's "-1" or else and thus must not be added
   }
-  Log() << Verbose(1) << "The scanned KeySet is ";
+  DoLog(1) && (Log() << Verbose(1) << "The scanned KeySet is ");
   for(KeySet::iterator runner = CurrentSet.begin(); runner != CurrentSet.end(); runner++) {
-    Log() << Verbose(0) << (*runner) << "\t";
-  }
-  Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << (*runner) << "\t");
+  }
+  DoLog(0) && (Log() << Verbose(0) << endl);
   return (status != 0);
 };
@@ -99,5 +101,5 @@
 
   // 1st pass: open file and read
-  Log() << Verbose(1) << "Parsing the KeySet file ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Parsing the KeySet file ... " << endl);
   sprintf(filename, "%s/%s%s", path, FRAGMENTPREFIX, KEYSETFILE);
   InputFile.open(filename);
@@ -112,5 +114,5 @@
         testGraphInsert = FragmentList->insert(GraphPair (CurrentSet,pair<int,double>(NumberOfFragments++,1)));  // store fragment number and current factor
         if (!testGraphInsert.second) {
-          eLog() << Verbose(0) << "KeySet file must be corrupt as there are two equal key sets therein!" << endl;
+          DoeLog(0) && (eLog()<< Verbose(0) << "KeySet file must be corrupt as there are two equal key sets therein!" << endl);
           performCriticalExit();
         }
@@ -121,7 +123,7 @@
     InputFile.clear();
     Free(&buffer);
-    Log() << Verbose(1) << "done." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
   } else {
-    Log() << Verbose(1) << "File " << filename << " not found." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "File " << filename << " not found." << endl);
     status = false;
   }
@@ -153,5 +155,5 @@
 
   // 2nd pass: open TEFactors file and read
-  Log() << Verbose(1) << "Parsing the TEFactors file ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Parsing the TEFactors file ... " << endl);
   sprintf(filename, "%s/%s%s", path, FRAGMENTPREFIX, TEFACTORSFILE);
   InputFile.open(filename);
@@ -163,5 +165,5 @@
         InputFile >> TEFactor;
         (*runner).second.second = TEFactor;
-        Log() << Verbose(2) << "Setting " << ++NumberOfFragments << " fragment's TEFactor to " << (*runner).second.second << "." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Setting " << ++NumberOfFragments << " fragment's TEFactor to " << (*runner).second.second << "." << endl);
       } else {
         status = false;
@@ -171,7 +173,7 @@
     // 4. Free and done
     InputFile.close();
-    Log() << Verbose(1) << "done." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
   } else {
-    Log() << Verbose(1) << "File " << filename << " not found." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "File " << filename << " not found." << endl);
     status = false;
   }
@@ -201,5 +203,5 @@
   line += KEYSETFILE;
   output.open(line.c_str(), ios::out);
-  Log() << Verbose(1) << "Saving key sets of the total graph ... ";
+  DoLog(1) && (Log() << Verbose(1) << "Saving key sets of the total graph ... ");
   if(output != NULL) {
     for(Graph::iterator runner = KeySetList.begin(); runner != KeySetList.end(); runner++) {
@@ -211,7 +213,7 @@
       output << endl;
     }
-    Log() << Verbose(0) << "done." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "done." << endl);
   } else {
-    eLog() << Verbose(0) << "Unable to open " << line << " for writing keysets!" << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "Unable to open " << line << " for writing keysets!" << endl);
     performCriticalExit();
     status = false;
@@ -242,11 +244,11 @@
   line += TEFACTORSFILE;
   output.open(line.c_str(), ios::out);
-  Log() << Verbose(1) << "Saving TEFactors of the total graph ... ";
+  DoLog(1) && (Log() << Verbose(1) << "Saving TEFactors of the total graph ... ");
   if(output != NULL) {
     for(Graph::iterator runner = KeySetList.begin(); runner != KeySetList.end(); runner++)
       output << (*runner).second.second << endl;
-    Log() << Verbose(1) << "done." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
   } else {
-    Log() << Verbose(1) << "failed to open " << line << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "failed to open " << line << "." << endl);
     status = false;
   }
@@ -292,13 +294,13 @@
         (*PresentItem).second.first = fabs(Value);
         (*PresentItem).second.second = FragOrder;
-        Log() << Verbose(2) << "Updated element (" <<  (*PresentItem).first << ",[" << (*PresentItem).second.first << "," << (*PresentItem).second.second << "])." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Updated element (" <<  (*PresentItem).first << ",[" << (*PresentItem).second.first << "," << (*PresentItem).second.second << "])." << endl);
       } else {
-        Log() << Verbose(2) << "Did not update element " <<  (*PresentItem).first << " as " << FragOrder << " is less than or equal to " << (*PresentItem).second.second << "." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Did not update element " <<  (*PresentItem).first << " as " << FragOrder << " is less than or equal to " << (*PresentItem).second.second << "." << endl);
       }
     } else {
-      Log() << Verbose(2) << "Inserted element (" <<  (*PresentItem).first << ",[" << (*PresentItem).second.first << "," << (*PresentItem).second.second << "])." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "Inserted element (" <<  (*PresentItem).first << ",[" << (*PresentItem).second.first << "," << (*PresentItem).second.second << "])." << endl);
     }
   } else {
-    Log() << Verbose(1) << "No Fragment under No. " << No << "found." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "No Fragment under No. " << No << "found." << endl);
   }
 };
@@ -359,5 +361,5 @@
   atom *Walker = mol->start;
   map<double, pair<int,int> > *FinalRootCandidates = new map<double, pair<int,int> > ;
-  Log() << Verbose(1) << "Root candidate list is: " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Root candidate list is: " << endl);
   for(map<int, pair<double,int> >::iterator runner = AdaptiveCriteriaList->begin(); runner != AdaptiveCriteriaList->end(); runner++) {
     Walker = mol->FindAtom((*runner).first);
@@ -365,11 +367,11 @@
       //if ((*runner).second.second >= Walker->AdaptiveOrder) { // only insert if this is an "active" root site for the current order
       if (!Walker->MaxOrder) {
-        Log() << Verbose(2) << "(" << (*runner).first << ",[" << (*runner).second.first << "," << (*runner).second.second << "])" << endl;
+        DoLog(2) && (Log() << Verbose(2) << "(" << (*runner).first << ",[" << (*runner).second.first << "," << (*runner).second.second << "])" << endl);
         FinalRootCandidates->insert( make_pair( (*runner).second.first, pair<int,int>((*runner).first, (*runner).second.second) ) );
       } else {
-        Log() << Verbose(2) << "Excluding (" << *Walker << ", " << (*runner).first << ",[" << (*runner).second.first << "," << (*runner).second.second << "]), as it has reached its maximum order." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Excluding (" << *Walker << ", " << (*runner).first << ",[" << (*runner).second.first << "," << (*runner).second.second << "]), as it has reached its maximum order." << endl);
       }
     } else {
-      eLog() << Verbose(0) << "Atom No. " << (*runner).second.first << " was not found in this molecule." << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Atom No. " << (*runner).second.first << " was not found in this molecule." << endl);
       performCriticalExit();
     }
@@ -396,5 +398,5 @@
     Walker = mol->FindAtom(No);
     //if (Walker->AdaptiveOrder < MinimumRingSize[Walker->nr]) {
-      Log() << Verbose(2) << "Root " << No << " is still above threshold (10^{" << Order <<"}: " << runner->first << ", setting entry " << No << " of Atom mask to true." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "Root " << No << " is still above threshold (10^{" << Order <<"}: " << runner->first << ", setting entry " << No << " of Atom mask to true." << endl);
       AtomMask[No] = true;
       status = true;
@@ -412,12 +414,12 @@
 void PrintAtomMask(bool *AtomMask, int AtomCount)
 {
-  Log() << Verbose(2) << "              ";
+  DoLog(2) && (Log() << Verbose(2) << "              ");
   for(int i=0;i<AtomCount;i++)
-    Log() << Verbose(0) << (i % 10);
-  Log() << Verbose(0) << endl;
-  Log() << Verbose(2) << "Atom mask is: ";
+    DoLog(0) && (Log() << Verbose(0) << (i % 10));
+  DoLog(0) && (Log() << Verbose(0) << endl);
+  DoLog(2) && (Log() << Verbose(2) << "Atom mask is: ");
   for(int i=0;i<AtomCount;i++)
-    Log() << Verbose(0) << (AtomMask[i] ? "t" : "f");
-  Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << (AtomMask[i] ? "t" : "f"));
+  DoLog(0) && (Log() << Verbose(0) << endl);
 };
 
@@ -446,5 +448,5 @@
     // transmorph graph keyset list into indexed KeySetList
     if (GlobalKeySetList == NULL) {
-      eLog() << Verbose(1) << "Given global key set list (graph) is NULL!" << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << "Given global key set list (graph) is NULL!" << endl);
       return false;
     }
@@ -454,5 +456,5 @@
     map<int, pair<double,int> > *AdaptiveCriteriaList = ScanAdaptiveFileIntoMap(path, *IndexKeySetList); // (Root No., (Value, Order)) !
     if (AdaptiveCriteriaList->empty()) {
-      eLog() << Verbose(2) << "Unable to parse file, incrementing all." << endl;
+      DoeLog(2) && (eLog()<< Verbose(2) << "Unable to parse file, incrementing all." << endl);
       while (Walker->next != end) {
         Walker = Walker->next;
@@ -492,7 +494,7 @@
     if (!status) {
       if (Order == 0)
-        Log() << Verbose(1) << "Single stepping done." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Single stepping done." << endl);
       else
-        Log() << Verbose(1) << "Order at every site is already equal or above desired order " << Order << "." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Order at every site is already equal or above desired order " << Order << "." << endl);
     }
   }
@@ -511,5 +513,5 @@
 {
   if (SortIndex != NULL) {
-    Log() << Verbose(1) << "SortIndex is " << SortIndex << " and not NULL as expected." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "SortIndex is " << SortIndex << " and not NULL as expected." << endl);
     return false;
   }
@@ -562,9 +564,9 @@
   bool *AtomMask = NULL;
 
-  Log() << Verbose(0) << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
 #ifdef ADDHYDROGEN
-  Log() << Verbose(0) << "I will treat hydrogen special and saturate dangling bonds with it." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "I will treat hydrogen special and saturate dangling bonds with it." << endl);
 #else
-  Log() << Verbose(0) << "Hydrogen is treated just like the rest of the lot." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Hydrogen is treated just like the rest of the lot." << endl);
 #endif
 
@@ -592,5 +594,5 @@
     // fill the bond structure of the individually stored subgraphs
   MolecularWalker->FillBondStructureFromReference(this, FragmentCounter, ListOfLocalAtoms, false);  // we want to keep the created ListOfLocalAtoms
-    Log() << Verbose(0) << "Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl);
     LocalBackEdgeStack = new StackClass<bond *> (MolecularWalker->Leaf->BondCount);
 //    // check the list of local atoms for debugging
@@ -601,9 +603,9 @@
 //      else
 //        Log() << Verbose(0) << "\t" << ListOfLocalAtoms[FragmentCounter][i]->Name;
-    Log() << Verbose(0) << "Gathering local back edges for subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Gathering local back edges for subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl);
     MolecularWalker->Leaf->PickLocalBackEdges(ListOfLocalAtoms[FragmentCounter++], BackEdgeStack, LocalBackEdgeStack);
-    Log() << Verbose(0) << "Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl);
     MolecularWalker->Leaf->CyclicStructureAnalysis(LocalBackEdgeStack, MinimumRingSize);
-    Log() << Verbose(0) << "Done with Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Done with Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl);
     delete(LocalBackEdgeStack);
   }
@@ -636,17 +638,17 @@
     while (MolecularWalker->next != NULL) {
       MolecularWalker = MolecularWalker->next;
-      Log() << Verbose(1) << "Fragmenting subgraph " << MolecularWalker << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Fragmenting subgraph " << MolecularWalker << "." << endl);
       //MolecularWalker->Leaf->OutputListOfBonds(out);  // output atom::ListOfBonds for debugging
       if (MolecularWalker->Leaf->first->next != MolecularWalker->Leaf->last) {
         // call BOSSANOVA method
-        Log() << Verbose(0) << endl << " ========== BOND ENERGY of subgraph " << FragmentCounter << " ========================= " << endl;
+        DoLog(0) && (Log() << Verbose(0) << endl << " ========== BOND ENERGY of subgraph " << FragmentCounter << " ========================= " << endl);
         MolecularWalker->Leaf->FragmentBOSSANOVA(FragmentList[FragmentCounter], RootStack[FragmentCounter], MinimumRingSize);
       } else {
-        eLog() << Verbose(1) << "Subgraph " << MolecularWalker << " has no atoms!" << endl;
+        DoeLog(1) && (eLog()<< Verbose(1) << "Subgraph " << MolecularWalker << " has no atoms!" << endl);
       }
       FragmentCounter++;  // next fragment list
     }
   }
-  Log() << Verbose(2) << "CheckOrder is " << CheckOrder << "." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "CheckOrder is " << CheckOrder << "." << endl);
   delete[](RootStack);
   delete[](AtomMask);
@@ -675,13 +677,13 @@
   //if (FragmentationToDo) {    // we should always store the fragments again as coordination might have changed slightly without changing bond structure
   // allocate memory for the pointer array and transmorph graphs into full molecular fragments
-  BondFragments = new MoleculeListClass();
+  BondFragments = new MoleculeListClass(World::getPointer());
   int k=0;
   for(Graph::iterator runner = TotalGraph.begin(); runner != TotalGraph.end(); runner++) {
     KeySet test = (*runner).first;
-    Log() << Verbose(0) << "Fragment No." << (*runner).second.first << " with TEFactor " << (*runner).second.second << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Fragment No." << (*runner).second.first << " with TEFactor " << (*runner).second.second << "." << endl);
     BondFragments->insert(StoreFragmentFromKeySet(test, configuration));
     k++;
   }
-  Log() << Verbose(0) << k << "/" << BondFragments->ListOfMolecules.size() << " fragments generated from the keysets." << endl;
+  DoLog(0) && (Log() << Verbose(0) << k << "/" << BondFragments->ListOfMolecules.size() << " fragments generated from the keysets." << endl);
 
   // ===== 9. Save fragments' configuration and keyset files et al to disk ===
@@ -690,9 +692,9 @@
     CreateMappingLabelsToConfigSequence(SortIndex);
 
-    Log() << Verbose(1) << "Writing " << BondFragments->ListOfMolecules.size() << " possible bond fragmentation configs" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Writing " << BondFragments->ListOfMolecules.size() << " possible bond fragmentation configs" << endl);
     if (BondFragments->OutputConfigForListOfFragments(configuration, SortIndex))
-      Log() << Verbose(1) << "All configs written." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "All configs written." << endl);
     else
-      Log() << Verbose(1) << "Some config writing failed." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Some config writing failed." << endl);
 
     // store force index reference file
@@ -703,5 +705,9 @@
 
     // store Adjacency file
-    StoreAdjacencyToFile(configuration->configpath);
+    char *filename = Malloc<char> (MAXSTRINGSIZE, "molecule::FragmentMolecule - *filename");
+    strcpy(filename, FRAGMENTPREFIX);
+    strcat(filename, ADJACENCYFILE);
+    StoreAdjacencyToFile(configuration->configpath, filename);
+    Free(&filename);
 
     // store Hydrogen saturation correction file
@@ -715,12 +721,12 @@
 
     // free memory for bond part
-    Log() << Verbose(1) << "Freeing bond memory" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Freeing bond memory" << endl);
     delete(FragmentList); // remove bond molecule from memory
     Free(&SortIndex);
   } else {
-    Log() << Verbose(1) << "FragmentList is zero on return, splitting failed." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "FragmentList is zero on return, splitting failed." << endl);
   }
   delete(BondFragments);
-  Log() << Verbose(0) << "End of bond fragmentation." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "End of bond fragmentation." << endl);
 
   return ((int)(!FragmentationToDo)+1);    // 1 - continue, 2 - stop (no fragmentation occured)
@@ -741,12 +747,12 @@
   line << path << "/" << FRAGMENTPREFIX << ORDERATSITEFILE;
   file.open(line.str().c_str());
-  Log() << Verbose(1) << "Writing OrderAtSite " << ORDERATSITEFILE << " ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Writing OrderAtSite " << ORDERATSITEFILE << " ... " << endl);
   if (file != NULL) {
     ActOnAllAtoms( &atom::OutputOrder, &file );
     file.close();
-    Log() << Verbose(1) << "done." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
     return true;
   } else {
-    Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl);
     return false;
   }
@@ -769,5 +775,5 @@
   ifstream file;
 
-  Log() << Verbose(1) << "Begin of ParseOrderAtSiteFromFile" << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Begin of ParseOrderAtSiteFromFile" << endl);
   line << path << "/" << FRAGMENTPREFIX << ORDERATSITEFILE;
   file.open(line.str().c_str());
@@ -790,8 +796,8 @@
     SetAtomValueToIndexedArray( MaxArray, &atom::nr, &atom::MaxOrder );
 
-    Log() << Verbose(1) << "done." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
     status = true;
   } else {
-    Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl);
     status = false;
   }
@@ -799,5 +805,5 @@
   Free(&MaxArray);
 
-  Log() << Verbose(1) << "End of ParseOrderAtSiteFromFile" << endl;
+  DoLog(1) && (Log() << Verbose(1) << "End of ParseOrderAtSiteFromFile" << endl);
   return status;
 };
@@ -816,5 +822,5 @@
   int SP, Removal;
 
-  Log() << Verbose(2) << "Looking for removal candidate." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Looking for removal candidate." << endl);
   SP = -1; //0;  // not -1, so that Root is never removed
   Removal = -1;
@@ -843,6 +849,4 @@
 
   Leaf->BondDistance = mol->BondDistance;
-  for(int i=NDIM*2;i--;)
-    Leaf->cell_size[i] = mol->cell_size[i];
 
   // first create the minimal set of atoms from the KeySet
@@ -903,8 +907,8 @@
       }
     } else {
-      eLog() << Verbose(1) << "Son " << Runner->Name << " has father " << FatherOfRunner->Name << " but its entry in SonList is " << SonList[FatherOfRunner->nr] << "!" << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << "Son " << Runner->Name << " has father " << FatherOfRunner->Name << " but its entry in SonList is " << SonList[FatherOfRunner->nr] << "!" << endl);
     }
     if ((LonelyFlag) && (Leaf->AtomCount > 1)) {
-      Log() << Verbose(0) << *Runner << "has got bonds only to hydrogens!" << endl;
+      DoLog(0) && (Log() << Verbose(0) << *Runner << "has got bonds only to hydrogens!" << endl);
     }
 #ifdef ADDHYDROGEN
@@ -926,5 +930,5 @@
 {
   atom **SonList = Calloc<atom*>(AtomCount, "molecule::StoreFragmentFromStack: **SonList");
-  molecule *Leaf = new molecule(elemente);
+  molecule *Leaf = World::getInstance().createMolecule();
 
 //  Log() << Verbose(1) << "Begin of StoreFragmentFromKeyset." << endl;
@@ -1053,8 +1057,8 @@
     TouchedList[j] = -1;
   }
-  Log() << Verbose(2) << "Remaining local nr.s on snake stack are: ";
+  DoLog(2) && (Log() << Verbose(2) << "Remaining local nr.s on snake stack are: ");
   for(KeySet::iterator runner = FragmentSet->begin(); runner != FragmentSet->end(); runner++)
-    Log() << Verbose(0) << (*runner) << " ";
-  Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << (*runner) << " ");
+  DoLog(0) && (Log() << Verbose(0) << endl);
   TouchedIndex = 0; // set Index to 0 for list of atoms added on this level
 };
@@ -1133,10 +1137,10 @@
         Log() << Verbose(1+verbosity) << "Enough items on stack for a fragment!" << endl;
         // store fragment as a KeySet
-        Log() << Verbose(2) << "Found a new fragment[" << FragmentSearch->FragmentCounter << "], local nr.s are: ";
+        DoLog(2) && (Log() << Verbose(2) << "Found a new fragment[" << FragmentSearch->FragmentCounter << "], local nr.s are: ");
         for(KeySet::iterator runner = FragmentSearch->FragmentSet->begin(); runner != FragmentSearch->FragmentSet->end(); runner++)
-          Log() << Verbose(0) << (*runner) << " ";
-        Log() << Verbose(0) << endl;
+          DoLog(0) && (Log() << Verbose(0) << (*runner) << " ");
+        DoLog(0) && (Log() << Verbose(0) << endl);
         //if (!CheckForConnectedSubgraph(FragmentSearch->FragmentSet))
-          //eLog() << Verbose(1) << "The found fragment is not a connected subgraph!" << endl;
+          //DoeLog(1) && (eLog()<< Verbose(1) << "The found fragment is not a connected subgraph!" << endl);
         InsertFragmentIntoGraph(FragmentSearch);
       }
@@ -1218,7 +1222,7 @@
 {
   bond *Binder = NULL;
-  Log() << Verbose(0) << "Free'ing all found lists. and resetting index lists" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Free'ing all found lists. and resetting index lists" << endl);
   for(int i=Order;i--;) {
-    Log() << Verbose(1) << "Current SP level is " << i << ": ";
+    DoLog(1) && (Log() << Verbose(1) << "Current SP level is " << i << ": ");
     Binder = FragmentSearch.BondsPerSPList[2*i];
     while (Binder->next != FragmentSearch.BondsPerSPList[2*i+1]) {
@@ -1231,5 +1235,5 @@
     cleanup(FragmentSearch.BondsPerSPList[2*i], FragmentSearch.BondsPerSPList[2*i+1]);
     // also start and end node
-    Log() << Verbose(0) << "cleaned." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "cleaned." << endl);
   }
 };
@@ -1261,12 +1265,12 @@
   int SP = -1;
 
-  Log() << Verbose(0) << "Starting BFS analysis ..." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Starting BFS analysis ..." << endl);
   for (SP = 0; SP < (Order-1); SP++) {
-    Log() << Verbose(1) << "New SP level reached: " << SP << ", creating new SP list with " << FragmentSearch.BondsPerSPCount[SP] << " item(s)";
+    DoLog(1) && (Log() << Verbose(1) << "New SP level reached: " << SP << ", creating new SP list with " << FragmentSearch.BondsPerSPCount[SP] << " item(s)");
     if (SP > 0) {
-      Log() << Verbose(0) << ", old level closed with " << FragmentSearch.BondsPerSPCount[SP-1] << " item(s)." << endl;
+      DoLog(0) && (Log() << Verbose(0) << ", old level closed with " << FragmentSearch.BondsPerSPCount[SP-1] << " item(s)." << endl);
       FragmentSearch.BondsPerSPCount[SP] = 0;
     } else
-      Log() << Verbose(0) << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "." << endl);
 
     RemainingWalkers = FragmentSearch.BondsPerSPCount[SP];
@@ -1278,8 +1282,8 @@
       Predecessor = CurrentEdge->leftatom;    // ... and leftatom is predecessor
       AtomKeyNr = Walker->nr;
-      Log() << Verbose(0) << "Current Walker is: " << *Walker << " with nr " << Walker->nr << " and SP of " << SP << ", with " << RemainingWalkers << " remaining walkers on this level." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Current Walker is: " << *Walker << " with nr " << Walker->nr << " and SP of " << SP << ", with " << RemainingWalkers << " remaining walkers on this level." << endl);
       // check for new sp level
       // go through all its bonds
-      Log() << Verbose(1) << "Going through all bonds of Walker." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Going through all bonds of Walker." << endl);
       for (BondList::const_iterator Runner = Walker->ListOfBonds.begin(); Runner != Walker->ListOfBonds.end(); (++Runner)) {
         OtherWalker = (*Runner)->GetOtherAtom(Walker);
@@ -1289,19 +1293,19 @@
   #endif
                                                               ) {  // skip hydrogens and restrict to fragment
-          Log() << Verbose(2) << "Current partner is " << *OtherWalker << " with nr " << OtherWalker->nr << " in bond " << *(*Runner) << "." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "Current partner is " << *OtherWalker << " with nr " << OtherWalker->nr << " in bond " << *(*Runner) << "." << endl);
           // set the label if not set (and push on root stack as well)
           if ((OtherWalker != Predecessor) && (OtherWalker->GetTrueFather()->nr > RootKeyNr)) { // only pass through those with label bigger than Root's
             FragmentSearch.ShortestPathList[OtherWalker->nr] = SP+1;
-            Log() << Verbose(3) << "Set Shortest Path to " << FragmentSearch.ShortestPathList[OtherWalker->nr] << "." << endl;
+            DoLog(3) && (Log() << Verbose(3) << "Set Shortest Path to " << FragmentSearch.ShortestPathList[OtherWalker->nr] << "." << endl);
             // add the bond in between to the SP list
             Binder = new bond(Walker, OtherWalker); // create a new bond in such a manner, that bond::rightatom is always the one more distant
             add(Binder, FragmentSearch.BondsPerSPList[2*(SP+1)+1]);
             FragmentSearch.BondsPerSPCount[SP+1]++;
-            Log() << Verbose(3) << "Added its bond to SP list, having now " << FragmentSearch.BondsPerSPCount[SP+1] << " item(s)." << endl;
+            DoLog(3) && (Log() << Verbose(3) << "Added its bond to SP list, having now " << FragmentSearch.BondsPerSPCount[SP+1] << " item(s)." << endl);
           } else {
             if (OtherWalker != Predecessor)
-              Log() << Verbose(3) << "Not passing on, as index of " << *OtherWalker << " " << OtherWalker->GetTrueFather()->nr << " is smaller than that of Root " << RootKeyNr << "." << endl;
+              DoLog(3) && (Log() << Verbose(3) << "Not passing on, as index of " << *OtherWalker << " " << OtherWalker->GetTrueFather()->nr << " is smaller than that of Root " << RootKeyNr << "." << endl);
             else
-              Log() << Verbose(3) << "This is my predecessor " << *Predecessor << "." << endl;
+              DoLog(3) && (Log() << Verbose(3) << "This is my predecessor " << *Predecessor << "." << endl);
           }
         } else Log() << Verbose(2) << "Is not in the restricted keyset or skipping hydrogen " << *OtherWalker << "." << endl;
@@ -1319,11 +1323,11 @@
 {
   bond *Binder = NULL;
-  Log() << Verbose(0) << "Printing all found lists." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Printing all found lists." << endl);
   for(int i=1;i<Order;i++) {    // skip the root edge in the printing
     Binder = FragmentSearch.BondsPerSPList[2*i];
-    Log() << Verbose(1) << "Current SP level is " << i << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Current SP level is " << i << "." << endl);
     while (Binder->next != FragmentSearch.BondsPerSPList[2*i+1]) {
       Binder = Binder->next;
-      Log() << Verbose(2) << *Binder << endl;
+      DoLog(2) && (Log() << Verbose(2) << *Binder << endl);
     }
   }
@@ -1369,6 +1373,6 @@
   int Counter = FragmentSearch.FragmentCounter; // mark current value of counter
 
-  Log() << Verbose(0) << endl;
-  Log() << Verbose(0) << "Begin of PowerSetGenerator with order " << Order << " at Root " << *FragmentSearch.Root << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
+  DoLog(0) && (Log() << Verbose(0) << "Begin of PowerSetGenerator with order " << Order << " at Root " << *FragmentSearch.Root << "." << endl);
 
   SetSPList(Order, FragmentSearch);
@@ -1382,10 +1386,10 @@
   // creating fragments with the found edge sets  (may be done in reverse order, faster)
   int SP = CountNumbersInBondsList(Order, FragmentSearch);
-  Log() << Verbose(0) << "Total number of edges is " << SP << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Total number of edges is " << SP << "." << endl);
   if (SP >= (Order-1)) {
     // start with root (push on fragment stack)
-    Log() << Verbose(0) << "Starting fragment generation with " << *FragmentSearch.Root << ", local nr is " << FragmentSearch.Root->nr << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Starting fragment generation with " << *FragmentSearch.Root << ", local nr is " << FragmentSearch.Root->nr << "." << endl);
     FragmentSearch.FragmentSet->clear();
-    Log() << Verbose(0) << "Preparing subset for this root and calling generator." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Preparing subset for this root and calling generator." << endl);
 
     // prepare the subset and call the generator
@@ -1397,10 +1401,10 @@
     Free(&BondsList);
   } else {
-    Log() << Verbose(0) << "Not enough total number of edges to build " << Order << "-body fragments." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Not enough total number of edges to build " << Order << "-body fragments." << endl);
   }
 
   // as FragmentSearch structure is used only once, we don't have to clean it anymore
   // remove root from stack
-  Log() << Verbose(0) << "Removing root again from stack." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Removing root again from stack." << endl);
   FragmentSearch.FragmentSet->erase(FragmentSearch.Root->nr);
 
@@ -1409,5 +1413,5 @@
 
   // return list
-  Log() << Verbose(0) << "End of PowerSetGenerator." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "End of PowerSetGenerator." << endl);
   return (FragmentSearch.FragmentCounter - Counter);
 };
@@ -1455,5 +1459,5 @@
   atom *Walker = NULL;
 
-  Log() << Verbose(0) << "Combining the lists of all orders per order and finally into a single one." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Combining the lists of all orders per order and finally into a single one." << endl);
   if (FragmentList == NULL) {
     FragmentList = new Graph;
@@ -1488,5 +1492,5 @@
 void FreeAllOrdersList(Graph ***FragmentLowerOrdersList, KeyStack &RootStack, molecule *mol)
 {
-  Log() << Verbose(1) << "Free'ing the lists of all orders per order." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Free'ing the lists of all orders per order." << endl);
   int RootNr = 0;
   int RootKeyNr = 0;
@@ -1541,5 +1545,5 @@
   struct UniqueFragments FragmentSearch;
 
-  Log() << Verbose(0) << "Begin of FragmentBOSSANOVA." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Begin of FragmentBOSSANOVA." << endl);
 
   // FragmentLowerOrdersList is a 2D-array of pointer to MoleculeListClass objects, one dimension represents the ANOVA expansion of a single order (i.e. 5)
@@ -1591,6 +1595,6 @@
 
       // create top order where nothing is reduced
-      Log() << Verbose(0) << "==============================================================================================================" << endl;
-      Log() << Verbose(0) << "Creating KeySets of Bond Order " << Order << " for " << *Walker << ", " << (RootStack.size()-RootNr) << " Roots remaining." << endl; // , NumLevels is " << NumLevels << "
+      DoLog(0) && (Log() << Verbose(0) << "==============================================================================================================" << endl);
+      DoLog(0) && (Log() << Verbose(0) << "Creating KeySets of Bond Order " << Order << " for " << *Walker << ", " << (RootStack.size()-RootNr) << " Roots remaining." << endl); // , NumLevels is " << NumLevels << "
 
       // Create list of Graphs of current Bond Order (i.e. F_{ij})
@@ -1602,5 +1606,5 @@
 
       // output resulting number
-      Log() << Verbose(1) << "Number of resulting KeySets is: " << NumMoleculesOfOrder[RootNr] << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Number of resulting KeySets is: " << NumMoleculesOfOrder[RootNr] << "." << endl);
       if (NumMoleculesOfOrder[RootNr] != 0) {
         NumMolecules = 0;
@@ -1619,7 +1623,7 @@
     }
   }
-  Log() << Verbose(0) << "==============================================================================================================" << endl;
-  Log() << Verbose(1) << "Total number of resulting molecules is: " << TotalNumMolecules << "." << endl;
-  Log() << Verbose(0) << "==============================================================================================================" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "==============================================================================================================" << endl);
+  DoLog(1) && (Log() << Verbose(1) << "Total number of resulting molecules is: " << TotalNumMolecules << "." << endl);
+  DoLog(0) && (Log() << Verbose(0) << "==============================================================================================================" << endl);
 
   // cleanup FragmentSearch structure
@@ -1639,5 +1643,5 @@
   Free(&NumMoleculesOfOrder);
 
-  Log() << Verbose(0) << "End of FragmentBOSSANOVA." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "End of FragmentBOSSANOVA." << endl);
 };
 
@@ -1654,4 +1658,5 @@
   atom *Walker = NULL;
   atom *OtherWalker = NULL;
+  double * const cell_size = World::getInstance().getDomain();
   double *matrix = ReturnFullMatrixforSymmetric(cell_size);
   enum Shading *ColorList = NULL;
@@ -1662,5 +1667,5 @@
   bool flag = true;
 
-  Log() << Verbose(2) << "Begin of ScanForPeriodicCorrection." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Begin of ScanForPeriodicCorrection." << endl);
 
   ColorList = Calloc<enum Shading>(AtomCount, "molecule::ScanForPeriodicCorrection: *ColorList");
@@ -1668,5 +1673,5 @@
     // remove bonds that are beyond bonddistance
     for(int i=NDIM;i--;)
-      Translationvector.x[i] = 0.;
+      Translationvector[i] = 0.;
     // scan all bonds
     Binder = first;
@@ -1675,10 +1680,10 @@
       Binder = Binder->next;
       for (int i=NDIM;i--;) {
-        tmp = fabs(Binder->leftatom->x.x[i] - Binder->rightatom->x.x[i]);
+        tmp = fabs(Binder->leftatom->x[i] - Binder->rightatom->x[i]);
         //Log() << Verbose(3) << "Checking " << i << "th distance of " << *Binder->leftatom << " to " << *Binder->rightatom << ": " << tmp << "." << endl;
         if (tmp > BondDistance) {
           OtherBinder = Binder->next; // note down binding partner for later re-insertion
           unlink(Binder);   // unlink bond
-          Log() << Verbose(2) << "Correcting at bond " << *Binder << "." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "Correcting at bond " << *Binder << "." << endl);
           flag = true;
           break;
@@ -1689,12 +1694,11 @@
       // create translation vector from their periodically modified distance
       for (int i=NDIM;i--;) {
-        tmp = Binder->leftatom->x.x[i] - Binder->rightatom->x.x[i];
+        tmp = Binder->leftatom->x[i] - Binder->rightatom->x[i];
         if (fabs(tmp) > BondDistance)
-          Translationvector.x[i] = (tmp < 0) ? +1. : -1.;
+          Translationvector[i] = (tmp < 0) ? +1. : -1.;
       }
       Translationvector.MatrixMultiplication(matrix);
       //Log() << Verbose(3) << "Translation vector is ";
-      Translationvector.Output();
-      Log() << Verbose(0) << endl;
+      Log() << Verbose(0) << Translationvector <<  endl;
       // apply to all atoms of first component via BFS
       for (int i=AtomCount;i--;)
@@ -1705,5 +1709,5 @@
         //Log() << Verbose (3) << "Current Walker is: " << *Walker << "." << endl;
         ColorList[Walker->nr] = black;    // mark as explored
-        Walker->x.AddVector(&Translationvector); // translate
+        Walker->x += Translationvector; // translate
         for (BondList::const_iterator Runner = Walker->ListOfBonds.begin(); Runner != Walker->ListOfBonds.end(); (++Runner)) {
           if ((*Runner) != Binder) {
@@ -1718,5 +1722,5 @@
       link(Binder, OtherBinder);
     } else {
-      Log() << Verbose(3) << "No corrections for this fragment." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "No corrections for this fragment." << endl);
     }
     //delete(CompStack);
@@ -1727,4 +1731,4 @@
   Free(&ColorList);
   Free(&matrix);
-  Log() << Verbose(2) << "End of ScanForPeriodicCorrection." << endl;
-};
+  DoLog(2) && (Log() << Verbose(2) << "End of ScanForPeriodicCorrection." << endl);
+};
Index: src/molecule_geometry.cpp
===================================================================
--- src/molecule_geometry.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/molecule_geometry.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -15,4 +15,5 @@
 #include "memoryallocator.hpp"
 #include "molecule.hpp"
+#include "World.hpp"
 
 /************************************* Functions for class molecule *********************************/
@@ -26,9 +27,10 @@
   bool status = true;
   const Vector *Center = DetermineCenterOfAll();
+  double * const cell_size = World::getInstance().getDomain();
   double *M = ReturnFullMatrixforSymmetric(cell_size);
   double *Minv = InverseMatrix(M);
 
   // go through all atoms
-  ActOnAllVectors( &Vector::SubtractVector, Center);
+  ActOnAllVectors( &Vector::SubtractVector, *Center);
   ActOnAllVectors( &Vector::WrapPeriodically, (const double *)M, (const double *)Minv);
 
@@ -46,4 +48,5 @@
 {
   bool status = true;
+  double * const cell_size = World::getInstance().getDomain();
   double *M = ReturnFullMatrixforSymmetric(cell_size);
   double *Minv = InverseMatrix(M);
@@ -69,6 +72,6 @@
   if (ptr != end) {   //list not empty?
     for (int i=NDIM;i--;) {
-      max->x[i] = ptr->x.x[i];
-      min->x[i] = ptr->x.x[i];
+      max->at(i) = ptr->x[i];
+      min->at(i) = ptr->x[i];
     }
     while (ptr->next != end) {  // continue with second if present
@@ -76,6 +79,6 @@
       //ptr->Output(1,1,out);
       for (int i=NDIM;i--;) {
-        max->x[i] = (max->x[i] < ptr->x.x[i]) ? ptr->x.x[i] : max->x[i];
-        min->x[i] = (min->x[i] > ptr->x.x[i]) ? ptr->x.x[i] : min->x[i];
+        max->at(i) = (max->at(i) < ptr->x[i]) ? ptr->x[i] : max->at(i);
+        min->at(i) = (min->at(i) > ptr->x[i]) ? ptr->x[i] : min->at(i);
       }
     }
@@ -86,5 +89,5 @@
 //    Log() << Verbose(0) << endl;
     min->Scale(-1.);
-    max->AddVector(min);
+    (*max) += (*min);
     Translate(min);
     Center.Zero();
@@ -109,5 +112,5 @@
       ptr = ptr->next;
       Num++;
-      Center.AddVector(&ptr->x);
+      Center += ptr->x;
     }
     Center.Scale(-1./Num); // divide through total number (and sign for direction)
@@ -133,6 +136,6 @@
       ptr = ptr->next;
       Num += 1.;
-      tmp.CopyVector(&ptr->x);
-      a->AddVector(&tmp);
+      tmp = ptr->x;
+      (*a) += tmp;
     }
     a->Scale(1./Num); // divide through total mass (and sign for direction)
@@ -158,7 +161,6 @@
       ptr = ptr->next;
       Num += ptr->type->mass;
-      tmp.CopyVector(&ptr->x);
-      tmp.Scale(ptr->type->mass);  // scale by mass
-      a->AddVector(&tmp);
+      tmp = ptr->type->mass * ptr->x;
+      (*a) += tmp;
     }
     a->Scale(-1./Num); // divide through total mass (and sign for direction)
@@ -186,5 +188,5 @@
 void molecule::CenterAtVector(Vector *newcenter)
 {
-  Center.CopyVector(newcenter);
+  Center = *newcenter;
 };
 
@@ -192,4 +194,9 @@
 /** Scales all atoms by \a *factor.
  * \param *factor pointer to scaling factor
+ *
+ * TODO: Is this realy what is meant, i.e.
+ * x=(x[0]*factor[0],x[1]*factor[1],x[2]*factor[2]) (current impl)
+ * or rather
+ * x=(**factor) * x (as suggested by comment)
  */
 void molecule::Scale(const double ** const factor)
@@ -200,6 +207,6 @@
     ptr = ptr->next;
     for (int j=0;j<MDSteps;j++)
-      ptr->Trajectory.R.at(j).Scale(factor);
-    ptr->x.Scale(factor);
+      ptr->Trajectory.R.at(j).ScaleAll(*factor);
+    ptr->x.ScaleAll(*factor);
   }
 };
@@ -215,6 +222,6 @@
     ptr = ptr->next;
     for (int j=0;j<MDSteps;j++)
-      ptr->Trajectory.R.at(j).Translate(trans);
-    ptr->x.Translate(trans);
+      ptr->Trajectory.R.at(j) += (*trans);
+    ptr->x += (*trans);
   }
 };
@@ -226,9 +233,10 @@
 void molecule::TranslatePeriodically(const Vector *trans)
 {
+  double * const cell_size = World::getInstance().getDomain();
   double *M = ReturnFullMatrixforSymmetric(cell_size);
   double *Minv = InverseMatrix(M);
 
   // go through all atoms
-  ActOnAllVectors( &Vector::SubtractVector, trans);
+  ActOnAllVectors( &Vector::SubtractVector, *trans);
   ActOnAllVectors( &Vector::WrapPeriodically, (const double *)M, (const double *)Minv);
 
@@ -243,5 +251,5 @@
 void molecule::Mirror(const Vector *n)
 {
-  ActOnAllVectors( &Vector::Mirror, n );
+  ActOnAllVectors( &Vector::Mirror, *n );
 };
 
@@ -252,4 +260,5 @@
 {
   atom *Walker = start;
+  double * const cell_size = World::getInstance().getDomain();
   double *matrix = ReturnFullMatrixforSymmetric(cell_size);
   double *inversematrix = InverseMatrix(cell_size);
@@ -266,5 +275,5 @@
       if (Walker->type->Z != 1) {
 #endif
-        Testvector.CopyVector(&Walker->x);
+        Testvector = Walker->x;
         Testvector.MatrixMultiplication(inversematrix);
         Translationvector.Zero();
@@ -272,33 +281,29 @@
          if (Walker->nr < (*Runner)->GetOtherAtom(Walker)->nr) // otherwise we shift one to, the other fro and gain nothing
             for (int j=0;j<NDIM;j++) {
-              tmp = Walker->x.x[j] - (*Runner)->GetOtherAtom(Walker)->x.x[j];
+              tmp = Walker->x[j] - (*Runner)->GetOtherAtom(Walker)->x[j];
               if ((fabs(tmp)) > BondDistance) {
                 flag = false;
-                Log() << Verbose(0) << "Hit: atom " << Walker->Name << " in bond " << *(*Runner) << " has to be shifted due to " << tmp << "." << endl;
+                DoLog(0) && (Log() << Verbose(0) << "Hit: atom " << Walker->Name << " in bond " << *(*Runner) << " has to be shifted due to " << tmp << "." << endl);
                 if (tmp > 0)
-                  Translationvector.x[j] -= 1.;
+                  Translationvector[j] -= 1.;
                 else
-                  Translationvector.x[j] += 1.;
+                  Translationvector[j] += 1.;
               }
             }
         }
-        Testvector.AddVector(&Translationvector);
+        Testvector += Translationvector;
         Testvector.MatrixMultiplication(matrix);
-        Center.AddVector(&Testvector);
-        Log() << Verbose(1) << "vector is: ";
-        Testvector.Output();
-        Log() << Verbose(0) << endl;
+        Center += Testvector;
+        Log() << Verbose(1) << "vector is: " << Testvector << endl;
 #ifdef ADDHYDROGEN
         // now also change all hydrogens
         for (BondList::const_iterator Runner = Walker->ListOfBonds.begin(); Runner != Walker->ListOfBonds.end(); (++Runner)) {
           if ((*Runner)->GetOtherAtom(Walker)->type->Z == 1) {
-            Testvector.CopyVector(&(*Runner)->GetOtherAtom(Walker)->x);
+            Testvector = (*Runner)->GetOtherAtom(Walker)->x;
             Testvector.MatrixMultiplication(inversematrix);
-            Testvector.AddVector(&Translationvector);
+            Testvector += Translationvector;
             Testvector.MatrixMultiplication(matrix);
-            Center.AddVector(&Testvector);
-            Log() << Verbose(1) << "Hydrogen vector is: ";
-            Testvector.Output();
-            Log() << Verbose(0) << endl;
+            Center += Testvector;
+            Log() << Verbose(1) << "Hydrogen vector is: " << Testvector << endl;
           }
         }
@@ -333,25 +338,24 @@
   while (ptr->next != end) {
     ptr = ptr->next;
-    Vector x;
-    x.CopyVector(&ptr->x);
+    Vector x = ptr->x;
     //x.SubtractVector(CenterOfGravity);
-    InertiaTensor[0] += ptr->type->mass*(x.x[1]*x.x[1] + x.x[2]*x.x[2]);
-    InertiaTensor[1] += ptr->type->mass*(-x.x[0]*x.x[1]);
-    InertiaTensor[2] += ptr->type->mass*(-x.x[0]*x.x[2]);
-    InertiaTensor[3] += ptr->type->mass*(-x.x[1]*x.x[0]);
-    InertiaTensor[4] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[2]*x.x[2]);
-    InertiaTensor[5] += ptr->type->mass*(-x.x[1]*x.x[2]);
-    InertiaTensor[6] += ptr->type->mass*(-x.x[2]*x.x[0]);
-    InertiaTensor[7] += ptr->type->mass*(-x.x[2]*x.x[1]);
-    InertiaTensor[8] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[1]*x.x[1]);
+    InertiaTensor[0] += ptr->type->mass*(x[1]*x[1] + x[2]*x[2]);
+    InertiaTensor[1] += ptr->type->mass*(-x[0]*x[1]);
+    InertiaTensor[2] += ptr->type->mass*(-x[0]*x[2]);
+    InertiaTensor[3] += ptr->type->mass*(-x[1]*x[0]);
+    InertiaTensor[4] += ptr->type->mass*(x[0]*x[0] + x[2]*x[2]);
+    InertiaTensor[5] += ptr->type->mass*(-x[1]*x[2]);
+    InertiaTensor[6] += ptr->type->mass*(-x[2]*x[0]);
+    InertiaTensor[7] += ptr->type->mass*(-x[2]*x[1]);
+    InertiaTensor[8] += ptr->type->mass*(x[0]*x[0] + x[1]*x[1]);
   }
   // print InertiaTensor for debugging
-  Log() << Verbose(0) << "The inertia tensor is:" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "The inertia tensor is:" << endl);
   for(int i=0;i<NDIM;i++) {
     for(int j=0;j<NDIM;j++)
-      Log() << Verbose(0) << InertiaTensor[i*NDIM+j] << " ";
-    Log() << Verbose(0) << endl;
-  }
-  Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << InertiaTensor[i*NDIM+j] << " ");
+    DoLog(0) && (Log() << Verbose(0) << endl);
+  }
+  DoLog(0) && (Log() << Verbose(0) << endl);
 
   // diagonalize to determine principal axis system
@@ -365,14 +369,14 @@
 
   for(int i=0;i<NDIM;i++) {
-    Log() << Verbose(1) << "eigenvalue = " << gsl_vector_get(eval, i);
-    Log() << Verbose(0) << ", eigenvector = (" << evec->data[i * evec->tda + 0] << "," << evec->data[i * evec->tda + 1] << "," << evec->data[i * evec->tda + 2] << ")" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "eigenvalue = " << gsl_vector_get(eval, i));
+    DoLog(0) && (Log() << Verbose(0) << ", eigenvector = (" << evec->data[i * evec->tda + 0] << "," << evec->data[i * evec->tda + 1] << "," << evec->data[i * evec->tda + 2] << ")" << endl);
   }
 
   // check whether we rotate or not
   if (DoRotate) {
-    Log() << Verbose(1) << "Transforming molecule into PAS ... ";
+    DoLog(1) && (Log() << Verbose(1) << "Transforming molecule into PAS ... ");
     // the eigenvectors specify the transformation matrix
     ActOnAllVectors( &Vector::MatrixMultiplication, (const double *) evec->data );
-    Log() << Verbose(0) << "done." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "done." << endl);
 
     // summing anew for debugging (resulting matrix has to be diagonal!)
@@ -385,25 +389,24 @@
     while (ptr->next != end) {
       ptr = ptr->next;
-      Vector x;
-      x.CopyVector(&ptr->x);
+      Vector x = ptr->x;
       //x.SubtractVector(CenterOfGravity);
-      InertiaTensor[0] += ptr->type->mass*(x.x[1]*x.x[1] + x.x[2]*x.x[2]);
-      InertiaTensor[1] += ptr->type->mass*(-x.x[0]*x.x[1]);
-      InertiaTensor[2] += ptr->type->mass*(-x.x[0]*x.x[2]);
-      InertiaTensor[3] += ptr->type->mass*(-x.x[1]*x.x[0]);
-      InertiaTensor[4] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[2]*x.x[2]);
-      InertiaTensor[5] += ptr->type->mass*(-x.x[1]*x.x[2]);
-      InertiaTensor[6] += ptr->type->mass*(-x.x[2]*x.x[0]);
-      InertiaTensor[7] += ptr->type->mass*(-x.x[2]*x.x[1]);
-      InertiaTensor[8] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[1]*x.x[1]);
+      InertiaTensor[0] += ptr->type->mass*(x[1]*x[1] + x[2]*x[2]);
+      InertiaTensor[1] += ptr->type->mass*(-x[0]*x[1]);
+      InertiaTensor[2] += ptr->type->mass*(-x[0]*x[2]);
+      InertiaTensor[3] += ptr->type->mass*(-x[1]*x[0]);
+      InertiaTensor[4] += ptr->type->mass*(x[0]*x[0] + x[2]*x[2]);
+      InertiaTensor[5] += ptr->type->mass*(-x[1]*x[2]);
+      InertiaTensor[6] += ptr->type->mass*(-x[2]*x[0]);
+      InertiaTensor[7] += ptr->type->mass*(-x[2]*x[1]);
+      InertiaTensor[8] += ptr->type->mass*(x[0]*x[0] + x[1]*x[1]);
     }
     // print InertiaTensor for debugging
-    Log() << Verbose(0) << "The inertia tensor is:" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "The inertia tensor is:" << endl);
     for(int i=0;i<NDIM;i++) {
       for(int j=0;j<NDIM;j++)
-        Log() << Verbose(0) << InertiaTensor[i*NDIM+j] << " ";
-      Log() << Verbose(0) << endl;
-    }
-    Log() << Verbose(0) << endl;
+        DoLog(0) && (Log() << Verbose(0) << InertiaTensor[i*NDIM+j] << " ");
+      DoLog(0) && (Log() << Verbose(0) << endl);
+    }
+    DoLog(0) && (Log() << Verbose(0) << endl);
   }
 
@@ -423,55 +426,52 @@
   double alpha, tmp;
   Vector z_axis;
-  z_axis.x[0] = 0.;
-  z_axis.x[1] = 0.;
-  z_axis.x[2] = 1.;
+  z_axis[0] = 0.;
+  z_axis[1] = 0.;
+  z_axis[2] = 1.;
 
   // rotate on z-x plane
-  Log() << Verbose(0) << "Begin of Aligning all atoms." << endl;
-  alpha = atan(-n->x[0]/n->x[2]);
-  Log() << Verbose(1) << "Z-X-angle: " << alpha << " ... ";
+  DoLog(0) && (Log() << Verbose(0) << "Begin of Aligning all atoms." << endl);
+  alpha = atan(-n->at(0)/n->at(2));
+  DoLog(1) && (Log() << Verbose(1) << "Z-X-angle: " << alpha << " ... ");
   while (ptr->next != end) {
     ptr = ptr->next;
-    tmp = ptr->x.x[0];
-    ptr->x.x[0] =  cos(alpha) * tmp + sin(alpha) * ptr->x.x[2];
-    ptr->x.x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->x.x[2];
+    tmp = ptr->x[0];
+    ptr->x[0] =  cos(alpha) * tmp + sin(alpha) * ptr->x[2];
+    ptr->x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->x[2];
     for (int j=0;j<MDSteps;j++) {
-      tmp = ptr->Trajectory.R.at(j).x[0];
-      ptr->Trajectory.R.at(j).x[0] =  cos(alpha) * tmp + sin(alpha) * ptr->Trajectory.R.at(j).x[2];
-      ptr->Trajectory.R.at(j).x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->Trajectory.R.at(j).x[2];
+      tmp = ptr->Trajectory.R.at(j)[0];
+      ptr->Trajectory.R.at(j)[0] =  cos(alpha) * tmp + sin(alpha) * ptr->Trajectory.R.at(j)[2];
+      ptr->Trajectory.R.at(j)[2] = -sin(alpha) * tmp + cos(alpha) * ptr->Trajectory.R.at(j)[2];
     }
   }
   // rotate n vector
-  tmp = n->x[0];
-  n->x[0] =  cos(alpha) * tmp +  sin(alpha) * n->x[2];
-  n->x[2] = -sin(alpha) * tmp +  cos(alpha) * n->x[2];
-  Log() << Verbose(1) << "alignment vector after first rotation: ";
-  n->Output();
-  Log() << Verbose(0) << endl;
+  tmp = n->at(0);
+  n->at(0) =  cos(alpha) * tmp +  sin(alpha) * n->at(2);
+  n->at(2) = -sin(alpha) * tmp +  cos(alpha) * n->at(2);
+  DoLog(1) && (Log() << Verbose(1) << "alignment vector after first rotation: " << n << endl);
 
   // rotate on z-y plane
   ptr = start;
-  alpha = atan(-n->x[1]/n->x[2]);
-  Log() << Verbose(1) << "Z-Y-angle: " << alpha << " ... ";
+  alpha = atan(-n->at(1)/n->at(2));
+  DoLog(1) && (Log() << Verbose(1) << "Z-Y-angle: " << alpha << " ... ");
   while (ptr->next != end) {
     ptr = ptr->next;
-    tmp = ptr->x.x[1];
-    ptr->x.x[1] =  cos(alpha) * tmp + sin(alpha) * ptr->x.x[2];
-    ptr->x.x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->x.x[2];
+    tmp = ptr->x[1];
+    ptr->x[1] =  cos(alpha) * tmp + sin(alpha) * ptr->x[2];
+    ptr->x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->x[2];
     for (int j=0;j<MDSteps;j++) {
-      tmp = ptr->Trajectory.R.at(j).x[1];
-      ptr->Trajectory.R.at(j).x[1] =  cos(alpha) * tmp + sin(alpha) * ptr->Trajectory.R.at(j).x[2];
-      ptr->Trajectory.R.at(j).x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->Trajectory.R.at(j).x[2];
+      tmp = ptr->Trajectory.R.at(j)[1];
+      ptr->Trajectory.R.at(j)[1] =  cos(alpha) * tmp + sin(alpha) * ptr->Trajectory.R.at(j)[2];
+      ptr->Trajectory.R.at(j)[2] = -sin(alpha) * tmp + cos(alpha) * ptr->Trajectory.R.at(j)[2];
     }
   }
   // rotate n vector (for consistency check)
-  tmp = n->x[1];
-  n->x[1] =  cos(alpha) * tmp +  sin(alpha) * n->x[2];
-  n->x[2] = -sin(alpha) * tmp +  cos(alpha) * n->x[2];
-
-  Log() << Verbose(1) << "alignment vector after second rotation: ";
-  n->Output();
-  Log() << Verbose(1) << endl;
-  Log() << Verbose(0) << "End of Aligning all atoms." << endl;
+  tmp = n->at(1);
+  n->at(1) =  cos(alpha) * tmp +  sin(alpha) * n->at(2);
+  n->at(2) = -sin(alpha) * tmp +  cos(alpha) * n->at(2);
+
+
+  DoLog(1) && (Log() << Verbose(1) << "alignment vector after second rotation: " << n << endl);
+  DoLog(0) && (Log() << Verbose(0) << "End of Aligning all atoms." << endl);
 };
 
@@ -490,21 +490,19 @@
 
   // initialize vectors
-  a.x[0] = gsl_vector_get(x,0);
-  a.x[1] = gsl_vector_get(x,1);
-  a.x[2] = gsl_vector_get(x,2);
-  b.x[0] = gsl_vector_get(x,3);
-  b.x[1] = gsl_vector_get(x,4);
-  b.x[2] = gsl_vector_get(x,5);
+  a[0] = gsl_vector_get(x,0);
+  a[1] = gsl_vector_get(x,1);
+  a[2] = gsl_vector_get(x,2);
+  b[0] = gsl_vector_get(x,3);
+  b[1] = gsl_vector_get(x,4);
+  b[2] = gsl_vector_get(x,5);
   // go through all atoms
   while (ptr != par->mol->end) {
     ptr = ptr->next;
     if (ptr->type == ((struct lsq_params *)params)->type) { // for specific type
-      c.CopyVector(&ptr->x);  // copy vector to temporary one
-      c.SubtractVector(&a);   // subtract offset vector
-      t = c.ScalarProduct(&b);           // get direction parameter
-      d.CopyVector(&b);       // and create vector
-      d.Scale(&t);
-      c.SubtractVector(&d);   // ... yielding distance vector
-      res += d.ScalarProduct((const Vector *)&d);        // add squared distance
+      c = ptr->x - a;
+      t = c.ScalarProduct(b);           // get direction parameter
+      d = t*b;       // and create vector
+      c -= d;   // ... yielding distance vector
+      res += d.ScalarProduct(d);        // add squared distance
     }
   }
Index: src/molecule_graph.cpp
===================================================================
--- src/molecule_graph.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/molecule_graph.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -17,4 +17,6 @@
 #include "memoryallocator.hpp"
 #include "molecule.hpp"
+#include "World.hpp"
+#include "Helpers/fast_functions.hpp"
 
 struct BFSAccounting
@@ -58,10 +60,10 @@
 
   if (!input) {
-    Log() << Verbose(1) << "Opening silica failed \n";
+    DoLog(1) && (Log() << Verbose(1) << "Opening silica failed \n");
   };
 
   *input >> ws >> atom1;
   *input >> ws >> atom2;
-  Log() << Verbose(1) << "Scanning file\n";
+  DoLog(1) && (Log() << Verbose(1) << "Scanning file\n");
   while (!input->eof()) // Check whether we read everything already
   {
@@ -106,4 +108,5 @@
   LinkedCell *LC = NULL;
   bool free_BG = false;
+  double * const cell_size = World::getInstance().getDomain();
 
   if (BG == NULL) {
@@ -113,5 +116,5 @@
 
   BondDistance = bonddistance; // * ((IsAngstroem) ? 1. : 1./AtomicLengthToAngstroem);
-  Log() << Verbose(0) << "Begin of CreateAdjacencyList." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Begin of CreateAdjacencyList." << endl);
   // remove every bond from the list
   bond *Binder = NULL;
@@ -126,12 +129,12 @@
   // count atoms in molecule = dimension of matrix (also give each unique name and continuous numbering)
   CountAtoms();
-  Log() << Verbose(1) << "AtomCount " << AtomCount << " and bonddistance is " << bonddistance << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "AtomCount " << AtomCount << " and bonddistance is " << bonddistance << "." << endl);
 
   if ((AtomCount > 1) && (bonddistance > 1.)) {
-    Log() << Verbose(2) << "Creating Linked Cell structure ... " << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Creating Linked Cell structure ... " << endl);
     LC = new LinkedCell(this, bonddistance);
 
     // create a list to map Tesselpoint::nr to atom *
-    Log() << Verbose(2) << "Creating TesselPoint to atom map ... " << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Creating TesselPoint to atom map ... " << endl);
     AtomMap = Calloc<atom *> (AtomCount, "molecule::CreateAdjacencyList - **AtomCount");
     Walker = start;
@@ -142,33 +145,39 @@
 
     // 3a. go through every cell
-    Log() << Verbose(2) << "Celling ... " << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Celling ... " << endl);
     for (LC->n[0] = 0; LC->n[0] < LC->N[0]; LC->n[0]++)
       for (LC->n[1] = 0; LC->n[1] < LC->N[1]; LC->n[1]++)
         for (LC->n[2] = 0; LC->n[2] < LC->N[2]; LC->n[2]++) {
-          const LinkedNodes *List = LC->GetCurrentCell();
-          //Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << " containing " << List->size() << " points." << endl;
+          const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
+//          Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << " containing " << List->size() << " points." << endl;
           if (List != NULL) {
-            for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+            for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
               Walker = AtomMap[(*Runner)->nr];
-              //Log() << Verbose(0) << "Current Atom is " << *Walker << "." << endl;
+//              Log() << Verbose(0) << "Current Atom is " << *Walker << "." << endl;
               // 3c. check for possible bond between each atom in this and every one in the 27 cells
               for (n[0] = -1; n[0] <= 1; n[0]++)
                 for (n[1] = -1; n[1] <= 1; n[1]++)
                   for (n[2] = -1; n[2] <= 1; n[2]++) {
-                    const LinkedNodes *OtherList = LC->GetRelativeToCurrentCell(n);
-                    //Log() << Verbose(2) << "Current relative cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << " containing " << List->size() << " points." << endl;
+                    const LinkedCell::LinkedNodes *OtherList = LC->GetRelativeToCurrentCell(n);
+//                    Log() << Verbose(2) << "Current relative cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << " containing " << List->size() << " points." << endl;
                     if (OtherList != NULL) {
-                      for (LinkedNodes::const_iterator OtherRunner = OtherList->begin(); OtherRunner != OtherList->end(); OtherRunner++) {
+                      for (LinkedCell::LinkedNodes::const_iterator OtherRunner = OtherList->begin(); OtherRunner != OtherList->end(); OtherRunner++) {
                         if ((*OtherRunner)->nr > Walker->nr) {
                           OtherWalker = AtomMap[(*OtherRunner)->nr];
-                          //Log() << Verbose(1) << "Checking distance " << OtherWalker->x.PeriodicDistanceSquared(&(Walker->x), cell_size) << " against typical bond length of " << bonddistance*bonddistance << "." << endl;
+//                          Log() << Verbose(0) << "Current other Atom is " << *OtherWalker << "." << endl;
+                          const double distance = OtherWalker->x.PeriodicDistanceSquared(Walker->x, cell_size);
+//                          Log() << Verbose(1) << "Checking distance " << distance << " against typical bond length of " << bonddistance*bonddistance << "." << endl;
                           (BG->*minmaxdistance)(Walker, OtherWalker, MinDistance, MaxDistance, IsAngstroem);
-                          const double distance = OtherWalker->x.PeriodicDistanceSquared(&(Walker->x), cell_size);
                           const bool status = (distance <= MaxDistance * MaxDistance) && (distance >= MinDistance * MinDistance);
-                          if ((OtherWalker->father->nr > Walker->father->nr) && (status)) { // create bond if distance is smaller
-                            //Log() << Verbose(1) << "Adding Bond between " << *Walker << " and " << *OtherWalker << " in distance " << sqrt(distance) << "." << endl;
-                            AddBond(Walker->father, OtherWalker->father, 1); // also increases molecule::BondCount
+//                          Log() << Verbose(1) << "MinDistance is " << MinDistance << " and MaxDistance is " << MaxDistance << "." << endl;
+                          if (OtherWalker->father->nr > Walker->father->nr) {
+                            if (status) { // create bond if distance is smaller
+//                              Log() << Verbose(1) << "Adding Bond between " << *Walker << " and " << *OtherWalker << " in distance " << sqrt(distance) << "." << endl;
+                              AddBond(Walker->father, OtherWalker->father, 1); // also increases molecule::BondCount
+                            } else {
+//                              Log() << Verbose(1) << "Not Adding: distance too great." << endl;
+                            }
                           } else {
-                            //Log() << Verbose(1) << "Not Adding: Wrong label order or distance too great." << endl;
+//                            Log() << Verbose(1) << "Not Adding: Wrong order of labels." << endl;
                           }
                         }
@@ -181,8 +190,8 @@
     Free(&AtomMap);
     delete (LC);
-    Log() << Verbose(1) << "I detected " << BondCount << " bonds in the molecule with distance " << BondDistance << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "I detected " << BondCount << " bonds in the molecule with distance " << BondDistance << "." << endl);
 
     // correct bond degree by comparing valence and bond degree
-    Log() << Verbose(2) << "Correcting bond degree ... " << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Correcting bond degree ... " << endl);
     CorrectBondDegree();
 
@@ -190,6 +199,6 @@
     ActOnAllAtoms( &atom::OutputBondOfAtom );
   } else
-    Log() << Verbose(1) << "AtomCount is " << AtomCount << ", thus no bonds, no connections!." << endl;
-  Log() << Verbose(0) << "End of CreateAdjacencyList." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "AtomCount is " << AtomCount << ", thus no bonds, no connections!." << endl);
+  DoLog(0) && (Log() << Verbose(0) << "End of CreateAdjacencyList." << endl);
   if (free_BG)
     delete(BG);
@@ -202,11 +211,11 @@
 void molecule::OutputBondsList() const
 {
-  Log() << Verbose(1) << endl << "From contents of bond chain list:";
+  DoLog(1) && (Log() << Verbose(1) << endl << "From contents of bond chain list:");
   bond *Binder = first;
   while (Binder->next != last) {
     Binder = Binder->next;
-    Log() << Verbose(0) << *Binder << "\t" << endl;
-  }
-  Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << *Binder << "\t" << endl);
+  }
+  DoLog(0) && (Log() << Verbose(0) << endl);
 }
 ;
@@ -225,14 +234,14 @@
 
   if (BondCount != 0) {
-    Log() << Verbose(1) << "Correcting Bond degree of each bond ... " << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Correcting Bond degree of each bond ... " << endl);
     do {
       OldNo = No;
       No = SumPerAtom( &atom::CorrectBondDegree );
     } while (OldNo != No);
-    Log() << Verbose(0) << " done." << endl;
+    DoLog(0) && (Log() << Verbose(0) << " done." << endl);
   } else {
-    Log() << Verbose(1) << "BondCount is " << BondCount << ", no bonds between any of the " << AtomCount << " atoms." << endl;
-  }
-  Log() << Verbose(0) << No << " bonds could not be corrected." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "BondCount is " << BondCount << ", no bonds between any of the " << AtomCount << " atoms." << endl);
+  }
+  DoLog(0) && (Log() << Verbose(0) << No << " bonds could not be corrected." << endl);
 
   return (No);
@@ -253,5 +262,5 @@
   bond *Binder = first;
   if ((Binder->next != last) && (Binder->next->Type == Undetermined)) {
-    Log() << Verbose(0) << "No Depth-First-Search analysis performed so far, calling ..." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "No Depth-First-Search analysis performed so far, calling ..." << endl);
     Subgraphs = DepthFirstSearchAnalysis(BackEdgeStack);
     while (Subgraphs->next != NULL) {
@@ -308,5 +317,5 @@
     Walker->GraphNr = DFS.CurrentGraphNr;
     Walker->LowpointNr = DFS.CurrentGraphNr;
-    Log() << Verbose(1) << "Setting Walker[" << Walker->Name << "]'s number to " << Walker->GraphNr << " with Lowpoint " << Walker->LowpointNr << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Setting Walker[" << Walker->Name << "]'s number to " << Walker->GraphNr << " with Lowpoint " << Walker->LowpointNr << "." << endl);
     DFS.AtomStack->Push(Walker);
     DFS.CurrentGraphNr++;
@@ -335,9 +344,9 @@
     if (Binder == NULL)
       break;
-    Log() << Verbose(2) << "Current Unused Bond is " << *Binder << "." << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Current Unused Bond is " << *Binder << "." << endl);
     // (4) Mark Binder used, ...
     Binder->MarkUsed(black);
     OtherAtom = Binder->GetOtherAtom(Walker);
-    Log() << Verbose(2) << "(4) OtherAtom is " << OtherAtom->Name << "." << endl;
+    DoLog(2) && (Log() << Verbose(2) << "(4) OtherAtom is " << OtherAtom->Name << "." << endl);
     if (OtherAtom->GraphNr != -1) {
       // (4a) ... if "other" atom has been visited (GraphNr != 0), set lowpoint to minimum of both, go to (3)
@@ -345,5 +354,5 @@
       DFS.BackEdgeStack->Push(Binder);
       Walker->LowpointNr = (Walker->LowpointNr < OtherAtom->GraphNr) ? Walker->LowpointNr : OtherAtom->GraphNr;
-      Log() << Verbose(3) << "(4a) Visited: Setting Lowpoint of Walker[" << Walker->Name << "] to " << Walker->LowpointNr << "." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "(4a) Visited: Setting Lowpoint of Walker[" << Walker->Name << "] to " << Walker->LowpointNr << "." << endl);
     } else {
       // (4b) ... otherwise set OtherAtom as Ancestor of Walker and Walker as OtherAtom, go to (2)
@@ -351,5 +360,5 @@
       OtherAtom->Ancestor = Walker;
       Walker = OtherAtom;
-      Log() << Verbose(3) << "(4b) Not Visited: OtherAtom[" << OtherAtom->Name << "]'s Ancestor is now " << OtherAtom->Ancestor->Name << ", Walker is OtherAtom " << OtherAtom->Name << "." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "(4b) Not Visited: OtherAtom[" << OtherAtom->Name << "]'s Ancestor is now " << OtherAtom->Ancestor->Name << ", Walker is OtherAtom " << OtherAtom->Name << "." << endl);
       break;
     }
@@ -373,5 +382,5 @@
 
   // (5) if Ancestor of Walker is ...
-  Log() << Verbose(1) << "(5) Number of Walker[" << Walker->Name << "]'s Ancestor[" << Walker->Ancestor->Name << "] is " << Walker->Ancestor->GraphNr << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "(5) Number of Walker[" << Walker->Name << "]'s Ancestor[" << Walker->Ancestor->Name << "] is " << Walker->Ancestor->GraphNr << "." << endl);
 
   if (Walker->Ancestor->GraphNr != DFS.Root->GraphNr) {
@@ -380,23 +389,23 @@
       // (6a) set Ancestor's Lowpoint number to minimum of of its Ancestor and itself, go to Step(8)
       Walker->Ancestor->LowpointNr = (Walker->Ancestor->LowpointNr < Walker->LowpointNr) ? Walker->Ancestor->LowpointNr : Walker->LowpointNr;
-      Log() << Verbose(2) << "(6) Setting Walker[" << Walker->Name << "]'s Ancestor[" << Walker->Ancestor->Name << "]'s Lowpoint to " << Walker->Ancestor->LowpointNr << "." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "(6) Setting Walker[" << Walker->Name << "]'s Ancestor[" << Walker->Ancestor->Name << "]'s Lowpoint to " << Walker->Ancestor->LowpointNr << "." << endl);
     } else {
       // (7) (Ancestor of Walker is a separating vertex, remove all from stack till Walker (including), these and Ancestor form a component
       Walker->Ancestor->SeparationVertex = true;
-      Log() << Verbose(2) << "(7) Walker[" << Walker->Name << "]'s Ancestor[" << Walker->Ancestor->Name << "]'s is a separating vertex, creating component." << endl;
+      DoLog(2) && (Log() << Verbose(2) << "(7) Walker[" << Walker->Name << "]'s Ancestor[" << Walker->Ancestor->Name << "]'s is a separating vertex, creating component." << endl);
       mol->SetNextComponentNumber(Walker->Ancestor, DFS.ComponentNumber);
-      Log() << Verbose(3) << "(7) Walker[" << Walker->Name << "]'s Ancestor's Compont is " << DFS.ComponentNumber << "." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "(7) Walker[" << Walker->Name << "]'s Ancestor's Compont is " << DFS.ComponentNumber << "." << endl);
       mol->SetNextComponentNumber(Walker, DFS.ComponentNumber);
-      Log() << Verbose(3) << "(7) Walker[" << Walker->Name << "]'s Compont is " << DFS.ComponentNumber << "." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "(7) Walker[" << Walker->Name << "]'s Compont is " << DFS.ComponentNumber << "." << endl);
       do {
         OtherAtom = DFS.AtomStack->PopLast();
         LeafWalker->Leaf->AddCopyAtom(OtherAtom);
         mol->SetNextComponentNumber(OtherAtom, DFS.ComponentNumber);
-        Log() << Verbose(3) << "(7) Other[" << OtherAtom->Name << "]'s Compont is " << DFS.ComponentNumber << "." << endl;
+        DoLog(3) && (Log() << Verbose(3) << "(7) Other[" << OtherAtom->Name << "]'s Compont is " << DFS.ComponentNumber << "." << endl);
       } while (OtherAtom != Walker);
       DFS.ComponentNumber++;
     }
     // (8) Walker becomes its Ancestor, go to (3)
-    Log() << Verbose(2) << "(8) Walker[" << Walker->Name << "] is now its Ancestor " << Walker->Ancestor->Name << ", backstepping. " << endl;
+    DoLog(2) && (Log() << Verbose(2) << "(8) Walker[" << Walker->Name << "] is now its Ancestor " << Walker->Ancestor->Name << ", backstepping. " << endl);
     Walker = Walker->Ancestor;
     DFS.BackStepping = true;
@@ -422,12 +431,12 @@
     //DFS.AtomStack->Output(out);
     mol->SetNextComponentNumber(DFS.Root, DFS.ComponentNumber);
-    Log() << Verbose(3) << "(9) Root[" << DFS.Root->Name << "]'s Component is " << DFS.ComponentNumber << "." << endl;
+    DoLog(3) && (Log() << Verbose(3) << "(9) Root[" << DFS.Root->Name << "]'s Component is " << DFS.ComponentNumber << "." << endl);
     mol->SetNextComponentNumber(Walker, DFS.ComponentNumber);
-    Log() << Verbose(3) << "(9) Walker[" << Walker->Name << "]'s Component is " << DFS.ComponentNumber << "." << endl;
+    DoLog(3) && (Log() << Verbose(3) << "(9) Walker[" << Walker->Name << "]'s Component is " << DFS.ComponentNumber << "." << endl);
     do {
       OtherAtom = DFS.AtomStack->PopLast();
       LeafWalker->Leaf->AddCopyAtom(OtherAtom);
       mol->SetNextComponentNumber(OtherAtom, DFS.ComponentNumber);
-      Log() << Verbose(3) << "(7) Other[" << OtherAtom->Name << "]'s Compont is " << DFS.ComponentNumber << "." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "(7) Other[" << OtherAtom->Name << "]'s Compont is " << DFS.ComponentNumber << "." << endl);
     } while (OtherAtom != Walker);
     DFS.ComponentNumber++;
@@ -436,7 +445,7 @@
     Walker = DFS.Root;
     Binder = mol->FindNextUnused(Walker);
-    Log() << Verbose(1) << "(10) Walker is Root[" << DFS.Root->Name << "], next Unused Bond is " << Binder << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "(10) Walker is Root[" << DFS.Root->Name << "], next Unused Bond is " << Binder << "." << endl);
     if (Binder != NULL) { // Root is separation vertex
-      Log() << Verbose(1) << "(11) Root is a separation vertex." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "(11) Root is a separation vertex." << endl);
       Walker->SeparationVertex = true;
     }
@@ -493,5 +502,7 @@
   bond *Binder = NULL;
 
-  Log() << Verbose(0) << "Begin of DepthFirstSearchAnalysis" << endl;
+  if (AtomCount == 0)
+    return SubGraphs;
+  DoLog(0) && (Log() << Verbose(0) << "Begin of DepthFirstSearchAnalysis" << endl);
   DepthFirstSearchAnalysis_Init(DFS, this);
 
@@ -503,5 +514,5 @@
     // put into new subgraph molecule and add this to list of subgraphs
     LeafWalker = new MoleculeLeafClass(LeafWalker);
-    LeafWalker->Leaf = new molecule(elemente);
+    LeafWalker->Leaf = World::getInstance().createMolecule();
     LeafWalker->Leaf->AddCopyAtom(DFS.Root);
 
@@ -515,5 +526,5 @@
 
         if (Binder == NULL) {
-          Log() << Verbose(2) << "No more Unused Bonds." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "No more Unused Bonds." << endl);
           break;
         } else
@@ -532,7 +543,7 @@
 
     // From OldGraphNr to CurrentGraphNr ranges an disconnected subgraph
-    Log() << Verbose(0) << "Disconnected subgraph ranges from " << OldGraphNr << " to " << DFS.CurrentGraphNr << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Disconnected subgraph ranges from " << OldGraphNr << " to " << DFS.CurrentGraphNr << "." << endl);
     LeafWalker->Leaf->Output((ofstream *)&cout);
-    Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl);
 
     // step on to next root
@@ -552,5 +563,5 @@
   // free all and exit
   DepthFirstSearchAnalysis_Finalize(DFS);
-  Log() << Verbose(0) << "End of DepthFirstSearchAnalysis" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "End of DepthFirstSearchAnalysis" << endl);
   return SubGraphs;
 }
@@ -578,5 +589,5 @@
 void molecule::OutputGraphInfoPerAtom() const
 {
-  Log() << Verbose(1) << "Final graph info for each atom is:" << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Final graph info for each atom is:" << endl);
   ActOnAllAtoms( &atom::OutputGraphInfo );
 }
@@ -588,17 +599,17 @@
 void molecule::OutputGraphInfoPerBond() const
 {
-  Log() << Verbose(1) << "Final graph info for each bond is:" << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Final graph info for each bond is:" << endl);
   bond *Binder = first;
   while (Binder->next != last) {
     Binder = Binder->next;
-    Log() << Verbose(2) << ((Binder->Type == TreeEdge) ? "TreeEdge " : "BackEdge ") << *Binder << ": <";
-    Log() << Verbose(0) << ((Binder->leftatom->SeparationVertex) ? "SP," : "") << "L" << Binder->leftatom->LowpointNr << " G" << Binder->leftatom->GraphNr << " Comp.";
+    DoLog(2) && (Log() << Verbose(2) << ((Binder->Type == TreeEdge) ? "TreeEdge " : "BackEdge ") << *Binder << ": <");
+    DoLog(0) && (Log() << Verbose(0) << ((Binder->leftatom->SeparationVertex) ? "SP," : "") << "L" << Binder->leftatom->LowpointNr << " G" << Binder->leftatom->GraphNr << " Comp.");
     Binder->leftatom->OutputComponentNumber();
-    Log() << Verbose(0) << " ===  ";
-    Log() << Verbose(0) << ((Binder->rightatom->SeparationVertex) ? "SP," : "") << "L" << Binder->rightatom->LowpointNr << " G" << Binder->rightatom->GraphNr << " Comp.";
+    DoLog(0) && (Log() << Verbose(0) << " ===  ");
+    DoLog(0) && (Log() << Verbose(0) << ((Binder->rightatom->SeparationVertex) ? "SP," : "") << "L" << Binder->rightatom->LowpointNr << " G" << Binder->rightatom->GraphNr << " Comp.");
     Binder->rightatom->OutputComponentNumber();
-    Log() << Verbose(0) << ">." << endl;
+    DoLog(0) && (Log() << Verbose(0) << ">." << endl);
     if (Binder->Cyclic) // cyclic ??
-      Log() << Verbose(3) << "Lowpoint at each side are equal: CYCLIC!" << endl;
+      DoLog(3) && (Log() << Verbose(3) << "Lowpoint at each side are equal: CYCLIC!" << endl);
   }
 }
@@ -674,5 +685,5 @@
   do { // look for Root
     Walker = BFS.BFSStack->PopFirst();
-    Log() << Verbose(2) << "Current Walker is " << *Walker << ", we look for SP to Root " << *BFS.Root << "." << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Current Walker is " << *Walker << ", we look for SP to Root " << *BFS.Root << "." << endl);
     for (BondList::const_iterator Runner = Walker->ListOfBonds.begin(); Runner != Walker->ListOfBonds.end(); (++Runner)) {
       if ((*Runner) != BackEdge) { // only walk along DFS spanning tree (otherwise we always find SP of one being backedge Binder)
@@ -681,5 +692,5 @@
         if (OtherAtom->type->Z != 1) {
 #endif
-        Log() << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *(*Runner) << "." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *(*Runner) << "." << endl);
         if (BFS.ColorList[OtherAtom->nr] == white) {
           BFS.TouchedStack->Push(OtherAtom);
@@ -687,11 +698,11 @@
           BFS.PredecessorList[OtherAtom->nr] = Walker; // Walker is the predecessor
           BFS.ShortestPathList[OtherAtom->nr] = BFS.ShortestPathList[Walker->nr] + 1;
-          Log() << Verbose(2) << "Coloring OtherAtom " << OtherAtom->Name << " lightgray, its predecessor is " << Walker->Name << " and its Shortest Path is " << BFS.ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "Coloring OtherAtom " << OtherAtom->Name << " lightgray, its predecessor is " << Walker->Name << " and its Shortest Path is " << BFS.ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl);
           //if (BFS.ShortestPathList[OtherAtom->nr] < MinimumRingSize[Walker->GetTrueFather()->nr]) { // Check for maximum distance
-          Log() << Verbose(3) << "Putting OtherAtom into queue." << endl;
+          DoLog(3) && (Log() << Verbose(3) << "Putting OtherAtom into queue." << endl);
           BFS.BFSStack->Push(OtherAtom);
           //}
         } else {
-          Log() << Verbose(3) << "Not Adding, has already been visited." << endl;
+          DoLog(3) && (Log() << Verbose(3) << "Not Adding, has already been visited." << endl);
         }
         if (OtherAtom == BFS.Root)
@@ -699,14 +710,14 @@
 #ifdef ADDHYDROGEN
       } else {
-        Log() << Verbose(2) << "Skipping hydrogen atom " << *OtherAtom << "." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Skipping hydrogen atom " << *OtherAtom << "." << endl);
         BFS.ColorList[OtherAtom->nr] = black;
       }
 #endif
       } else {
-        Log() << Verbose(2) << "Bond " << *(*Runner) << " not Visiting, is the back edge." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Bond " << *(*Runner) << " not Visiting, is the back edge." << endl);
       }
     }
     BFS.ColorList[Walker->nr] = black;
-    Log() << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl);
     if (OtherAtom == BFS.Root) { // if we have found the root, check whether this cycle wasn't already found beforehand
       // step through predecessor list
@@ -718,9 +729,9 @@
       }
       if (OtherAtom == BackEdge->rightatom) { // if each atom in found cycle is cyclic, loop's been found before already
-        Log() << Verbose(3) << "This cycle was already found before, skipping and removing seeker from search." << endl;
+        DoLog(3) && (Log() << Verbose(3) << "This cycle was already found before, skipping and removing seeker from search." << endl);
         do {
           OtherAtom = BFS.TouchedStack->PopLast();
           if (BFS.PredecessorList[OtherAtom->nr] == Walker) {
-            Log() << Verbose(4) << "Removing " << *OtherAtom << " from lists and stacks." << endl;
+            DoLog(4) && (Log() << Verbose(4) << "Removing " << *OtherAtom << " from lists and stacks." << endl);
             BFS.PredecessorList[OtherAtom->nr] = NULL;
             BFS.ShortestPathList[OtherAtom->nr] = -1;
@@ -756,13 +767,13 @@
     RingSize = 1;
     BFS.Root->GetTrueFather()->IsCyclic = true;
-    Log() << Verbose(1) << "Found ring contains: ";
+    DoLog(1) && (Log() << Verbose(1) << "Found ring contains: ");
     Walker = BFS.Root;
     while (Walker != BackEdge->rightatom) {
-      Log() << Verbose(0) << Walker->Name << " <-> ";
+      DoLog(0) && (Log() << Verbose(0) << Walker->Name << " <-> ");
       Walker = BFS.PredecessorList[Walker->nr];
       Walker->GetTrueFather()->IsCyclic = true;
       RingSize++;
     }
-    Log() << Verbose(0) << Walker->Name << "  with a length of " << RingSize << "." << endl << endl;
+    DoLog(0) && (Log() << Verbose(0) << Walker->Name << "  with a length of " << RingSize << "." << endl << endl);
     // walk through all and set MinimumRingSize
     Walker = BFS.Root;
@@ -776,5 +787,5 @@
       MinRingSize = RingSize;
   } else {
-    Log() << Verbose(1) << "No ring containing " << *BFS.Root << " with length equal to or smaller than " << MinimumRingSize[Walker->GetTrueFather()->nr] << " found." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "No ring containing " << *BFS.Root << " with length equal to or smaller than " << MinimumRingSize[Walker->GetTrueFather()->nr] << " found." << endl);
   }
 };
@@ -854,9 +865,9 @@
 
       }
-      Log() << Verbose(1) << "Minimum ring size of " << *Root << " is " << MinimumRingSize[Root->GetTrueFather()->nr] << "." << endl;
-    }
-    Log() << Verbose(1) << "Minimum ring size is " << MinRingSize << ", over " << NumCycles << " cycles total." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Minimum ring size of " << *Root << " is " << MinimumRingSize[Root->GetTrueFather()->nr] << "." << endl);
+    }
+    DoLog(1) && (Log() << Verbose(1) << "Minimum ring size is " << MinRingSize << ", over " << NumCycles << " cycles total." << endl);
   } else
-    Log() << Verbose(1) << "No rings were detected in the molecular structure." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "No rings were detected in the molecular structure." << endl);
 }
 ;
@@ -886,5 +897,5 @@
   //BackEdgeStack->Output(out);
 
-  Log() << Verbose(1) << "Analysing cycles ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Analysing cycles ... " << endl);
   NumCycles = 0;
   while (!BackEdgeStack->IsEmpty()) {
@@ -897,5 +908,5 @@
     ResetBFSAccounting(Walker, BFS);
 
-    Log() << Verbose(1) << "---------------------------------------------------------------------------------------------------------" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "---------------------------------------------------------------------------------------------------------" << endl);
     OtherAtom = NULL;
     CyclicStructureAnalysis_CyclicBFSFromRootToRoot(BackEdge, BFS);
@@ -927,9 +938,9 @@
     }
     if (i == vertex->ListOfBonds.size()) {
-      eLog() << Verbose(0) << "Error: All Component entries are already occupied!" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Error: All Component entries are already occupied!" << endl);
       performCriticalExit();
     }
   } else {
-    eLog() << Verbose(0) << "Error: Given vertex is NULL!" << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "Error: Given vertex is NULL!" << endl);
     performCriticalExit();
   }
@@ -969,8 +980,8 @@
 void OutputAlreadyVisited(int *list)
 {
-  Log() << Verbose(4) << "Already Visited Bonds:\t";
+  DoLog(4) && (Log() << Verbose(4) << "Already Visited Bonds:\t");
   for (int i = 1; i <= list[0]; i++)
-    Log() << Verbose(0) << list[i] << "  ";
-  Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << list[i] << "  ");
+  DoLog(0) && (Log() << Verbose(0) << endl);
 }
 ;
@@ -978,9 +989,9 @@
 /** Storing the bond structure of a molecule to file.
  * Simply stores Atom::nr and then the Atom::nr of all bond partners per line.
- * \param *out output stream for debugging
  * \param *path path to file
+ * \param *filename name of file
  * \return true - file written successfully, false - writing failed
  */
-bool molecule::StoreAdjacencyToFile(char *path)
+bool molecule::StoreAdjacencyToFile(char *path, char *filename)
 {
   ofstream AdjacencyFile;
@@ -988,14 +999,17 @@
   bool status = true;
 
-  line << path << "/" << FRAGMENTPREFIX << ADJACENCYFILE;
+  if (path != NULL)
+    line << path << "/" << filename;
+  else
+    line << filename;
   AdjacencyFile.open(line.str().c_str(), ios::out);
-  Log() << Verbose(1) << "Saving adjacency list ... ";
+  DoLog(1) && (Log() << Verbose(1) << "Saving adjacency list ... ");
   if (AdjacencyFile != NULL) {
     AdjacencyFile << "m\tn" << endl;
     ActOnAllAtoms(&atom::OutputAdjacency, &AdjacencyFile);
     AdjacencyFile.close();
-    Log() << Verbose(1) << "done." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
   } else {
-    Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl);
     status = false;
   }
@@ -1007,9 +1021,9 @@
 /** Storing the bond structure of a molecule to file.
  * Simply stores Atom::nr and then the Atom::nr of all bond partners, one per line.
- * \param *out output stream for debugging
  * \param *path path to file
+ * \param *filename name of file
  * \return true - file written successfully, false - writing failed
  */
-bool molecule::StoreBondsToFile(char *path)
+bool molecule::StoreBondsToFile(char *path, char *filename)
 {
   ofstream BondFile;
@@ -1017,14 +1031,17 @@
   bool status = true;
 
-  line << path << "/" << FRAGMENTPREFIX << ADJACENCYFILE;
+  if (path != NULL)
+    line << path << "/" << filename;
+  else
+    line << filename;
   BondFile.open(line.str().c_str(), ios::out);
-  Log() << Verbose(1) << "Saving adjacency list ... ";
+  DoLog(1) && (Log() << Verbose(1) << "Saving adjacency list ... ");
   if (BondFile != NULL) {
     BondFile << "m\tn" << endl;
     ActOnAllAtoms(&atom::OutputBonds, &BondFile);
     BondFile.close();
-    Log() << Verbose(1) << "done." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
   } else {
-    Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl);
     status = false;
   }
@@ -1039,5 +1056,5 @@
   filename << path << "/" << FRAGMENTPREFIX << ADJACENCYFILE;
   File.open(filename.str().c_str(), ios::out);
-  Log() << Verbose(1) << "Looking at bond structure stored in adjacency file and comparing to present one ... ";
+  DoLog(1) && (Log() << Verbose(1) << "Looking at bond structure stored in adjacency file and comparing to present one ... ");
   if (File == NULL)
     return false;
@@ -1080,5 +1097,5 @@
     //Log() << Verbose(0) << endl;
   } else {
-    Log() << Verbose(0) << "Number of bonds for Atom " << *Walker << " does not match, parsed " << CurrentBondsOfAtom << " against " << Walker->ListOfBonds.size() << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Number of bonds for Atom " << *Walker << " does not match, parsed " << CurrentBondsOfAtom << " against " << Walker->ListOfBonds.size() << "." << endl);
     status = false;
   }
@@ -1103,5 +1120,5 @@
 
   if (!CheckAdjacencyFileAgainstMolecule_Init(path, File, CurrentBonds)) {
-    Log() << Verbose(1) << "Adjacency file not found." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Adjacency file not found." << endl);
     return true;
   }
@@ -1129,7 +1146,7 @@
 
   if (status) { // if equal we parse the KeySetFile
-    Log() << Verbose(1) << "done: Equal." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done: Equal." << endl);
   } else
-    Log() << Verbose(1) << "done: Not equal by " << NonMatchNumber << " atoms." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done: Not equal by " << NonMatchNumber << " atoms." << endl);
   return status;
 }
@@ -1147,5 +1164,5 @@
   bool status = true;
   if (ReferenceStack->IsEmpty()) {
-    Log() << Verbose(1) << "ReferenceStack is empty!" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "ReferenceStack is empty!" << endl);
     return false;
   }
@@ -1162,10 +1179,10 @@
         if (OtherAtom == ListOfLocalAtoms[(*Runner)->rightatom->nr]) { // found the bond
           LocalStack->Push((*Runner));
-          Log() << Verbose(3) << "Found local edge " << *(*Runner) << "." << endl;
+          DoLog(3) && (Log() << Verbose(3) << "Found local edge " << *(*Runner) << "." << endl);
           break;
         }
       }
     Binder = ReferenceStack->PopFirst(); // loop the stack for next item
-    Log() << Verbose(3) << "Current candidate edge " << Binder << "." << endl;
+    DoLog(3) && (Log() << Verbose(3) << "Current candidate edge " << Binder << "." << endl);
     ReferenceStack->Push(Binder);
   } while (FirstBond != Binder);
@@ -1216,21 +1233,21 @@
   BFS.PredecessorList[OtherAtom->nr] = Walker; // Walker is the predecessor
   BFS.ShortestPathList[OtherAtom->nr] = BFS.ShortestPathList[Walker->nr] + 1;
-  Log() << Verbose(2) << "Coloring OtherAtom " << OtherAtom->Name << " " << ((BFS.ColorList[OtherAtom->nr] == white) ? "white" : "lightgray") << ", its predecessor is " << Walker->Name << " and its Shortest Path is " << BFS.ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Coloring OtherAtom " << OtherAtom->Name << " " << ((BFS.ColorList[OtherAtom->nr] == white) ? "white" : "lightgray") << ", its predecessor is " << Walker->Name << " and its Shortest Path is " << BFS.ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl);
   if ((((BFS.ShortestPathList[OtherAtom->nr] < BFS.BondOrder) && (Binder != Bond)))) { // Check for maximum distance
-    Log() << Verbose(3);
+    DoLog(3) && (Log() << Verbose(3));
     if (AddedAtomList[OtherAtom->nr] == NULL) { // add if it's not been so far
       AddedAtomList[OtherAtom->nr] = Mol->AddCopyAtom(OtherAtom);
-      Log() << Verbose(0) << "Added OtherAtom " << OtherAtom->Name;
+      DoLog(0) && (Log() << Verbose(0) << "Added OtherAtom " << OtherAtom->Name);
       AddedBondList[Binder->nr] = Mol->CopyBond(AddedAtomList[Walker->nr], AddedAtomList[OtherAtom->nr], Binder);
-      Log() << Verbose(0) << " and bond " << *(AddedBondList[Binder->nr]) << ", ";
+      DoLog(0) && (Log() << Verbose(0) << " and bond " << *(AddedBondList[Binder->nr]) << ", ");
     } else { // this code should actually never come into play (all white atoms are not yet present in BondMolecule, that's why they are white in the first place)
-      Log() << Verbose(0) << "Not adding OtherAtom " << OtherAtom->Name;
+      DoLog(0) && (Log() << Verbose(0) << "Not adding OtherAtom " << OtherAtom->Name);
       if (AddedBondList[Binder->nr] == NULL) {
         AddedBondList[Binder->nr] = Mol->CopyBond(AddedAtomList[Walker->nr], AddedAtomList[OtherAtom->nr], Binder);
-        Log() << Verbose(0) << ", added Bond " << *(AddedBondList[Binder->nr]);
+        DoLog(0) && (Log() << Verbose(0) << ", added Bond " << *(AddedBondList[Binder->nr]));
       } else
-        Log() << Verbose(0) << ", not added Bond ";
-    }
-    Log() << Verbose(0) << ", putting OtherAtom into queue." << endl;
+        DoLog(0) && (Log() << Verbose(0) << ", not added Bond ");
+    }
+    DoLog(0) && (Log() << Verbose(0) << ", putting OtherAtom into queue." << endl);
     BFS.BFSStack->Push(OtherAtom);
   } else { // out of bond order, then replace
@@ -1238,9 +1255,9 @@
       BFS.ColorList[OtherAtom->nr] = white; // unmark if it has not been queued/added, to make it available via its other bonds (cyclic)
     if (Binder == Bond)
-      Log() << Verbose(3) << "Not Queueing, is the Root bond";
+      DoLog(3) && (Log() << Verbose(3) << "Not Queueing, is the Root bond");
     else if (BFS.ShortestPathList[OtherAtom->nr] >= BFS.BondOrder)
-      Log() << Verbose(3) << "Not Queueing, is out of Bond Count of " << BFS.BondOrder;
+      DoLog(3) && (Log() << Verbose(3) << "Not Queueing, is out of Bond Count of " << BFS.BondOrder);
     if (!Binder->Cyclic)
-      Log() << Verbose(0) << ", is not part of a cyclic bond, saturating bond with Hydrogen." << endl;
+      DoLog(0) && (Log() << Verbose(0) << ", is not part of a cyclic bond, saturating bond with Hydrogen." << endl);
     if (AddedBondList[Binder->nr] == NULL) {
       if ((AddedAtomList[OtherAtom->nr] != NULL)) { // .. whether we add or saturate
@@ -1259,5 +1276,5 @@
 void BreadthFirstSearchAdd_VisitedNode(molecule *Mol, struct BFSAccounting &BFS, atom *&Walker, atom *&OtherAtom, bond *&Binder, bond *&Bond, atom **&AddedAtomList, bond **&AddedBondList, bool IsAngstroem)
 {
-  Log() << Verbose(3) << "Not Adding, has already been visited." << endl;
+  DoLog(3) && (Log() << Verbose(3) << "Not Adding, has already been visited." << endl);
   // This has to be a cyclic bond, check whether it's present ...
   if (AddedBondList[Binder->nr] == NULL) {
@@ -1305,10 +1322,10 @@
     // followed by n+1 till top of stack.
     Walker = BFS.BFSStack->PopFirst(); // pop oldest added
-    Log() << Verbose(1) << "Current Walker is: " << Walker->Name << ", and has " << Walker->ListOfBonds.size() << " bonds." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Current Walker is: " << Walker->Name << ", and has " << Walker->ListOfBonds.size() << " bonds." << endl);
     for (BondList::const_iterator Runner = Walker->ListOfBonds.begin(); Runner != Walker->ListOfBonds.end(); (++Runner)) {
       if ((*Runner) != NULL) { // don't look at bond equal NULL
         Binder = (*Runner);
         OtherAtom = (*Runner)->GetOtherAtom(Walker);
-        Log() << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *(*Runner) << "." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *(*Runner) << "." << endl);
         if (BFS.ColorList[OtherAtom->nr] == white) {
           BreadthFirstSearchAdd_UnvisitedNode(Mol, BFS, Walker, OtherAtom, Binder, Bond, AddedAtomList, AddedBondList, IsAngstroem);
@@ -1319,5 +1336,5 @@
     }
     BFS.ColorList[Walker->nr] = black;
-    Log() << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl);
   }
   BreadthFirstSearchAdd_Free(BFS);
@@ -1344,5 +1361,5 @@
   // reset parent list
   ParentList = Calloc<atom*> (AtomCount, "molecule::BuildInducedSubgraph_Init: **ParentList");
-  Log() << Verbose(3) << "Resetting ParentList." << endl;
+  DoLog(3) && (Log() << Verbose(3) << "Resetting ParentList." << endl);
 }
 ;
@@ -1351,5 +1368,5 @@
 {
   // fill parent list with sons
-  Log() << Verbose(3) << "Filling Parent List." << endl;
+  DoLog(3) && (Log() << Verbose(3) << "Filling Parent List." << endl);
   atom *Walker = mol->start;
   while (Walker->next != mol->end) {
@@ -1357,5 +1374,5 @@
     ParentList[Walker->father->nr] = Walker;
     // Outputting List for debugging
-    Log() << Verbose(4) << "Son[" << Walker->father->nr << "] of " << Walker->father << " is " << ParentList[Walker->father->nr] << "." << endl;
+    DoLog(4) && (Log() << Verbose(4) << "Son[" << Walker->father->nr << "] of " << Walker->father << " is " << ParentList[Walker->father->nr] << "." << endl);
   }
 
@@ -1375,5 +1392,5 @@
   atom *OtherAtom = NULL;
   // check each entry of parent list and if ok (one-to-and-onto matching) create bonds
-  Log() << Verbose(3) << "Creating bonds." << endl;
+  DoLog(3) && (Log() << Verbose(3) << "Creating bonds." << endl);
   Walker = Father->start;
   while (Walker->next != Father->end) {
@@ -1386,5 +1403,5 @@
           OtherAtom = (*Runner)->GetOtherAtom(Walker);
           if (ParentList[OtherAtom->nr] != NULL) { // if otheratom is also a father of an atom on this molecule, create the bond
-            Log() << Verbose(4) << "Endpoints of Bond " << (*Runner) << " are both present: " << ParentList[Walker->nr]->Name << " and " << ParentList[OtherAtom->nr]->Name << "." << endl;
+            DoLog(4) && (Log() << Verbose(4) << "Endpoints of Bond " << (*Runner) << " are both present: " << ParentList[Walker->nr]->Name << " and " << ParentList[OtherAtom->nr]->Name << "." << endl);
             mol->AddBond(ParentList[Walker->nr], ParentList[OtherAtom->nr], (*Runner)->BondDegree);
           }
@@ -1411,10 +1428,10 @@
   atom **ParentList = NULL;
 
-  Log() << Verbose(2) << "Begin of BuildInducedSubgraph." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Begin of BuildInducedSubgraph." << endl);
   BuildInducedSubgraph_Init(ParentList, Father->AtomCount);
   BuildInducedSubgraph_FillParentList(this, Father, ParentList);
   status = BuildInducedSubgraph_CreateBondsFromParent(this, Father, ParentList);
   BuildInducedSubgraph_Finalize(ParentList);
-  Log() << Verbose(2) << "End of BuildInducedSubgraph." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "End of BuildInducedSubgraph." << endl);
   return status;
 }
@@ -1433,6 +1450,6 @@
   int size;
 
-  Log() << Verbose(1) << "Begin of CheckForConnectedSubgraph" << endl;
-  Log() << Verbose(2) << "Disconnected atom: ";
+  DoLog(1) && (Log() << Verbose(1) << "Begin of CheckForConnectedSubgraph" << endl);
+  DoLog(2) && (Log() << Verbose(2) << "Disconnected atom: ");
 
   // count number of atoms in graph
@@ -1456,15 +1473,15 @@
       }
       if (!BondStatus) {
-        Log() << Verbose(0) << (*Walker) << endl;
+        DoLog(0) && (Log() << Verbose(0) << (*Walker) << endl);
         return false;
       }
     }
   else {
-    Log() << Verbose(0) << "none." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "none." << endl);
     return true;
   }
-  Log() << Verbose(0) << "none." << endl;
-
-  Log() << Verbose(1) << "End of CheckForConnectedSubgraph" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "none." << endl);
+
+  DoLog(1) && (Log() << Verbose(1) << "End of CheckForConnectedSubgraph" << endl);
 
   return true;
Index: src/molecule_template.hpp
===================================================================
--- src/molecule_template.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/molecule_template.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -16,4 +16,5 @@
 #endif
 
+#include "atom.hpp"
 /********************************************** declarations *******************************/
 
@@ -54,4 +55,20 @@
   }
 };
+template <typename res, typename T> void molecule::ActOnAllVectors( res (Vector::*f)(T&), T &t ) const
+{
+  atom *Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    ((Walker->node)->*f)(t);
+  }
+};
+template <typename res, typename T> void molecule::ActOnAllVectors( res (Vector::*f)(T&) const, T &t ) const
+{
+  atom *Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    ((Walker->node)->*f)(t);
+  }
+};
 // two arguments
 template <typename res, typename T, typename U> void molecule::ActOnAllVectors( res (Vector::*f)(T, U), T t, U u ) const
Index: src/moleculelist.cpp
===================================================================
--- src/moleculelist.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/moleculelist.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -7,4 +7,5 @@
 #include <cstring>
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
@@ -19,4 +20,5 @@
 #include "memoryallocator.hpp"
 #include "periodentafel.hpp"
+#include "World.hpp"
 
 /*********************************** Functions for class MoleculeListClass *************************/
@@ -24,5 +26,6 @@
 /** Constructor for MoleculeListClass.
  */
-MoleculeListClass::MoleculeListClass()
+MoleculeListClass::MoleculeListClass(World *_world) :
+  world(_world)
 {
   // empty lists
@@ -35,10 +38,10 @@
 MoleculeListClass::~MoleculeListClass()
 {
-  Log() << Verbose(3) << this << ": Freeing ListOfMolcules." << endl;
+  DoLog(3) && (Log() << Verbose(3) << this << ": Freeing ListOfMolcules." << endl);
   for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
-    Log() << Verbose(4) << "ListOfMolecules: Freeing " << *ListRunner << "." << endl;
-    delete (*ListRunner);
-  }
-  Log() << Verbose(4) << "Freeing ListOfMolecules." << endl;
+    DoLog(4) && (Log() << Verbose(4) << "ListOfMolecules: Freeing " << *ListRunner << "." << endl);
+    world->destroyMolecule(*ListRunner);
+  }
+  DoLog(4) && (Log() << Verbose(4) << "Freeing ListOfMolecules." << endl);
   ListOfMolecules.clear(); // empty list
 };
@@ -137,9 +140,9 @@
  * \param *out output stream
  */
-void MoleculeListClass::Enumerate(ofstream *out)
-{
-  element* Elemental = NULL;
+void MoleculeListClass::Enumerate(ostream *out)
+{
   atom *Walker = NULL;
-  int Counts[MAX_ELEMENTS];
+  periodentafel *periode = World::getInstance().getPeriode();
+  std::map<atomicNumber_t,unsigned int> counts;
   double size=0;
   Vector Origin;
@@ -153,7 +156,4 @@
     Origin.Zero();
     for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
-      // reset element counts
-      for (int j = 0; j<MAX_ELEMENTS;j++)
-        Counts[j] = 0;
       // count atoms per element and determine size of bounding sphere
       size=0.;
@@ -161,15 +161,15 @@
       while (Walker->next != (*ListRunner)->end) {
         Walker = Walker->next;
-        Counts[Walker->type->Z]++;
-        if (Walker->x.DistanceSquared(&Origin) > size)
-          size = Walker->x.DistanceSquared(&Origin);
+        counts[Walker->type->getNumber()]++;
+        if (Walker->x.DistanceSquared(Origin) > size)
+          size = Walker->x.DistanceSquared(Origin);
       }
       // output Index, Name, number of atoms, chemical formula
       (*out) << ((*ListRunner)->ActiveFlag ? "*" : " ") << (*ListRunner)->IndexNr << "\t" << (*ListRunner)->name << "\t\t" << (*ListRunner)->AtomCount << "\t";
-      Elemental = (*ListRunner)->elemente->end;
-      while(Elemental->previous != (*ListRunner)->elemente->start) {
-        Elemental = Elemental->previous;
-        if (Counts[Elemental->Z] != 0)
-          (*out) << Elemental->symbol << Counts[Elemental->Z];
+
+      std::map<atomicNumber_t,unsigned int>::reverse_iterator iter;
+      for(iter=counts.rbegin(); iter!=counts.rend();++iter){
+        atomicNumber_t Z =(*iter).first;
+        (*out) << periode->FindElement(Z)->getSymbol() << (*iter).second;
       }
       // Center and size
@@ -213,5 +213,5 @@
   // remove src
   ListOfMolecules.remove(srcmol);
-  delete(srcmol);
+  World::getInstance().destroyMolecule(srcmol);
   return true;
 };
@@ -315,5 +315,5 @@
   Tesselation *TesselStruct = NULL;
   if ((srcmol == NULL) || (mol == NULL)) {
-    eLog() << Verbose(1) << "Either fixed or variable molecule is given as NULL." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Either fixed or variable molecule is given as NULL." << endl);
     return false;
   }
@@ -323,5 +323,5 @@
   FindNonConvexBorder(mol, TesselStruct, (const LinkedCell *&)LCList, 4., NULL);
   if (TesselStruct == NULL) {
-    eLog() << Verbose(1) << "Could not tesselate the fixed molecule." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Could not tesselate the fixed molecule." << endl);
     return false;
   }
@@ -340,7 +340,7 @@
   while (Walker->next != srcmol->end) {
     Walker = Walker->next;
-    Log() << Verbose(2) << "INFO: Current Walker is " << *Walker << "." << endl;
+    DoLog(2) && (Log() << Verbose(2) << "INFO: Current Walker is " << *Walker << "." << endl);
     if (!TesselStruct->IsInnerPoint(Walker->x, LCList)) {
-      CopyAtoms[Walker->nr] = new atom(Walker);
+      CopyAtoms[Walker->nr] = Walker->clone();
       mol->AddAtom(CopyAtoms[Walker->nr]);
       nr++;
@@ -349,5 +349,5 @@
     }
   }
-  Log() << Verbose(1) << nr << " of " << srcmol->AtomCount << " atoms have been merged.";
+  DoLog(1) && (Log() << Verbose(1) << nr << " of " << srcmol->AtomCount << " atoms have been merged.");
 
   // go through all bonds and add as well
@@ -355,5 +355,5 @@
   while(Binder->next != srcmol->last) {
     Binder = Binder->next;
-    Log() << Verbose(3) << "Adding Bond between " << *CopyAtoms[Binder->leftatom->nr] << " and " << *CopyAtoms[Binder->rightatom->nr]<< "." << endl;
+    DoLog(3) && (Log() << Verbose(3) << "Adding Bond between " << *CopyAtoms[Binder->leftatom->nr] << " and " << *CopyAtoms[Binder->rightatom->nr]<< "." << endl);
     mol->AddBond(CopyAtoms[Binder->leftatom->nr], CopyAtoms[Binder->rightatom->nr], Binder->BondDegree);
   }
@@ -367,8 +367,8 @@
 void MoleculeListClass::Output(ofstream *out)
 {
-  Log() << Verbose(1) << "MoleculeList: ";
+  DoLog(1) && (Log() << Verbose(1) << "MoleculeList: ");
   for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
-    Log() << Verbose(0) << *ListRunner << "\t";
-  Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << *ListRunner << "\t");
+  DoLog(0) && (Log() << Verbose(0) << endl);
 };
 
@@ -396,5 +396,5 @@
   char *FragmentNumber = NULL;
 
-  Log() << Verbose(1) << "Saving hydrogen saturation correction ... ";
+  DoLog(1) && (Log() << Verbose(1) << "Saving hydrogen saturation correction ... ");
   // 0. parse in fit constant files that should have the same dimension as the final energy files
   // 0a. find dimension of matrices with constants
@@ -406,5 +406,5 @@
   input.open(line.c_str());
   if (input == NULL) {
-    Log() << Verbose(1) << endl << "Unable to open " << line << ", is the directory correct?" << endl;
+    DoLog(1) && (Log() << Verbose(1) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
     return false;
   }
@@ -423,5 +423,5 @@
     b++;
   }
-  Log() << Verbose(0) << "I recognized " << a << " columns and " << b << " rows, ";
+  DoLog(0) && (Log() << Verbose(0) << "I recognized " << a << " columns and " << b << " rows, ");
   input.close();
 
@@ -444,5 +444,5 @@
     input.open(line.c_str());
     if (input == NULL) {
-      eLog() << Verbose(0) << endl << "Unable to open " << line << ", is the directory correct?" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
       performCriticalExit();
       return false;
@@ -466,12 +466,12 @@
   }
   for (int k = 0; k < 3; k++) {
-    Log() << Verbose(0) << "Constants " << k << ":" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Constants " << k << ":" << endl);
     for (int j = 0; j < b; j++) {
       for (int i = 0; i < a; i++) {
-        Log() << Verbose(0) << FitConstant[k][i][j] << "\t";
+        DoLog(0) && (Log() << Verbose(0) << FitConstant[k][i][j] << "\t");
       }
-      Log() << Verbose(0) << endl;
-    }
-    Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << endl);
+    }
+    DoLog(0) && (Log() << Verbose(0) << endl);
   }
 
@@ -502,5 +502,5 @@
           if ((Runner->type->Z == 1) && (Runner->nr > Walker->nr) && (Binder->GetOtherAtom(Runner) != Binder->GetOtherAtom(Walker))) { // (hydrogens have only one bonding partner!)
             // 4. evaluate the morse potential for each matrix component and add up
-            distance = Runner->x.Distance(&Walker->x);
+            distance = Runner->x.distance(Walker->x);
             //Log() << Verbose(0) << "Fragment " << (*ListRunner)->name << ": " << *Runner << "<= " << distance << "=>" << *Walker << ":" << endl;
             for (int k = 0; k < a; k++) {
@@ -561,5 +561,5 @@
   }
   Free(&FitConstant);
-  Log() << Verbose(0) << "done." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done." << endl);
   return true;
 };
@@ -578,8 +578,8 @@
   stringstream line;
   atom *Walker = NULL;
-  element *runner = NULL;
+  periodentafel *periode=World::getInstance().getPeriode();
 
   // open file for the force factors
-  Log() << Verbose(1) << "Saving  force factors ... ";
+  DoLog(1) && (Log() << Verbose(1) << "Saving  force factors ... ");
   line << path << "/" << FRAGMENTPREFIX << FORCESFILE;
   ForcesFile.open(line.str().c_str(), ios::out);
@@ -588,12 +588,11 @@
     //output << prefix << "Forces" << endl;
     for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
-      runner = (*ListRunner)->elemente->start;
-      while (runner->next != (*ListRunner)->elemente->end) { // go through every element
-        runner = runner->next;
-        if ((*ListRunner)->ElementsInMolecule[runner->Z]) { // if this element got atoms
+      periodentafel::const_iterator elemIter;
+      for(elemIter=periode->begin();elemIter!=periode->end();++elemIter){
+          if ((*ListRunner)->ElementsInMolecule[(*elemIter).first]) { // if this element got atoms
           Walker = (*ListRunner)->start;
           while (Walker->next != (*ListRunner)->end) { // go through every atom of this element
             Walker = Walker->next;
-            if (Walker->type->Z == runner->Z) {
+            if (Walker->type->getNumber() == (*elemIter).first) {
               if ((Walker->GetTrueFather() != NULL) && (Walker->GetTrueFather() != Walker)) {// if there is a rea
                 //Log() << Verbose(0) << "Walker is " << *Walker << " with true father " << *( Walker->GetTrueFather()) << ", it
@@ -609,8 +608,8 @@
     }
     ForcesFile.close();
-    Log() << Verbose(1) << "done." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
   } else {
     status = false;
-    Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl);
   }
   ForcesFile.close();
@@ -640,5 +639,10 @@
   int FragmentCounter = 0;
   ofstream output;
-
+  double cell_size_backup[6];
+  double * const cell_size = World::getInstance().getDomain();
+
+  // backup cell_size
+  for (int i=0;i<6;i++)
+    cell_size_backup[i] = cell_size[i];
   // store the fragments as config and as xyz
   for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
@@ -648,5 +652,5 @@
       strcpy(PathBackup, path);
     else {
-      eLog() << Verbose(0) << "OutputConfigForListOfFragments: NULL default path obtained from config!" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "OutputConfigForListOfFragments: NULL default path obtained from config!" << endl);
       performCriticalExit();
     }
@@ -659,9 +663,9 @@
     sprintf(FragmentName, "%s/%s%s.conf.xyz", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
     outputFragment.open(FragmentName, ios::out);
-    Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as XYZ ...";
+    DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as XYZ ...");
     if ((intermediateResult = (*ListRunner)->OutputXYZ(&outputFragment)))
-      Log() << Verbose(0) << " done." << endl;
+      DoLog(0) && (Log() << Verbose(0) << " done." << endl);
     else
-      Log() << Verbose(0) << " failed." << endl;
+      DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
     result = result && intermediateResult;
     outputFragment.close();
@@ -669,11 +673,11 @@
 
     // list atoms in fragment for debugging
-    Log() << Verbose(2) << "Contained atoms: ";
+    DoLog(2) && (Log() << Verbose(2) << "Contained atoms: ");
     Walker = (*ListRunner)->start;
     while (Walker->next != (*ListRunner)->end) {
       Walker = Walker->next;
-      Log() << Verbose(0) << Walker->Name << " ";
-    }
-    Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << Walker->Name << " ");
+    }
+    DoLog(0) && (Log() << Verbose(0) << endl);
 
     // center on edge
@@ -683,6 +687,6 @@
     for (int k = 0; k < NDIM; k++) {
       j += k + 1;
-      BoxDimension.x[k] = 2.5 * (configuration->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
-      (*ListRunner)->cell_size[j] += BoxDimension.x[k] * 2.;
+      BoxDimension[k] = 2.5 * (configuration->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
+      cell_size[j] = BoxDimension[k] * 2.;
     }
     (*ListRunner)->Translate(&BoxDimension);
@@ -699,9 +703,9 @@
     // and save as config
     sprintf(FragmentName, "%s/%s%s.conf", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
-    Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as config ...";
+    DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as config ...");
     if ((intermediateResult = configuration->Save(FragmentName, (*ListRunner)->elemente, (*ListRunner))))
-      Log() << Verbose(0) << " done." << endl;
+      DoLog(0) && (Log() << Verbose(0) << " done." << endl);
     else
-      Log() << Verbose(0) << " failed." << endl;
+      DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
     result = result && intermediateResult;
 
@@ -711,9 +715,9 @@
     // and save as mpqc input file
     sprintf(FragmentName, "%s/%s%s.conf", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
-    Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as mpqc input ...";
+    DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as mpqc input ...");
     if ((intermediateResult = configuration->SaveMPQC(FragmentName, (*ListRunner))))
-      Log() << Verbose(2) << " done." << endl;
+      DoLog(2) && (Log() << Verbose(2) << " done." << endl);
     else
-      Log() << Verbose(0) << " failed." << endl;
+      DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
 
     result = result && intermediateResult;
@@ -722,8 +726,12 @@
     Free(&FragmentNumber);
   }
-  Log() << Verbose(0) << " done." << endl;
+  DoLog(0) && (Log() << Verbose(0) << " done." << endl);
 
   // printing final number
-  Log() << Verbose(2) << "Final number of fragments: " << FragmentCounter << "." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "Final number of fragments: " << FragmentCounter << "." << endl);
+
+  // restore cell_size
+  for (int i=0;i<6;i++)
+    cell_size[i] = cell_size_backup[i];
 
   return result;
@@ -748,5 +756,5 @@
 void MoleculeListClass::DissectMoleculeIntoConnectedSubgraphs(const periodentafel * const periode, config * const configuration)
 {
-  molecule *mol = new molecule(periode);
+  molecule *mol = World::getInstance().createMolecule();
   atom *Walker = NULL;
   atom *Advancer = NULL;
@@ -760,5 +768,5 @@
       Walker = Advancer;
       Advancer = Advancer->next;
-      Log() << Verbose(3) << "Re-linking " << *Walker << "..." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "Re-linking " << *Walker << "..." << endl);
       unlink(Walker);
       Walker->father = Walker;
@@ -773,10 +781,14 @@
     }
     // remove the molecule
-    delete(*MolRunner);
+    World::getInstance().destroyMolecule(*MolRunner);
     ListOfMolecules.erase(MolRunner);
   }
 
   // 1. dissect the molecule into connected subgraphs
-  configuration->BG->ConstructBondGraph(mol);
+  if (!configuration->BG->ConstructBondGraph(mol)) {
+    World::getInstance().destroyMolecule(mol);
+    DoeLog(1) && (eLog()<< Verbose(1) << "There are no bonds." << endl);
+    return;
+  }
 
   // 2. scan for connected subgraphs
@@ -785,4 +797,9 @@
   Subgraphs = mol->DepthFirstSearchAnalysis(BackEdgeStack);
   delete(BackEdgeStack);
+  if ((Subgraphs == NULL) || (Subgraphs->next == NULL)) {
+    World::getInstance().destroyMolecule(mol);
+    DoeLog(1) && (eLog()<< Verbose(1) << "There are no atoms." << endl);
+    return;
+  }
 
   // 3. dissect (the following construct is needed to have the atoms not in the order of the DFS, but in
@@ -795,5 +812,5 @@
   molecule **molecules = Malloc<molecule *>(MolCount, "config::Load() - **molecules");
   for (int i=0;i<MolCount;i++) {
-    molecules[i] = (molecule*) new molecule(mol->elemente);
+    molecules[i] = World::getInstance().createMolecule();
     molecules[i]->ActiveFlag = true;
     strncpy(molecules[i]->name, mol->name, MAXSTRINGSIZE);
@@ -802,5 +819,5 @@
       strncat(molecules[i]->name, number, MAXSTRINGSIZE - strlen(mol->name) - 1);
     }
-    cout << "MolName is " << molecules[i]->name << endl;
+    DoLog(1) && (Log() << Verbose(1) << "MolName is " << molecules[i]->name << endl);
     insert(molecules[i]);
   }
@@ -826,14 +843,14 @@
     Walker = mol->start->next;
     if ((Walker->nr <0) || (Walker->nr >= mol->AtomCount)) {
-      eLog() << Verbose(0) << "Index of atom " << *Walker << " is invalid!" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Index of atom " << *Walker << " is invalid!" << endl);
       performCriticalExit();
     }
     FragmentCounter = MolMap[Walker->nr];
     if (FragmentCounter != 0) {
-      Log() << Verbose(3) << "Re-linking " << *Walker << "..." << endl;
+      DoLog(3) && (Log() << Verbose(3) << "Re-linking " << *Walker << "..." << endl);
       unlink(Walker);
       molecules[FragmentCounter-1]->AddAtom(Walker);    // counting starts at 1
     } else {
-      eLog() << Verbose(0) << "Atom " << *Walker << " not associated to molecule!" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Atom " << *Walker << " not associated to molecule!" << endl);
       performCriticalExit();
     }
@@ -856,5 +873,5 @@
   Free(&MolMap);
   Free(&molecules);
-  Log() << Verbose(1) << "I scanned " << FragmentCounter << " molecules." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "I scanned " << FragmentCounter << " molecules." << endl);
 };
 
@@ -893,5 +910,5 @@
   OBSERVE;
   molecule *mol = NULL;
-  mol = new molecule(periode);
+  mol = World::getInstance().createMolecule();
   insert(mol);
 };
@@ -902,5 +919,5 @@
   char filename[MAXSTRINGSIZE];
   Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
-  mol = new molecule(periode);
+  mol = World::getInstance().createMolecule();
   do {
     Log() << Verbose(0) << "Enter file name: ";
@@ -910,10 +927,10 @@
   // center at set box dimensions
   mol->CenterEdge(&center);
-  mol->cell_size[0] = center.x[0];
-  mol->cell_size[1] = 0;
-  mol->cell_size[2] = center.x[1];
-  mol->cell_size[3] = 0;
-  mol->cell_size[4] = 0;
-  mol->cell_size[5] = center.x[2];
+  World::getInstance().getDomain()[0] = center[0];
+  World::getInstance().getDomain()[1] = 0;
+  World::getInstance().getDomain()[2] = center[1];
+  World::getInstance().getDomain()[3] = 0;
+  World::getInstance().getDomain()[4] = 0;
+  World::getInstance().getDomain()[5] = center[2];
   insert(mol);
 }
@@ -960,5 +977,5 @@
       mol = *ListRunner;
       ListOfMolecules.erase(ListRunner);
-      delete(mol);
+      World::getInstance().destroyMolecule(mol);
       break;
     }
@@ -1007,5 +1024,5 @@
   // remove the leaf itself
   if (Leaf != NULL) {
-    delete (Leaf);
+    World::getInstance().destroyMolecule(Leaf);
     Leaf = NULL;
   }
@@ -1053,13 +1070,13 @@
   int AtomNo;
 
-  Log() << Verbose(1) << "Begin of FillBondStructureFromReference." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Begin of FillBondStructureFromReference." << endl);
   // fill ListOfLocalAtoms if NULL was given
   if (!FillListOfLocalAtoms(ListOfLocalAtoms, FragmentCounter, reference->AtomCount, FreeList)) {
-    Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl);
     return false;
   }
 
   if (status) {
-    Log() << Verbose(1) << "Creating adjacency list for subgraph " << Leaf << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Creating adjacency list for subgraph " << Leaf << "." << endl);
     // remove every bond from the list
     bond *Binder = NULL;
@@ -1082,5 +1099,5 @@
             Leaf->AddBond(Walker, OtherWalker, (*Runner)->BondDegree);
         } else {
-          Log() << Verbose(1) << "OtherWalker = ListOfLocalAtoms[" << FragmentCounter << "][" << (*Runner)->GetOtherAtom(Walker->GetTrueFather())->nr << "] is NULL!" << endl;
+          DoLog(1) && (Log() << Verbose(1) << "OtherWalker = ListOfLocalAtoms[" << FragmentCounter << "][" << (*Runner)->GetOtherAtom(Walker->GetTrueFather())->nr << "] is NULL!" << endl);
           status = false;
         }
@@ -1095,5 +1112,5 @@
       Free(&ListOfLocalAtoms);
   }
-  Log() << Verbose(1) << "End of FillBondStructureFromReference." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "End of FillBondStructureFromReference." << endl);
   return status;
 };
@@ -1128,5 +1145,5 @@
         next->FillRootStackForSubgraphs(RootStack, AtomMask, ++FragmentCounter);
     } else {
-      Log() << Verbose(1) << "Rootstack[" << FragmentCounter << "] is NULL." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Rootstack[" << FragmentCounter << "] is NULL." << endl);
       return false;
     }
@@ -1134,5 +1151,5 @@
     return true;
   } else {
-    Log() << Verbose(1) << "Rootstack is NULL." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Rootstack is NULL." << endl);
     return false;
   }
@@ -1184,8 +1201,8 @@
   int KeySetCounter = 0;
 
-  Log() << Verbose(1) << "Begin of AssignKeySetsToFragment." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Begin of AssignKeySetsToFragment." << endl);
   // fill ListOfLocalAtoms if NULL was given
   if (!FillListOfLocalAtoms(ListOfLocalAtoms, FragmentCounter, reference->AtomCount, FreeList)) {
-    Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl);
     return false;
   }
@@ -1215,8 +1232,8 @@
     delete (TempSet);
     if (KeySetCounter == 0) {// if there are no keysets, delete the list
-      Log() << Verbose(1) << "KeySetCounter is zero, deleting FragmentList." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "KeySetCounter is zero, deleting FragmentList." << endl);
       delete (FragmentList[FragmentCounter]);
     } else
-      Log() << Verbose(1) << KeySetCounter << " keysets were assigned to subgraph " << FragmentCounter << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << KeySetCounter << " keysets were assigned to subgraph " << FragmentCounter << "." << endl);
     FragmentCounter++;
     if (next != NULL)
@@ -1224,5 +1241,5 @@
     FragmentCounter--;
   } else
-    Log() << Verbose(1) << "KeySetList is NULL or empty." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "KeySetList is NULL or empty." << endl);
 
   if ((FreeList) && (ListOfLocalAtoms != NULL)) {
@@ -1232,5 +1249,5 @@
       Free(&ListOfLocalAtoms);
   }
-  Log() << Verbose(1) << "End of AssignKeySetsToFragment." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "End of AssignKeySetsToFragment." << endl);
   return status;
 };
@@ -1245,5 +1262,5 @@
 void MoleculeLeafClass::TranslateIndicesToGlobalIDs(Graph **FragmentList, int &FragmentCounter, int &TotalNumberOfKeySets, Graph &TotalGraph)
 {
-  Log() << Verbose(1) << "Begin of TranslateIndicesToGlobalIDs." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Begin of TranslateIndicesToGlobalIDs." << endl);
   KeySet *TempSet = new KeySet;
   if (FragmentList[FragmentCounter] != NULL) {
@@ -1256,10 +1273,10 @@
     delete (TempSet);
   } else {
-    Log() << Verbose(1) << "FragmentList is NULL." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "FragmentList is NULL." << endl);
   }
   if (next != NULL)
     next->TranslateIndicesToGlobalIDs(FragmentList, ++FragmentCounter, TotalNumberOfKeySets, TotalGraph);
   FragmentCounter--;
-  Log() << Verbose(1) << "End of TranslateIndicesToGlobalIDs." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "End of TranslateIndicesToGlobalIDs." << endl);
 };
 
Index: src/parser.cpp
===================================================================
--- src/parser.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/parser.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -32,5 +32,5 @@
   if (input == NULL) {
     if (!test)
-      Log() << Verbose(0) << endl << "Unable to open " << filename << ", is the directory correct?" << endl;
+      DoLog(0) && (Log() << Verbose(0) << endl << "Unable to open " << filename << ", is the directory correct?" << endl);
     return false;
   }
@@ -109,7 +109,7 @@
 bool MatrixContainer::InitialiseIndices(class MatrixContainer *Matrix) 
 {
-  Log() << Verbose(0) << "Initialising indices";
+  DoLog(0) && (Log() << Verbose(0) << "Initialising indices");
   if (Matrix == NULL) {
-    Log() << Verbose(0) << " with trivial mapping." << endl;
+    DoLog(0) && (Log() << Verbose(0) << " with trivial mapping." << endl);
     Indices = Malloc<int*>(MatrixCounter + 1, "MatrixContainer::InitialiseIndices: **Indices");
     for(int i=MatrixCounter+1;i--;) {
@@ -119,5 +119,5 @@
     }
   } else {
-    Log() << Verbose(0) << " from other MatrixContainer." << endl;
+    DoLog(0) && (Log() << Verbose(0) << " from other MatrixContainer." << endl);
     if (MatrixCounter != Matrix->MatrixCounter)
       return false;
@@ -160,5 +160,5 @@
   //Log() << Verbose(1) << "Opening " << name << " ... "  << input << endl;
   if (input == NULL) {
-    eLog() << Verbose(1) << endl << "Unable to open " << name << ", is the directory correct?" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << endl << "Unable to open " << name << ", is the directory correct?" << endl);
     //performCriticalExit();
     return false;
@@ -183,5 +183,5 @@
   //Log() << Verbose(1) << "ColumnCounter[" << MatrixNr << "]: " << ColumnCounter[MatrixNr] << "." << endl;
   if (ColumnCounter[MatrixNr] == 0) {
-    eLog() << Verbose(0) << "ColumnCounter[" << MatrixNr << "]: " << ColumnCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "ColumnCounter[" << MatrixNr << "]: " << ColumnCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl);
     performCriticalExit();
   }
@@ -199,5 +199,5 @@
   //Log() << Verbose(1) << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << "." << endl;
   if (RowCounter[MatrixNr] == 0) {
-    eLog() << Verbose(0) << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl);
     performCriticalExit();
   }
@@ -232,5 +232,5 @@
     }
   } else {
-    eLog() << Verbose(1) << "Matrix nr. " << MatrixNr << " has column and row count of (" << ColumnCounter[MatrixNr] << "," << RowCounter[MatrixNr] << "), could not allocate nor parse!" << endl; 
+    DoeLog(1) && (eLog()<< Verbose(1) << "Matrix nr. " << MatrixNr << " has column and row count of (" << ColumnCounter[MatrixNr] << "," << RowCounter[MatrixNr] << "), could not allocate nor parse!" << endl); 
   }
   input.close();
@@ -269,5 +269,5 @@
   input.open(file.str().c_str(), ios::in);
   if (input == NULL) {
-    Log() << Verbose(0) << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl);
     return false;
   }
@@ -278,7 +278,7 @@
   }
   input.close();
-  Log() << Verbose(0) << "Determined " << MatrixCounter << " fragments." << endl;
-
-  Log() << Verbose(0) << "Parsing through each fragment and retrieving " << prefix << suffix << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Determined " << MatrixCounter << " fragments." << endl);
+
+  DoLog(0) && (Log() << Verbose(0) << "Parsing through each fragment and retrieving " << prefix << suffix << "." << endl);
   Header = ReAlloc<char*>(Header, MatrixCounter + 1, "MatrixContainer::ParseFragmentMatrix: **Header"); // one more each for the total molecule
   Matrix = ReAlloc<double**>(Matrix, MatrixCounter + 1, "MatrixContainer::ParseFragmentMatrix: ***Matrix"); // one more each for the total molecule
@@ -433,5 +433,5 @@
               //Log() << Verbose(0) << "Corresponding index in CurrentFragment is " << m << "." << endl;
               if (m > RowCounter[ KeySets.OrderSet[Order][CurrentFragment] ]) {
-                eLog() << Verbose(0) << "In fragment No. " << KeySets.OrderSet[Order][CurrentFragment]   << " current force index " << m << " is greater than " << RowCounter[ KeySets.OrderSet[Order][CurrentFragment] ] << "!" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "In fragment No. " << KeySets.OrderSet[Order][CurrentFragment]   << " current force index " << m << " is greater than " << RowCounter[ KeySets.OrderSet[Order][CurrentFragment] ] << "!" << endl);
                 performCriticalExit();
                 return false;
@@ -469,5 +469,5 @@
   char *FragmentNumber = NULL;
 
-  Log() << Verbose(0) << "Writing fragment files." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Writing fragment files." << endl);
   for(int i=0;i<MatrixCounter;i++) {
     stringstream line;
@@ -477,5 +477,5 @@
     output.open(line.str().c_str(), ios::out);
     if (output == NULL) {
-      eLog() << Verbose(0) << "Unable to open output energy file " << line.str() << "!" << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Unable to open output energy file " << line.str() << "!" << endl);
       performCriticalExit();
       return false;
@@ -503,9 +503,9 @@
   stringstream line;
 
-  Log() << Verbose(0) << "Writing matrix values of " << suffix << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Writing matrix values of " << suffix << "." << endl);
   line << name << prefix << suffix;
   output.open(line.str().c_str(), ios::out);
   if (output == NULL) {
-    eLog() << Verbose(0) << "Unable to open output matrix file " << line.str() << "!" << endl;
+    DoeLog(0) && (eLog()<< Verbose(0) << "Unable to open output matrix file " << line.str() << "!" << endl);
     performCriticalExit();
     return false;
@@ -529,5 +529,5 @@
 bool EnergyMatrix::ParseIndices()
 {
-  Log() << Verbose(0) << "Parsing energy indices." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Parsing energy indices." << endl);
   Indices = Malloc<int*>(MatrixCounter + 1, "EnergyMatrix::ParseIndices: **Indices");
   for(int i=MatrixCounter+1;i--;) {
@@ -588,5 +588,5 @@
     }
     // allocate last plus one matrix
-    Log() << Verbose(0) << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl);
     Matrix[MatrixCounter] = Malloc<double*>(RowCounter[MatrixCounter] + 1, "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
     for(int j=0;j<=RowCounter[MatrixCounter];j++)
@@ -615,5 +615,5 @@
   stringstream line;
 
-  Log() << Verbose(0) << "Parsing force indices for " << MatrixCounter << " matrices." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Parsing force indices for " << MatrixCounter << " matrices." << endl);
   Indices = Malloc<int*>(MatrixCounter + 1, "ForceMatrix::ParseIndices: **Indices");
   line << name << FRAGMENTPREFIX << FORCESFILE;
@@ -621,5 +621,5 @@
   //Log() << Verbose(0) << "Opening " << line.str() << " ... "  << input << endl;
   if (input == NULL) {
-    Log() << Verbose(0) << endl << "Unable to open " << line.str() << ", is the directory correct?" << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl << "Unable to open " << line.str() << ", is the directory correct?" << endl);
     return false;
   }
@@ -664,5 +664,5 @@
       int j = Indices[ FragmentNr ][l];
       if (j > RowCounter[MatrixCounter]) {
-        eLog() << Verbose(0) << "Current force index " << j << " is greater than " << RowCounter[MatrixCounter] << "!" << endl;
+        DoeLog(0) && (eLog()<< Verbose(0) << "Current force index " << j << " is greater than " << RowCounter[MatrixCounter] << "!" << endl);
         performCriticalExit();
         return false;
@@ -700,5 +700,5 @@
     input.open(file.str().c_str(), ios::in);
     if (input == NULL) {
-      Log() << Verbose(0) << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
+      DoLog(0) && (Log() << Verbose(0) << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl);
       return false;
     }
@@ -724,5 +724,5 @@
   
     // allocate last plus one matrix
-    Log() << Verbose(0) << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl);
     Matrix[MatrixCounter] = Malloc<double*>(RowCounter[MatrixCounter] + 1, "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
     for(int j=0;j<=RowCounter[MatrixCounter];j++)
@@ -753,5 +753,5 @@
   stringstream line;
   
-  Log() << Verbose(0) << "Parsing hessian indices for " << MatrixCounter << " matrices." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Parsing hessian indices for " << MatrixCounter << " matrices." << endl);
   Indices = Malloc<int*>(MatrixCounter + 1, "HessianMatrix::ParseIndices: **Indices");
   line << name << FRAGMENTPREFIX << FORCESFILE;
@@ -759,5 +759,5 @@
   //Log() << Verbose(0) << "Opening " << line.str() << " ... "  << input << endl;
   if (input == NULL) {
-    Log() << Verbose(0) << endl << "Unable to open " << line.str() << ", is the directory correct?" << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl << "Unable to open " << line.str() << ", is the directory correct?" << endl);
     return false;
   }
@@ -802,5 +802,5 @@
       int j = Indices[ FragmentNr ][l];
       if (j > RowCounter[MatrixCounter]) {
-        eLog() << Verbose(0) << "Current hessian index " << j << " is greater than " << RowCounter[MatrixCounter] << ", where i=" << i << ", Order=" << Order << ", l=" << l << " and FragmentNr=" << FragmentNr << "!" << endl;
+        DoeLog(0) && (eLog()<< Verbose(0) << "Current hessian index " << j << " is greater than " << RowCounter[MatrixCounter] << ", where i=" << i << ", Order=" << Order << ", l=" << l << " and FragmentNr=" << FragmentNr << "!" << endl);
         performCriticalExit();
         return false;
@@ -810,5 +810,5 @@
           int k = Indices[ FragmentNr ][m];
           if (k > ColumnCounter[MatrixCounter]) {
-            eLog() << Verbose(0) << "Current hessian index " << k << " is greater than " << ColumnCounter[MatrixCounter] << ", where m=" << m << ", j=" << j << ", i=" << i << ", Order=" << Order << ", l=" << l << " and FragmentNr=" << FragmentNr << "!" << endl;
+            DoeLog(0) && (eLog()<< Verbose(0) << "Current hessian index " << k << " is greater than " << ColumnCounter[MatrixCounter] << ", where m=" << m << ", j=" << j << ", i=" << i << ", Order=" << Order << ", l=" << l << " and FragmentNr=" << FragmentNr << "!" << endl);
             performCriticalExit();
             return false;
@@ -863,5 +863,5 @@
               //Log() << Verbose(0) << "Corresponding row index for " << k << " in CurrentFragment is " << m << "." << endl;
               if (m > RowCounter[ KeySets.OrderSet[Order][CurrentFragment] ]) {
-                eLog() << Verbose(0) << "In fragment No. " << KeySets.OrderSet[Order][CurrentFragment]   << " current row index " << m << " is greater than " << RowCounter[ KeySets.OrderSet[Order][CurrentFragment] ] << "!" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "In fragment No. " << KeySets.OrderSet[Order][CurrentFragment]   << " current row index " << m << " is greater than " << RowCounter[ KeySets.OrderSet[Order][CurrentFragment] ] << "!" << endl);
                 performCriticalExit();
                 return false;
@@ -881,5 +881,5 @@
                   //Log() << Verbose(0) << "Corresponding column index for " << l << " in CurrentFragment is " << n << "." << endl;
                   if (n > ColumnCounter[ KeySets.OrderSet[Order][CurrentFragment] ]) {
-                    eLog() << Verbose(0) << "In fragment No. " << KeySets.OrderSet[Order][CurrentFragment]   << " current column index " << n << " is greater than " << ColumnCounter[ KeySets.OrderSet[Order][CurrentFragment] ] << "!" << endl;
+                    DoeLog(0) && (eLog()<< Verbose(0) << "In fragment No. " << KeySets.OrderSet[Order][CurrentFragment]   << " current column index " << n << " is greater than " << ColumnCounter[ KeySets.OrderSet[Order][CurrentFragment] ] << "!" << endl);
                     performCriticalExit();
                     return false;
@@ -930,5 +930,5 @@
     input.open(file.str().c_str(), ios::in);
     if (input == NULL) {
-      Log() << Verbose(0) << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
+      DoLog(0) && (Log() << Verbose(0) << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl);
       return false;
     }
@@ -952,5 +952,5 @@
   
     // allocate last plus one matrix
-    Log() << Verbose(0) << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl);
     Matrix[MatrixCounter] = Malloc<double*>(RowCounter[MatrixCounter] + 1, "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
     for(int j=0;j<=RowCounter[MatrixCounter];j++)
@@ -1007,5 +1007,5 @@
 
   FragmentCounter = FCounter;
-  Log() << Verbose(0) << "Parsing key sets." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Parsing key sets." << endl);
   KeySets = Malloc<int*>(FragmentCounter, "KeySetsContainer::ParseKeySets: **KeySets");
   for(int i=FragmentCounter;i--;)
@@ -1014,5 +1014,5 @@
   input.open(file.str().c_str(), ios::in);
   if (input == NULL) {
-    Log() << Verbose(0) << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl);
     return false;
   }
@@ -1048,5 +1048,5 @@
   int Counter;
 
-  Log() << Verbose(0) << "Creating Fragment terms." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Creating Fragment terms." << endl);
   // scan through all to determine maximum order
   Order=0;
@@ -1059,5 +1059,5 @@
       Order = Counter;
   }
-  Log() << Verbose(0) << "Found Order is " << Order << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Found Order is " << Order << "." << endl);
 
   // scan through all to determine fragments per order
@@ -1073,5 +1073,5 @@
   }
   for(int i=0;i<Order;i++)
-    Log() << Verbose(0) << "Found No. of Fragments of Order " << i+1 << " is " << FragmentsPerOrder[i] << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Found No. of Fragments of Order " << i+1 << " is " << FragmentsPerOrder[i] << "." << endl);
 
   // scan through all to gather indices to each order set
@@ -1089,12 +1089,12 @@
     FragmentsPerOrder[Counter-1]++;
   }
-  Log() << Verbose(0) << "Printing OrderSet." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Printing OrderSet." << endl);
   for(int i=0;i<Order;i++) {
     for (int j=0;j<FragmentsPerOrder[i];j++) {
-      Log() << Verbose(0) << " " << OrderSet[i][j];
-    }
-    Log() << Verbose(0) << endl;
-  }
-  Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << " " << OrderSet[i][j]);
+    }
+    DoLog(0) && (Log() << Verbose(0) << endl);
+  }
+  DoLog(0) && (Log() << Verbose(0) << endl);
 
 
Index: src/periodentafel.cpp
===================================================================
--- src/periodentafel.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/periodentafel.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -10,4 +10,5 @@
 #include <fstream>
 #include <cstring>
+#include <cassert>
 
 #include "element.hpp"
@@ -18,4 +19,6 @@
 #include "verbose.hpp"
 
+using namespace std;
+
 /************************************* Functions for class periodentafel ***************************/
 
@@ -23,11 +26,6 @@
  * Initialises start and end of list and resets periodentafel::checkliste to false.
  */
-periodentafel::periodentafel() : start(new element), end(new element)
-{
-  start->previous = NULL;
-  start->next = end;
-  end->previous = start;
-  end->next = NULL;
-};
+periodentafel::periodentafel()
+{};
 
 /** destructor for class periodentafel
@@ -37,6 +35,4 @@
 {
   CleanupPeriodtable();
-  delete(end);
-  delete(start);
 };
 
@@ -45,10 +41,13 @@
  * \return true - succeeded, false - does not occur
  */
-bool periodentafel::AddElement(element * const pointer)
-{
+periodentafel::iterator periodentafel::AddElement(element * const pointer)
+{
+  atomicNumber_t Z = pointer->getNumber();
+  assert(!elements.count(Z));
   pointer->sort = &pointer->Z;
-  if (pointer->Z < 1 && pointer->Z >= MAX_ELEMENTS)
-    Log() << Verbose(0) << "Invalid Z number!\n";
-  return add(pointer, end);
+  if (pointer->getNumber() < 1 && pointer->getNumber() >= MAX_ELEMENTS)
+    DoeLog(0) && (eLog() << Verbose(0) << "Invalid Z number!\n");
+  pair<iterator,bool> res = elements.insert(pair<atomicNumber_t,element*>(Z,pointer));
+  return res.first;
 };
 
@@ -57,7 +56,8 @@
  * \return true - succeeded, false - element not found
  */
-bool periodentafel::RemoveElement(element * const pointer)
-{
-  return remove(pointer, start, end);
+void periodentafel::RemoveElement(element * const pointer)
+{
+  atomicNumber_t Z = pointer->getNumber();
+  elements.erase(Z);
 };
 
@@ -65,7 +65,10 @@
  * \return true - succeeded, false - does not occur
  */
-bool periodentafel::CleanupPeriodtable()
-{
-  return cleanup(start,end);
+void periodentafel::CleanupPeriodtable()
+{
+  for(iterator iter=elements.begin();iter!=elements.end();++iter){
+    delete(*iter).second;
+  }
+  elements.clear();
 };
 
@@ -75,8 +78,8 @@
  * \return pointer to element or NULL if not found
  */
-element * const periodentafel::FindElement(const int Z) const
-{
-  element *walker = find(&Z, start,end);
-  return(walker);
+const element * periodentafel::FindElement(atomicNumber_t Z) const
+{
+  const_iterator res = elements.find(Z);
+  return res!=elements.end()?((*res).second):0;
 };
 
@@ -86,23 +89,24 @@
  * \return pointer to element
  */
-element * const periodentafel::FindElement(const char * const shorthand) const
-{
-  element *walker =  periodentafel::start;
-  while (walker->next != periodentafel::end) {
-    walker = walker->next;
-    if (strncmp(walker->symbol, shorthand, 3) == 0)
-      return(walker);
-  }
-  return (NULL);
+const element * periodentafel::FindElement(const char * const shorthand) const
+{
+  element *res = 0;
+  for(const_iterator iter=elements.begin();iter!=elements.end();++iter) {
+    if((*iter).second->getSymbol() == shorthand){
+      res = (*iter).second;
+      break;
+    }
+  }
+  return res;
 };
 
 /** Asks for element number and returns pointer to element
  */
-element * const periodentafel::AskElement() const
-{
-  element *walker = NULL;
+const element * periodentafel::AskElement() const
+{
+  const element *walker = NULL;
   int Z;
   do {
-    Log() << Verbose(0) << "Atomic number Z: ";
+    DoLog(0) && (Log() << Verbose(0) << "Atomic number Z: ");
     cin >> Z;
     walker = this->FindElement(Z);  // give type
@@ -114,37 +118,56 @@
  * \return pointer to either present or newly created element
  */
-element * const periodentafel::EnterElement()
-{
-  element *walker = NULL;
-  int Z = -1;
-  Log() << Verbose(0) << "Atomic number: " << Z << endl;
+const element * periodentafel::EnterElement()
+{
+  const element *res = NULL;
+  atomicNumber_t Z = 0;
+  DoLog(0) && (Log() << Verbose(0) << "Atomic number: " << Z << endl);
   cin >> Z;
-  walker = FindElement(Z);
-  if (walker == NULL) {
-    Log() << Verbose(0) << "Element not found in database, please enter." << endl;
-    walker = new element;
-    walker->Z = Z;
-    Log() << Verbose(0) << "Mass: " << endl;
-    cin >> walker->mass;
-    Log() << Verbose(0) << "Name [max 64 chars]: " << endl;
-    cin >> walker->name;
-    Log() << Verbose(0) << "Short form [max 3 chars]: " << endl;
-    cin >> walker->symbol;
-    periodentafel::AddElement(walker);
-  }
-  return(walker);
-};
+  res = FindElement(Z);
+  if (!res) {
+    // TODO: make this using the constructor
+    element *tmp;
+    DoLog(0) && (Log() << Verbose(0) << "Element not found in database, please enter." << endl);
+    tmp = new element;
+    tmp->Z = Z;
+    DoLog(0) && (Log() << Verbose(0) << "Mass: " << endl);
+    cin >> tmp->mass;
+    DoLog(0) && (Log() << Verbose(0) << "Name [max 64 chars]: " << endl);
+    cin >> tmp->name;
+    DoLog(0) && (Log() << Verbose(0) << "Short form [max 3 chars]: " << endl);
+    cin >> tmp->symbol;
+    AddElement(tmp);
+    res = tmp;
+  }
+  return res;
+};
+
+
+/******************** Access to iterators ****************************/
+periodentafel::const_iterator periodentafel::begin(){
+  return elements.begin();
+}
+
+periodentafel::const_iterator periodentafel::end(){
+  return elements.end();
+}
+
+periodentafel::reverse_iterator periodentafel::rbegin(){
+  return reverse_iterator(elements.end());
+}
+
+periodentafel::reverse_iterator periodentafel::rend(){
+  return reverse_iterator(elements.begin());
+}
 
 /** Prints period table to given stream.
  * \param output stream
  */
-bool periodentafel::Output(ofstream * const output) const
+bool periodentafel::Output(ostream * const output) const
 {
   bool result = true;
-  element *walker = start;
   if (output != NULL) {
-    while (walker->next != end) {
-      walker = walker->next;
-      result = result && walker->Output(output);
+    for(const_iterator iter=elements.begin(); iter !=elements.end();++iter){
+      result = result && (*iter).second->Output(output);
     }
     return result;
@@ -157,7 +180,6 @@
  * \param *checkliste elements table for this molecule
  */
-bool periodentafel::Checkout(ofstream * const output, const int * const checkliste) const
-{
-  element *walker = start;
+bool periodentafel::Checkout(ostream * const output, const int * const checkliste) const
+{
   bool result = true;
   int No = 1;
@@ -166,9 +188,8 @@
     *output << "# Ion type data (PP = PseudoPotential, Z = atomic number)" << endl;
     *output << "#Ion_TypeNr.\tAmount\tZ\tRGauss\tL_Max(PP)L_Loc(PP)IonMass\t# chemical name, symbol" << endl;
-    while (walker->next != end) {
-      walker = walker->next;
-      if ((walker != NULL) && (walker->Z > 0) && (walker->Z < MAX_ELEMENTS) && (checkliste[walker->Z])) {
-        walker->No = No;
-        result = result && walker->Checkout(output, No++, checkliste[walker->Z]);
+    for(const_iterator iter=elements.begin(); iter!=elements.end();++iter){
+      if (((*iter).first < MAX_ELEMENTS) && (checkliste[(*iter).first])) {
+        (*iter).second->No = No;
+        result = result && (*iter).second->Checkout(output, No++, checkliste[(*iter).first]);
       }
     }
@@ -184,6 +205,6 @@
 {
   ifstream infile;
-  double tmp;
   element *ptr;
+  map<atomicNumber_t,element*> parsedElems;
   bool status = true;
   bool otherstatus = true;
@@ -198,5 +219,5 @@
     infile.getline(header1, MAXSTRINGSIZE);
     infile.getline(header2, MAXSTRINGSIZE); // skip first two header lines
-    Log() << Verbose(0) <<  "Parsed elements:";
+    DoLog(0) && (Log() << Verbose(0) <<  "Parsed elements:");
     while (!infile.eof()) {
       element *neues = new element;
@@ -220,15 +241,15 @@
       //infile >> ws;
       infile >> ws;
-      Log() << Verbose(0) << " " << neues->symbol;
+      DoLog(0) && (Log() << Verbose(0) << " " << neues->symbol);
       //neues->Output((ofstream *)&cout);
       if ((neues->Z > 0) && (neues->Z < MAX_ELEMENTS))
-        periodentafel::AddElement(neues);
+        parsedElems[neues->getNumber()] = neues;
       else {
-        Log() << Verbose(0) << "Could not parse element: ";
+        DoLog(0) && (Log() << Verbose(0) << "Could not parse element: ");
         neues->Output((ofstream *)&cout);
         delete(neues);
       }
     }
-    Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl);
     infile.close();
     infile.clear();
@@ -243,7 +264,8 @@
   if (infile != NULL) {
     while (!infile.eof()) {
-      infile >> tmp;
-      infile >> ws;
-      infile >> FindElement((int)tmp)->Valence;
+      atomicNumber_t Z;
+      infile >> Z;
+      infile >> ws;
+      infile >> parsedElems[Z]->Valence;
       infile >> ws;
       //Log() << Verbose(3) << "Element " << (int)tmp << " has " << FindElement((int)tmp)->Valence << " valence electrons." << endl;
@@ -261,7 +283,8 @@
   if (infile != NULL) {
     while (!infile.eof()) {
-      infile >> tmp;
-      infile >> ws;
-      infile >> FindElement((int)tmp)->NoValenceOrbitals;
+      atomicNumber_t Z;
+      infile >> Z;
+      infile >> ws;
+      infile >> parsedElems[Z]->NoValenceOrbitals;
       infile >> ws;
       //Log() << Verbose(3) << "Element " << (int)tmp << " has " << FindElement((int)tmp)->NoValenceOrbitals << " number of singly occupied valence orbitals." << endl;
@@ -279,6 +302,7 @@
   if (infile != NULL) {
     while (!infile.eof()) {
-      infile >> tmp;
-      ptr = FindElement((int)tmp);
+      atomicNumber_t Z;
+      infile >> Z;
+      ptr = parsedElems[Z];
       infile >> ws;
       infile >> ptr->HBondDistance[0];
@@ -300,6 +324,7 @@
   if (infile != NULL) {
     while (!infile.eof()) {
-      infile >> tmp;
-      ptr = FindElement((int)tmp);
+      atomicNumber_t Z;
+      infile >> Z;
+      ptr = parsedElems[Z];
       infile >> ws;
       infile >> ptr->HBondAngle[0];
@@ -313,6 +338,17 @@
     otherstatus = false;
 
-  if (!otherstatus)
-    eLog() << Verbose(2) << "Something went wrong while parsing the other databases!" << endl;
+  if (otherstatus){
+    map<atomicNumber_t,element*>::iterator iter;
+    for(iter=parsedElems.begin();iter!=parsedElems.end();++iter){
+      AddElement((*iter).second);
+    }
+  }
+  else{
+    DoeLog(2) && (eLog()<< Verbose(2) << "Something went wrong while parsing the other databases!" << endl);
+    map<atomicNumber_t,element*>::iterator iter;
+    for(iter=parsedElems.begin();iter!=parsedElems.end();++iter){
+      AddElement((*iter).second);
+    }
+  }
 
   return status;
@@ -334,8 +370,6 @@
     f << header1 << endl;
     f << header2 << endl;
-    element *walker = periodentafel::start;
-    while (walker->next != periodentafel::end) {
-      walker = walker->next;
-      result = result && walker->Output(&f);
+    for(const_iterator iter=elements.begin();iter!=elements.end();++iter){
+         result = result && (*iter).second->Output(&f);
     }
     f.close();
Index: src/periodentafel.hpp
===================================================================
--- src/periodentafel.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/periodentafel.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -1,6 +1,4 @@
 #ifndef PERIODENTAFEL_HPP_
 #define PERIODENTAFEL_HPP_
-
-using namespace std;
 
 /*********************************************** includes ***********************************/
@@ -12,6 +10,9 @@
 
 #include <iostream>
+#include <map>
+#include <iterator>
 
 #include "defs.hpp"
+#include "types.hpp"
 
 /****************************************** forward declarations *****************************/
@@ -25,7 +26,13 @@
  */
 class periodentafel {
+  /******* Types *********/
+  private:
+    typedef std::map<atomicNumber_t,element*> elementSet;
   public:
-    element *start; //!< start of element list
-    element *end;   //!< end of element list
+    typedef elementSet::iterator iterator;
+    typedef elementSet::const_iterator const_iterator;
+    typedef std::reverse_iterator<const_iterator> reverse_iterator;
+  public:
+
     char header1[MAXSTRINGSIZE]; //!< store first header line
     char header2[MAXSTRINGSIZE]; //!< store second header line
@@ -34,17 +41,23 @@
   ~periodentafel();
 
-  bool AddElement(element * const pointer);
-  bool RemoveElement(element * const pointer);
-  bool CleanupPeriodtable();
-  element * const FindElement(const int Z) const;
-  element * const FindElement(const char * const shorthand) const;
-  element * const AskElement() const;
-  element * const EnterElement();
-  bool Output(ofstream * const output) const;
-  bool Checkout(ofstream * const output, const int * const checkliste) const;
+  iterator AddElement(element * const pointer);
+  void RemoveElement(element * const pointer);
+  void CleanupPeriodtable();
+  const element *FindElement(atomicNumber_t) const;
+  const element *FindElement(const char * const shorthand) const;
+  const element *AskElement() const;
+  const element *EnterElement();
+
+  const_iterator begin();
+  const_iterator end();
+  reverse_iterator rbegin();
+  reverse_iterator rend();
+  bool Output(std::ostream * const output) const;
+  bool Checkout(std::ostream * const output, const int * const checkliste) const;
   bool LoadPeriodentafel(const char * const path);
   bool StorePeriodentafel(const char * const path) const;
 
   private:
+    elementSet elements;
 };
 
Index: src/stackclass.hpp
===================================================================
--- src/stackclass.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/stackclass.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -72,5 +72,5 @@
     return true;
   } else {
-    eLog() << Verbose(1) << "Stack is full, " << "Stack: CurrentLastEntry " << CurrentLastEntry<< "\tCurrentFirstEntry " << CurrentFirstEntry << "\tNextFreeField " << NextFreeField << "\tEntryCount " << EntryCount << "!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Stack is full, " << "Stack: CurrentLastEntry " << CurrentLastEntry<< "\tCurrentFirstEntry " << CurrentFirstEntry << "\tNextFreeField " << NextFreeField << "\tEntryCount " << EntryCount << "!" << endl);
     return false;
   }
@@ -87,5 +87,5 @@
     Walker = StackList[CurrentFirstEntry];
     if (Walker == NULL)
-      eLog() << Verbose(1) << "Stack's field is empty!" << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << "Stack's field is empty!" << endl);
     StackList[CurrentFirstEntry] = NULL;
     if (CurrentFirstEntry != CurrentLastEntry) { // hasn't last item been popped as well?
@@ -96,5 +96,5 @@
     }
   } else
-    eLog() << Verbose(1) << "Stack is empty!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Stack is empty!" << endl);
   return Walker;
 };
@@ -111,10 +111,10 @@
     StackList[CurrentLastEntry] = NULL;
     if (Walker == NULL)
-      eLog() << Verbose(1) << "Stack's field is empty!" << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << "Stack's field is empty!" << endl);
     NextFreeField = CurrentLastEntry;
     if (CurrentLastEntry != CurrentFirstEntry)  // has there been more than one item on stack
       CurrentLastEntry = (CurrentLastEntry + (EntryCount-1)) % EntryCount; // step back from current free field to last (modulo does not work in -1, thus go EntryCount-1 instead)
   } else {
-    eLog() << Verbose(1) << "Stack is empty!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Stack is empty!" << endl);
   }
   return Walker;
@@ -130,10 +130,10 @@
 {
   bool found = false;
-  Log() << Verbose(5) << "First " << CurrentFirstEntry<< "\tLast " << CurrentLastEntry<< "\tNext " << NextFreeField<< "\tCount " << EntryCount<< "." << endl;
+  DoLog(5) && (Log() << Verbose(5) << "First " << CurrentFirstEntry<< "\tLast " << CurrentLastEntry<< "\tNext " << NextFreeField<< "\tCount " << EntryCount<< "." << endl);
   int i=CurrentFirstEntry;
   if (!IsEmpty())
     do {
       if (StackList[i] == ptr) {  // if item found, remove
-        Log() << Verbose(5) << "Item " << *ptr << " was number " << i << " on stack, removing it." << endl;
+        DoLog(5) && (Log() << Verbose(5) << "Item " << *ptr << " was number " << i << " on stack, removing it." << endl);
         found = true;
         StackList[i] = NULL;
@@ -141,8 +141,8 @@
       if ((found) && (StackList[i] != NULL)) {  // means we have to shift (and not the removed item)
         if (i == 0) { // we are down to first item in stack, have to put onto last item
-          Log() << Verbose(5) << "Shifting item 0 to place " << EntryCount-1 << "." << endl;
+          DoLog(5) && (Log() << Verbose(5) << "Shifting item 0 to place " << EntryCount-1 << "." << endl);
           StackList[EntryCount-1] = StackList[0];
         } else {
-          Log() << Verbose(5) << "Shifting item " << i << " to place " << i-1 << "." << endl;
+          DoLog(5) && (Log() << Verbose(5) << "Shifting item " << i << " to place " << i-1 << "." << endl);
           StackList[i-1] = StackList[i];
         }
@@ -151,5 +151,5 @@
     } while (i!=NextFreeField);
   else
-    eLog() << Verbose(1) << "Stack is already empty!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Stack is already empty!" << endl);
   if (found) {
     NextFreeField = CurrentLastEntry;
Index: src/tesselation.cpp
===================================================================
--- src/tesselation.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/tesselation.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -7,4 +7,5 @@
 
 #include <fstream>
+#include <assert.h>
 
 #include "helpers.hpp"
@@ -14,6 +15,10 @@
 #include "tesselation.hpp"
 #include "tesselationhelpers.hpp"
+#include "triangleintersectionlist.hpp"
 #include "vector.hpp"
+#include "vector_ops.hpp"
 #include "verbose.hpp"
+#include "Plane.hpp"
+#include "Exceptions/LinearDependenceException.hpp"
 
 class molecule;
@@ -24,11 +29,10 @@
  */
 BoundaryPointSet::BoundaryPointSet() :
-    LinesCount(0),
-    value(0.),
-    Nr(-1)
-{
-	Info FunctionInfo(__func__);
-	Log() << Verbose(1) << "Adding noname." << endl;
-};
+  LinesCount(0), value(0.), Nr(-1)
+{
+  Info FunctionInfo(__func__);
+  DoLog(1) && (Log() << Verbose(1) << "Adding noname." << endl);
+}
+;
 
 /** Constructor of BoundaryPointSet with Tesselpoint.
@@ -36,12 +40,10 @@
  */
 BoundaryPointSet::BoundaryPointSet(TesselPoint * const Walker) :
-  LinesCount(0),
-  node(Walker),
-  value(0.),
-  Nr(Walker->nr)
-{
-	Info FunctionInfo(__func__);
-  Log() << Verbose(1) << "Adding Node " << *Walker << endl;
-};
+  LinesCount(0), node(Walker), value(0.), Nr(Walker->nr)
+{
+  Info FunctionInfo(__func__);
+  DoLog(1) && (Log() << Verbose(1) << "Adding Node " << *Walker << endl);
+}
+;
 
 /** Destructor of BoundaryPointSet.
@@ -51,10 +53,11 @@
 BoundaryPointSet::~BoundaryPointSet()
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   //Log() << Verbose(0) << "Erasing point nr. " << Nr << "." << endl;
   if (!lines.empty())
-    eLog() << Verbose(2) << "Memory Leak! I " << *this << " am still connected to some lines." << endl;
+    DoeLog(2) && (eLog() << Verbose(2) << "Memory Leak! I " << *this << " am still connected to some lines." << endl);
   node = NULL;
-};
+}
+;
 
 /** Add a line to the LineMap of this point.
@@ -63,17 +66,14 @@
 void BoundaryPointSet::AddLine(BoundaryLineSet * const line)
 {
-	Info FunctionInfo(__func__);
-  Log() << Verbose(1) << "Adding " << *this << " to line " << *line << "."
-      << endl;
-  if (line->endpoints[0] == this)
-    {
-      lines.insert(LinePair(line->endpoints[1]->Nr, line));
-    }
-  else
-    {
-      lines.insert(LinePair(line->endpoints[0]->Nr, line));
-    }
+  Info FunctionInfo(__func__);
+  DoLog(1) && (Log() << Verbose(1) << "Adding " << *this << " to line " << *line << "." << endl);
+  if (line->endpoints[0] == this) {
+    lines.insert(LinePair(line->endpoints[1]->Nr, line));
+  } else {
+    lines.insert(LinePair(line->endpoints[0]->Nr, line));
+  }
   LinesCount++;
-};
+}
+;
 
 /** output operator for BoundaryPointSet.
@@ -93,10 +93,11 @@
  */
 BoundaryLineSet::BoundaryLineSet() :
-    Nr(-1)
-{
-	Info FunctionInfo(__func__);
+  Nr(-1)
+{
+  Info FunctionInfo(__func__);
   for (int i = 0; i < 2; i++)
     endpoints[i] = NULL;
-};
+}
+;
 
 /** Constructor of BoundaryLineSet with two endpoints.
@@ -107,5 +108,5 @@
 BoundaryLineSet::BoundaryLineSet(BoundaryPointSet * const Point[2], const int number)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // set number
   Nr = number;
@@ -118,6 +119,7 @@
   skipped = false;
   // clear triangles list
-  Log() << Verbose(0) << "New Line with endpoints " << *this << "." << endl;
-};
+  DoLog(0) && (Log() << Verbose(0) << "New Line with endpoints " << *this << "." << endl);
+}
+;
 
 /** Constructor of BoundaryLineSet with two endpoints.
@@ -140,6 +142,7 @@
   skipped = false;
   // clear triangles list
-  Log() << Verbose(0) << "New Line with endpoints " << *this << "." << endl;
-};
+  DoLog(0) && (Log() << Verbose(0) << "New Line with endpoints " << *this << "." << endl);
+}
+;
 
 /** Destructor for BoundaryLineSet.
@@ -149,5 +152,5 @@
 BoundaryLineSet::~BoundaryLineSet()
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   int Numbers[2];
 
@@ -180,5 +183,5 @@
         //Log() << Verbose(0) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
         if (endpoints[i] != NULL) {
-          delete(endpoints[i]);
+          delete (endpoints[i]);
           endpoints[i] = NULL;
         }
@@ -187,6 +190,7 @@
   }
   if (!triangles.empty())
-    eLog() << Verbose(2) << "Memory Leak! I " << *this << " am still connected to some triangles." << endl;
-};
+    DoeLog(2) && (eLog() << Verbose(2) << "Memory Leak! I " << *this << " am still connected to some triangles." << endl);
+}
+;
 
 /** Add triangle to TriangleMap of this boundary line.
@@ -195,8 +199,9 @@
 void BoundaryLineSet::AddTriangle(BoundaryTriangleSet * const triangle)
 {
-	Info FunctionInfo(__func__);
-  Log() << Verbose(0) << "Add " << triangle->Nr << " to line " << *this << "." << endl;
+  Info FunctionInfo(__func__);
+  DoLog(0) && (Log() << Verbose(0) << "Add " << triangle->Nr << " to line " << *this << "." << endl);
   triangles.insert(TrianglePair(triangle->Nr, triangle));
-};
+}
+;
 
 /** Checks whether we have a common endpoint with given \a *line.
@@ -206,10 +211,11 @@
 bool BoundaryLineSet::IsConnectedTo(const BoundaryLineSet * const line) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
     return true;
   else
     return false;
-};
+}
+;
 
 /** Checks whether the adjacent triangles of a baseline are convex or not.
@@ -221,9 +227,9 @@
 bool BoundaryLineSet::CheckConvexityCriterion() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   Vector BaseLineCenter, BaseLineNormal, BaseLine, helper[2], NormalCheck;
   // get the two triangles
   if (triangles.size() != 2) {
-    eLog() << Verbose(0) << "Baseline " << *this << " is connected to less than two triangles, Tesselation incomplete!" << endl;
+    DoeLog(0) && (eLog() << Verbose(0) << "Baseline " << *this << " is connected to less than two triangles, Tesselation incomplete!" << endl);
     return true;
   }
@@ -231,9 +237,7 @@
   // have a normal vector on the base line pointing outwards
   //Log() << Verbose(0) << "INFO: " << *this << " has vectors at " << *(endpoints[0]->node->node) << " and at " << *(endpoints[1]->node->node) << "." << endl;
-  BaseLineCenter.CopyVector(endpoints[0]->node->node);
-  BaseLineCenter.AddVector(endpoints[1]->node->node);
-  BaseLineCenter.Scale(1./2.);
-  BaseLine.CopyVector(endpoints[0]->node->node);
-  BaseLine.SubtractVector(endpoints[1]->node->node);
+  BaseLineCenter = (1./2.)*((*endpoints[0]->node->node) + (*endpoints[1]->node->node));
+  BaseLine = (*endpoints[0]->node->node) - (*endpoints[1]->node->node);
+
   //Log() << Verbose(0) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
 
@@ -241,26 +245,25 @@
   NormalCheck.Zero();
   double sign = -1.;
-  int i=0;
+  int i = 0;
   class BoundaryPointSet *node = NULL;
-  for(TriangleMap::const_iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
+  for (TriangleMap::const_iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
     //Log() << Verbose(0) << "INFO: NormalVector of " << *(runner->second) << " is " << runner->second->NormalVector << "." << endl;
-    NormalCheck.AddVector(&runner->second->NormalVector);
-    NormalCheck.Scale(sign);
+    NormalCheck += runner->second->NormalVector;
+    NormalCheck *= sign;
     sign = -sign;
     if (runner->second->NormalVector.NormSquared() > MYEPSILON)
-      BaseLineNormal.CopyVector(&runner->second->NormalVector);   // yes, copy second on top of first
+      BaseLineNormal = runner->second->NormalVector;   // yes, copy second on top of first
     else {
-      eLog() << Verbose(0) << "Triangle " << *runner->second << " has zero normal vector!" << endl;
+      DoeLog(0) && (eLog() << Verbose(0) << "Triangle " << *runner->second << " has zero normal vector!" << endl);
     }
     node = runner->second->GetThirdEndpoint(this);
     if (node != NULL) {
       //Log() << Verbose(0) << "INFO: Third node for triangle " << *(runner->second) << " is " << *node << " at " << *(node->node->node) << "." << endl;
-      helper[i].CopyVector(node->node->node);
-      helper[i].SubtractVector(&BaseLineCenter);
-      helper[i].MakeNormalVector(&BaseLine);  // we want to compare the triangle's heights' angles!
+      helper[i] = (*node->node->node) - BaseLineCenter;
+      helper[i].MakeNormalTo(BaseLine);  // we want to compare the triangle's heights' angles!
       //Log() << Verbose(0) << "INFO: Height vector with respect to baseline is " << helper[i] << "." << endl;
       i++;
     } else {
-      eLog() << Verbose(1) << "I cannot find third node in triangle, something's wrong." << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "I cannot find third node in triangle, something's wrong." << endl);
       return true;
     }
@@ -268,5 +271,5 @@
   //Log() << Verbose(0) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
   if (NormalCheck.NormSquared() < MYEPSILON) {
-    Log() << Verbose(0) << "ACCEPT: Normalvectors of both triangles are the same: convex." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "ACCEPT: Normalvectors of both triangles are the same: convex." << endl);
     return true;
   }
@@ -274,8 +277,8 @@
   double angle = GetAngle(helper[0], helper[1], BaseLineNormal);
   if ((angle - M_PI) > -MYEPSILON) {
-    Log() << Verbose(0) << "ACCEPT: Angle is greater than pi: convex." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "ACCEPT: Angle is greater than pi: convex." << endl);
     return true;
   } else {
-    Log() << Verbose(0) << "REJECT: Angle is less than pi: concave." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "REJECT: Angle is less than pi: concave." << endl);
     return false;
   }
@@ -288,10 +291,11 @@
 bool BoundaryLineSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
 {
-	Info FunctionInfo(__func__);
-  for(int i=0;i<2;i++)
+  Info FunctionInfo(__func__);
+  for (int i = 0; i < 2; i++)
     if (point == endpoints[i])
       return true;
   return false;
-};
+}
+;
 
 /** Returns other endpoint of the line.
@@ -301,5 +305,5 @@
 class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(const BoundaryPointSet * const point) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   if (endpoints[0] == point)
     return endpoints[1];
@@ -308,5 +312,6 @@
   else
     return NULL;
-};
+}
+;
 
 /** output operator for BoundaryLineSet.
@@ -314,9 +319,10 @@
  * \param &a boundary line
  */
-ostream & operator <<(ostream &ost, const  BoundaryLineSet &a)
+ostream & operator <<(ostream &ost, const BoundaryLineSet &a)
 {
   ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << "," << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "]";
   return ost;
-};
+}
+;
 
 // ======================================== Triangles on Boundary =================================
@@ -327,11 +333,11 @@
   Nr(-1)
 {
-	Info FunctionInfo(__func__);
-  for (int i = 0; i < 3; i++)
-    {
-      endpoints[i] = NULL;
-      lines[i] = NULL;
-    }
-};
+  Info FunctionInfo(__func__);
+  for (int i = 0; i < 3; i++) {
+    endpoints[i] = NULL;
+    lines[i] = NULL;
+  }
+}
+;
 
 /** Constructor for BoundaryTriangleSet with three lines.
@@ -342,5 +348,5 @@
   Nr(number)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // set number
   // set lines
@@ -354,21 +360,21 @@
     // for all three lines
     for (int j = 0; j < 2; j++) { // for both endpoints
-      OrderMap.insert(pair<int, class BoundaryPointSet *> (
-          line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
+      OrderMap.insert(pair<int, class BoundaryPointSet *> (line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
       // and we don't care whether insertion fails
     }
   // set endpoints
   int Counter = 0;
-  Log() << Verbose(0) << "New triangle " << Nr << " with end points: " << endl;
+  DoLog(0) && (Log() << Verbose(0) << "New triangle " << Nr << " with end points: " << endl);
   for (PointMap::iterator runner = OrderMap.begin(); runner != OrderMap.end(); runner++) {
     endpoints[Counter] = runner->second;
-    Log() << Verbose(0) << " " << *endpoints[Counter] << endl;
+    DoLog(0) && (Log() << Verbose(0) << " " << *endpoints[Counter] << endl);
     Counter++;
   }
   if (Counter < 3) {
-    eLog() << Verbose(0) << "We have a triangle with only two distinct endpoints!" << endl;
+    DoeLog(0) && (eLog() << Verbose(0) << "We have a triangle with only two distinct endpoints!" << endl);
     performCriticalExit();
   }
-};
+}
+;
 
 /** Destructor of BoundaryTriangleSet.
@@ -378,5 +384,5 @@
 BoundaryTriangleSet::~BoundaryTriangleSet()
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   for (int i = 0; i < 3; i++) {
     if (lines[i] != NULL) {
@@ -385,12 +391,13 @@
       }
       if (lines[i]->triangles.empty()) {
-          //Log() << Verbose(0) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
-          delete (lines[i]);
-          lines[i] = NULL;
+        //Log() << Verbose(0) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
+        delete (lines[i]);
+        lines[i] = NULL;
       }
     }
   }
   //Log() << Verbose(0) << "Erasing triangle Nr." << Nr << " itself." << endl;
-};
+}
+;
 
 /** Calculates the normal vector for this triangle.
@@ -400,13 +407,16 @@
 void BoundaryTriangleSet::GetNormalVector(const Vector &OtherVector)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // get normal vector
-  NormalVector.MakeNormalVector(endpoints[0]->node->node, endpoints[1]->node->node, endpoints[2]->node->node);
+  NormalVector = Plane(*(endpoints[0]->node->node),
+                       *(endpoints[1]->node->node),
+                       *(endpoints[2]->node->node)).getNormal();
 
   // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
-  if (NormalVector.ScalarProduct(&OtherVector) > 0.)
+  if (NormalVector.ScalarProduct(OtherVector) > 0.)
     NormalVector.Scale(-1.);
-  Log() << Verbose(1) << "Normal Vector is " << NormalVector << "." << endl;
-};
+  DoLog(1) && (Log() << Verbose(1) << "Normal Vector is " << NormalVector << "." << endl);
+}
+;
 
 /** Finds the point on the triangle \a *BTS through which the line defined by \a *MolCenter and \a *x crosses.
@@ -422,4 +432,5 @@
  * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
  */
+
 bool BoundaryTriangleSet::GetIntersectionInsideTriangle(const Vector * const MolCenter, const Vector * const x, Vector * const Intersection) const
 {
@@ -428,52 +439,63 @@
   Vector helper;
 
-  if (!Intersection->GetIntersectionWithPlane(&NormalVector, endpoints[0]->node->node, MolCenter, x)) {
-    eLog() << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl;
+  try {
+    *Intersection = Plane(NormalVector, *(endpoints[0]->node->node)).GetIntersection(*MolCenter, *x);
+  }
+  catch (LinearDependenceException &excp) {
+    Log() << Verbose(1) << excp;
+    DoeLog(1) && (eLog() << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl);
     return false;
   }
 
-  Log() << Verbose(1) << "INFO: Triangle is " << *this << "." << endl;
-  Log() << Verbose(1) << "INFO: Line is from " << *MolCenter << " to " << *x << "." << endl;
-  Log() << Verbose(1) << "INFO: Intersection is " << *Intersection << "." << endl;
-
-  if (Intersection->DistanceSquared(endpoints[0]->node->node) < MYEPSILON) {
-    Log() << Verbose(1) << "Intersection coindices with first endpoint." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Triangle is " << *this << "." << endl);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Line is from " << *MolCenter << " to " << *x << "." << endl);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Intersection is " << *Intersection << "." << endl);
+
+  if (Intersection->DistanceSquared(*endpoints[0]->node->node) < MYEPSILON) {
+    DoLog(1) && (Log() << Verbose(1) << "Intersection coindices with first endpoint." << endl);
     return true;
-  }   else if (Intersection->DistanceSquared(endpoints[1]->node->node) < MYEPSILON) {
-    Log() << Verbose(1) << "Intersection coindices with second endpoint." << endl;
+  }   else if (Intersection->DistanceSquared(*endpoints[1]->node->node) < MYEPSILON) {
+    DoLog(1) && (Log() << Verbose(1) << "Intersection coindices with second endpoint." << endl);
     return true;
-  }   else if (Intersection->DistanceSquared(endpoints[2]->node->node) < MYEPSILON) {
-    Log() << Verbose(1) << "Intersection coindices with third endpoint." << endl;
+  }   else if (Intersection->DistanceSquared(*endpoints[2]->node->node) < MYEPSILON) {
+    DoLog(1) && (Log() << Verbose(1) << "Intersection coindices with third endpoint." << endl);
     return true;
   }
   // Calculate cross point between one baseline and the line from the third endpoint to intersection
-  int i=0;
+  int i = 0;
   do {
-    if (CrossPoint.GetIntersectionOfTwoLinesOnPlane(endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node, endpoints[(i+2)%3]->node->node, Intersection, &NormalVector)) {
-      helper.CopyVector(endpoints[(i+1)%3]->node->node);
-      helper.SubtractVector(endpoints[i%3]->node->node);
-      CrossPoint.SubtractVector(endpoints[i%3]->node->node);  // cross point was returned as absolute vector
-      const double s = CrossPoint.ScalarProduct(&helper)/helper.NormSquared();
-      Log() << Verbose(1) << "INFO: Factor s is " << s << "." << endl;
+    try {
+      CrossPoint = GetIntersectionOfTwoLinesOnPlane(*(endpoints[i%3]->node->node),
+                                                    *(endpoints[(i+1)%3]->node->node),
+                                                    *(endpoints[(i+2)%3]->node->node),
+                                                    *Intersection);
+      helper = (*endpoints[(i+1)%3]->node->node) - (*endpoints[i%3]->node->node);
+      CrossPoint -= (*endpoints[i%3]->node->node);  // cross point was returned as absolute vector
+      const double s = CrossPoint.ScalarProduct(helper)/helper.NormSquared();
+      DoLog(1) && (Log() << Verbose(1) << "INFO: Factor s is " << s << "." << endl);
       if ((s < -MYEPSILON) || ((s-1.) > MYEPSILON)) {
-        Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << "outside of triangle." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << "outside of triangle." << endl);
         i=4;
         break;
       }
       i++;
-    } else 
+    } catch (LinearDependenceException &excp){
       break;
-  } while (i<3);
-  if (i==3) {
-    Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " inside of triangle." << endl;
+    }
+  } while (i < 3);
+  if (i == 3) {
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " inside of triangle." << endl);
     return true;
   } else {
-    Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " outside of triangle." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " outside of triangle." << endl);
     return false;
   }
-};
-
-/** Finds the point on the triangle \a *BTS through which the line defined by \a *MolCenter and \a *x crosses.
- * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
+}
+;
+
+/** Finds the point on the triangle to the point \a *x.
+ * We call Vector::GetIntersectionWithPlane() with \a * and the center of the triangle to receive an intersection point.
+ * Then we check the in-plane part (the part projected down onto plane). We check whether it crosses one of the
+ * boundary lines. If it does, we return this intersection as closest point, otherwise the projected point down.
  * Thus we test if it's really on the plane and whether it's inside the triangle on the plane or not.
  * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
@@ -490,20 +512,21 @@
 
   // 1. get intersection with plane
-  Log() << Verbose(1) << "INFO: Looking for closest point of triangle " << *this << " to " << *x << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Looking for closest point of triangle " << *this << " to " << *x << "." << endl);
   GetCenter(&Direction);
-  if (!ClosestPoint->GetIntersectionWithPlane(&NormalVector, endpoints[0]->node->node, x, &Direction)) {
-    ClosestPoint->CopyVector(x);
+  try {
+    *ClosestPoint = Plane(NormalVector, *(endpoints[0]->node->node)).GetIntersection(*x, Direction);
+  }
+  catch (LinearDependenceException &excp) {
+    (*ClosestPoint) = (*x);
   }
 
   // 2. Calculate in plane part of line (x, intersection)
-  Vector InPlane;
-  InPlane.CopyVector(x);
-  InPlane.SubtractVector(ClosestPoint);  // points from plane intersection to straight-down point
-  InPlane.ProjectOntoPlane(&NormalVector);
-  InPlane.AddVector(ClosestPoint);
-
-  Log() << Verbose(2) << "INFO: Triangle is " << *this << "." << endl;
-  Log() << Verbose(2) << "INFO: Line is from " << Direction << " to " << *x << "." << endl;
-  Log() << Verbose(2) << "INFO: In-plane part is " << InPlane << "." << endl;
+  Vector InPlane = (*x) - (*ClosestPoint); // points from plane intersection to straight-down point
+  InPlane.ProjectOntoPlane(NormalVector);
+  InPlane += *ClosestPoint;
+
+  DoLog(2) && (Log() << Verbose(2) << "INFO: Triangle is " << *this << "." << endl);
+  DoLog(2) && (Log() << Verbose(2) << "INFO: Line is from " << Direction << " to " << *x << "." << endl);
+  DoLog(2) && (Log() << Verbose(2) << "INFO: In-plane part is " << InPlane << "." << endl);
 
   // Calculate cross point between one baseline and the desired point such that distance is shortest
@@ -513,22 +536,20 @@
   Vector CrossPoint[3];
   Vector helper;
-  for (int i=0;i<3;i++) {
+  for (int i = 0; i < 3; i++) {
     // treat direction of line as normal of a (cut)plane and the desired point x as the plane offset, the intersect line with point
-    Direction.CopyVector(endpoints[(i+1)%3]->node->node);
-    Direction.SubtractVector(endpoints[i%3]->node->node);
+    Direction = (*endpoints[(i+1)%3]->node->node) - (*endpoints[i%3]->node->node);
     // calculate intersection, line can never be parallel to Direction (is the same vector as PlaneNormal);
-    CrossPoint[i].GetIntersectionWithPlane(&Direction, &InPlane, endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node);
-    CrossDirection[i].CopyVector(&CrossPoint[i]);
-    CrossDirection[i].SubtractVector(&InPlane);
-    CrossPoint[i].SubtractVector(endpoints[i%3]->node->node);  // cross point was returned as absolute vector
-    const double s = CrossPoint[i].ScalarProduct(&Direction)/Direction.NormSquared();
-    Log() << Verbose(2) << "INFO: Factor s is " << s << "." << endl;
+    CrossPoint[i] = Plane(Direction, InPlane).GetIntersection(*(endpoints[i%3]->node->node), *(endpoints[(i+1)%3]->node->node));
+    CrossDirection[i] = CrossPoint[i] - InPlane;
+    CrossPoint[i] -= (*endpoints[i%3]->node->node);  // cross point was returned as absolute vector
+    const double s = CrossPoint[i].ScalarProduct(Direction)/Direction.NormSquared();
+    DoLog(2) && (Log() << Verbose(2) << "INFO: Factor s is " << s << "." << endl);
     if ((s >= -MYEPSILON) && ((s-1.) <= MYEPSILON)) {
-      CrossPoint[i].AddVector(endpoints[i%3]->node->node);  // make cross point absolute again
-      Log() << Verbose(2) << "INFO: Crosspoint is " << CrossPoint[i] << ", intersecting BoundaryLine between " << *endpoints[i%3]->node->node << " and " << *endpoints[(i+1)%3]->node->node << "." << endl;
-      const double distance = CrossPoint[i].DistanceSquared(x);
+          CrossPoint[i] += (*endpoints[i%3]->node->node);  // make cross point absolute again
+      DoLog(2) && (Log() << Verbose(2) << "INFO: Crosspoint is " << CrossPoint[i] << ", intersecting BoundaryLine between " << *endpoints[i % 3]->node->node << " and " << *endpoints[(i + 1) % 3]->node->node << "." << endl);
+      const double distance = CrossPoint[i].DistanceSquared(*x);
       if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
         ShortestDistance = distance;
-        ClosestPoint->CopyVector(&CrossPoint[i]);
+        (*ClosestPoint) = CrossPoint[i];
       }
     } else
@@ -536,25 +557,27 @@
   }
   InsideFlag = true;
-  for (int i=0;i<3;i++) {
-    const double sign = CrossDirection[i].ScalarProduct(&CrossDirection[(i+1)%3]);
-    const double othersign = CrossDirection[i].ScalarProduct(&CrossDirection[(i+2)%3]);;
-    if ((sign > -MYEPSILON) && (othersign > -MYEPSILON))  // have different sign
+  for (int i = 0; i < 3; i++) {
+    const double sign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 1) % 3]);
+    const double othersign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 2) % 3]);
+
+    if ((sign > -MYEPSILON) && (othersign > -MYEPSILON)) // have different sign
       InsideFlag = false;
   }
   if (InsideFlag) {
-    ClosestPoint->CopyVector(&InPlane);
-    ShortestDistance = InPlane.DistanceSquared(x);
-  } else {  // also check endnodes
-    for (int i=0;i<3;i++) {
-      const double distance = x->DistanceSquared(endpoints[i]->node->node);
+    (*ClosestPoint) = InPlane;
+    ShortestDistance = InPlane.DistanceSquared(*x);
+  } else { // also check endnodes
+    for (int i = 0; i < 3; i++) {
+      const double distance = x->DistanceSquared(*endpoints[i]->node->node);
       if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
         ShortestDistance = distance;
-        ClosestPoint->CopyVector(endpoints[i]->node->node);
+        (*ClosestPoint) = (*endpoints[i]->node->node);
       }
     }
   }
-  Log() << Verbose(1) << "INFO: Closest Point is " << *ClosestPoint << " with shortest squared distance is " << ShortestDistance << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Closest Point is " << *ClosestPoint << " with shortest squared distance is " << ShortestDistance << "." << endl);
   return ShortestDistance;
-};
+}
+;
 
 /** Checks whether lines is any of the three boundary lines this triangle contains.
@@ -564,10 +587,11 @@
 bool BoundaryTriangleSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
 {
-	Info FunctionInfo(__func__);
-  for(int i=0;i<3;i++)
+  Info FunctionInfo(__func__);
+  for (int i = 0; i < 3; i++)
     if (line == lines[i])
       return true;
   return false;
-};
+}
+;
 
 /** Checks whether point is any of the three endpoints this triangle contains.
@@ -577,10 +601,11 @@
 bool BoundaryTriangleSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
 {
-	Info FunctionInfo(__func__);
-  for(int i=0;i<3;i++)
+  Info FunctionInfo(__func__);
+  for (int i = 0; i < 3; i++)
     if (point == endpoints[i])
       return true;
   return false;
-};
+}
+;
 
 /** Checks whether point is any of the three endpoints this triangle contains.
@@ -590,10 +615,11 @@
 bool BoundaryTriangleSet::ContainsBoundaryPoint(const TesselPoint * const point) const
 {
-	Info FunctionInfo(__func__);
-  for(int i=0;i<3;i++)
+  Info FunctionInfo(__func__);
+  for (int i = 0; i < 3; i++)
     if (point == endpoints[i]->node)
       return true;
   return false;
-};
+}
+;
 
 /** Checks whether three given \a *Points coincide with triangle's endpoints.
@@ -603,20 +629,11 @@
 bool BoundaryTriangleSet::IsPresentTupel(const BoundaryPointSet * const Points[3]) const
 {
-	Info FunctionInfo(__func__);
-	Log() << Verbose(1) << "INFO: Checking " << Points[0] << ","  << Points[1] << "," << Points[2] << " against " << endpoints[0] << "," << endpoints[1] << "," << endpoints[2] << "." << endl;
-  return (((endpoints[0] == Points[0])
-            || (endpoints[0] == Points[1])
-            || (endpoints[0] == Points[2])
-          ) && (
-            (endpoints[1] == Points[0])
-            || (endpoints[1] == Points[1])
-            || (endpoints[1] == Points[2])
-          ) && (
-            (endpoints[2] == Points[0])
-            || (endpoints[2] == Points[1])
-            || (endpoints[2] == Points[2])
-
-          ));
-};
+  Info FunctionInfo(__func__);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Checking " << Points[0] << "," << Points[1] << "," << Points[2] << " against " << endpoints[0] << "," << endpoints[1] << "," << endpoints[2] << "." << endl);
+  return (((endpoints[0] == Points[0]) || (endpoints[0] == Points[1]) || (endpoints[0] == Points[2])) && ((endpoints[1] == Points[0]) || (endpoints[1] == Points[1]) || (endpoints[1] == Points[2])) && ((endpoints[2] == Points[0]) || (endpoints[2] == Points[1]) || (endpoints[2] == Points[2])
+
+  ));
+}
+;
 
 /** Checks whether three given \a *Points coincide with triangle's endpoints.
@@ -626,19 +643,10 @@
 bool BoundaryTriangleSet::IsPresentTupel(const BoundaryTriangleSet * const T) const
 {
-	Info FunctionInfo(__func__);
-  return (((endpoints[0] == T->endpoints[0])
-            || (endpoints[0] == T->endpoints[1])
-            || (endpoints[0] == T->endpoints[2])
-          ) && (
-            (endpoints[1] == T->endpoints[0])
-            || (endpoints[1] == T->endpoints[1])
-            || (endpoints[1] == T->endpoints[2])
-          ) && (
-            (endpoints[2] == T->endpoints[0])
-            || (endpoints[2] == T->endpoints[1])
-            || (endpoints[2] == T->endpoints[2])
-
-          ));
-};
+  Info FunctionInfo(__func__);
+  return (((endpoints[0] == T->endpoints[0]) || (endpoints[0] == T->endpoints[1]) || (endpoints[0] == T->endpoints[2])) && ((endpoints[1] == T->endpoints[0]) || (endpoints[1] == T->endpoints[1]) || (endpoints[1] == T->endpoints[2])) && ((endpoints[2] == T->endpoints[0]) || (endpoints[2] == T->endpoints[1]) || (endpoints[2] == T->endpoints[2])
+
+  ));
+}
+;
 
 /** Returns the endpoint which is not contained in the given \a *line.
@@ -648,14 +656,15 @@
 class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(const BoundaryLineSet * const line) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // sanity check
   if (!ContainsBoundaryLine(line))
     return NULL;
-  for(int i=0;i<3;i++)
+  for (int i = 0; i < 3; i++)
     if (!line->ContainsBoundaryPoint(endpoints[i]))
       return endpoints[i];
   // actually, that' impossible :)
   return NULL;
-};
+}
+;
 
 /** Calculates the center point of the triangle.
@@ -665,10 +674,10 @@
 void BoundaryTriangleSet::GetCenter(Vector * const center) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   center->Zero();
-  for(int i=0;i<3;i++)
-    center->AddVector(endpoints[i]->node->node);
-  center->Scale(1./3.);
-  Log() << Verbose(1) << "INFO: Center is at " << *center << "." << endl;
+  for (int i = 0; i < 3; i++)
+    (*center) += (*endpoints[i]->node->node);
+  center->Scale(1. / 3.);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Center is at " << *center << "." << endl);
 }
 
@@ -680,8 +689,9 @@
 {
   ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << "," << a.endpoints[1]->node->Name << "," << a.endpoints[2]->node->Name << "]";
-//  ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
-//      << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
+  //  ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
+  //      << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
   return ost;
-};
+}
+;
 
 // ======================================== Polygons on Boundary =================================
@@ -693,5 +703,6 @@
 {
   Info FunctionInfo(__func__);
-};
+}
+;
 
 /** Destructor of BoundaryPolygonSet.
@@ -703,6 +714,7 @@
   Info FunctionInfo(__func__);
   endpoints.clear();
-  Log() << Verbose(1) << "Erasing polygon Nr." << Nr << " itself." << endl;
-};
+  DoLog(1) && (Log() << Verbose(1) << "Erasing polygon Nr." << Nr << " itself." << endl);
+}
+;
 
 /** Calculates the normal vector for this triangle.
@@ -718,10 +730,10 @@
   Vector *TotalNormal = new Vector;
   PointSet::const_iterator Runner[3];
-  for (int i=0;i<3; i++) {
+  for (int i = 0; i < 3; i++) {
     Runner[i] = endpoints.begin();
-    for (int j = 0; j<i; j++) { // go as much further
+    for (int j = 0; j < i; j++) { // go as much further
       Runner[i]++;
       if (Runner[i] == endpoints.end()) {
-        eLog() << Verbose(0) << "There are less than three endpoints in the polygon!" << endl;
+        DoeLog(0) && (eLog() << Verbose(0) << "There are less than three endpoints in the polygon!" << endl);
         performCriticalExit();
       }
@@ -729,20 +741,23 @@
   }
   TotalNormal->Zero();
-  int counter=0;
-  for (; Runner[2] != endpoints.end(); ) {
-    TemporaryNormal.MakeNormalVector((*Runner[0])->node->node, (*Runner[1])->node->node, (*Runner[2])->node->node);
-    for (int i=0;i<3;i++) // increase each of them
+  int counter = 0;
+  for (; Runner[2] != endpoints.end();) {
+    TemporaryNormal = Plane(*((*Runner[0])->node->node),
+                            *((*Runner[1])->node->node),
+                            *((*Runner[2])->node->node)).getNormal();
+    for (int i = 0; i < 3; i++) // increase each of them
       Runner[i]++;
-    TotalNormal->AddVector(&TemporaryNormal);
-  }
-  TotalNormal->Scale(1./(double)counter);
+    (*TotalNormal) += TemporaryNormal;
+  }
+  TotalNormal->Scale(1. / (double) counter);
 
   // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
-  if (TotalNormal->ScalarProduct(&OtherVector) > 0.)
+  if (TotalNormal->ScalarProduct(OtherVector) > 0.)
     TotalNormal->Scale(-1.);
-  Log() << Verbose(1) << "Normal Vector is " << *TotalNormal << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Normal Vector is " << *TotalNormal << "." << endl);
 
   return TotalNormal;
-};
+}
+;
 
 /** Calculates the center point of the triangle.
@@ -756,9 +771,9 @@
   int counter = 0;
   for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
-    center->AddVector((*Runner)->node->node);
+    (*center) += (*(*Runner)->node->node);
     counter++;
   }
-  center->Scale(1./(double)counter);
-  Log() << Verbose(1) << "Center is at " << *center << "." << endl;
+  center->Scale(1. / (double) counter);
+  DoLog(1) && (Log() << Verbose(1) << "Center is at " << *center << "." << endl);
 }
 
@@ -771,5 +786,6 @@
   Info FunctionInfo(__func__);
   return ContainsPresentTupel(triangle->endpoints, 3);
-};
+}
+;
 
 /** Checks whether the polygons contains both endpoints of the line.
@@ -781,5 +797,6 @@
   Info FunctionInfo(__func__);
   return ContainsPresentTupel(line->endpoints, 2);
-};
+}
+;
 
 /** Checks whether point is any of the three endpoints this triangle contains.
@@ -790,14 +807,15 @@
 {
   Info FunctionInfo(__func__);
-  for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
-    Log() << Verbose(0) << "Checking against " << **Runner << endl;
+  for (PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
+    DoLog(0) && (Log() << Verbose(0) << "Checking against " << **Runner << endl);
     if (point == (*Runner)) {
-      Log() << Verbose(0) << " Contained." << endl;
+      DoLog(0) && (Log() << Verbose(0) << " Contained." << endl);
       return true;
     }
   }
-  Log() << Verbose(0) << " Not contained." << endl;
+  DoLog(0) && (Log() << Verbose(0) << " Not contained." << endl);
   return false;
-};
+}
+;
 
 /** Checks whether point is any of the three endpoints this triangle contains.
@@ -808,12 +826,13 @@
 {
   Info FunctionInfo(__func__);
-  for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
+  for (PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
     if (point == (*Runner)->node) {
-      Log() << Verbose(0) << " Contained." << endl;
+      DoLog(0) && (Log() << Verbose(0) << " Contained." << endl);
       return true;
     }
-  Log() << Verbose(0) << " Not contained." << endl;
+  DoLog(0) && (Log() << Verbose(0) << " Not contained." << endl);
   return false;
-};
+}
+;
 
 /** Checks whether given array of \a *Points coincide with polygons's endpoints.
@@ -826,7 +845,7 @@
   Info FunctionInfo(__func__);
   int counter = 0;
-  Log() << Verbose(1) << "Polygon is " << *this << endl;
-  for(int i=0;i<dim;i++) {
-    Log() << Verbose(1) << " Testing endpoint " << *Points[i] << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Polygon is " << *this << endl);
+  for (int i = 0; i < dim; i++) {
+    DoLog(1) && (Log() << Verbose(1) << " Testing endpoint " << *Points[i] << endl);
     if (ContainsBoundaryPoint(Points[i])) {
       counter++;
@@ -838,5 +857,6 @@
   else
     return false;
-};
+}
+;
 
 /** Checks whether given PointList coincide with polygons's endpoints.
@@ -848,7 +868,7 @@
   Info FunctionInfo(__func__);
   size_t counter = 0;
-  Log() << Verbose(1) << "Polygon is " << *this << endl;
-  for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
-    Log() << Verbose(1) << " Testing endpoint " << **Runner << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Polygon is " << *this << endl);
+  for (PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
+    DoLog(1) && (Log() << Verbose(1) << " Testing endpoint " << **Runner << endl);
     if (ContainsBoundaryPoint(*Runner))
       counter++;
@@ -859,5 +879,6 @@
   else
     return false;
-};
+}
+;
 
 /** Checks whether given set of \a *Points coincide with polygons's endpoints.
@@ -867,6 +888,7 @@
 bool BoundaryPolygonSet::ContainsPresentTupel(const BoundaryPolygonSet * const P) const
 {
-  return ContainsPresentTupel((const PointSet)P->endpoints);
-};
+  return ContainsPresentTupel((const PointSet) P->endpoints);
+}
+;
 
 /** Gathers all the endpoints' triangles in a unique set.
@@ -876,21 +898,22 @@
 {
   Info FunctionInfo(__func__);
-  pair <TriangleSet::iterator, bool> Tester;
+  pair<TriangleSet::iterator, bool> Tester;
   TriangleSet *triangles = new TriangleSet;
 
-  for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
-    for(LineMap::const_iterator Walker = (*Runner)->lines.begin(); Walker != (*Runner)->lines.end(); Walker++)
-      for(TriangleMap::const_iterator Sprinter = (Walker->second)->triangles.begin(); Sprinter != (Walker->second)->triangles.end(); Sprinter++) {
+  for (PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
+    for (LineMap::const_iterator Walker = (*Runner)->lines.begin(); Walker != (*Runner)->lines.end(); Walker++)
+      for (TriangleMap::const_iterator Sprinter = (Walker->second)->triangles.begin(); Sprinter != (Walker->second)->triangles.end(); Sprinter++) {
         //Log() << Verbose(0) << " Testing triangle " << *(Sprinter->second) << endl;
         if (ContainsBoundaryTriangle(Sprinter->second)) {
           Tester = triangles->insert(Sprinter->second);
           if (Tester.second)
-            Log() << Verbose(0) << "Adding triangle " << *(Sprinter->second) << endl;
+            DoLog(0) && (Log() << Verbose(0) << "Adding triangle " << *(Sprinter->second) << endl);
         }
       }
 
-  Log() << Verbose(1) << "The Polygon of " << endpoints.size() << " endpoints has " << triangles->size() << " unique triangles in total." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "The Polygon of " << endpoints.size() << " endpoints has " << triangles->size() << " unique triangles in total." << endl);
   return triangles;
-};
+}
+;
 
 /** Fills the endpoints of this polygon from the triangles attached to \a *line.
@@ -901,18 +924,19 @@
 {
   Info FunctionInfo(__func__);
-  pair <PointSet::iterator, bool> Tester;
+  pair<PointSet::iterator, bool> Tester;
   if (line == NULL)
     return false;
-  Log() << Verbose(1) << "Filling polygon from line " << *line << endl;
-  for(TriangleMap::const_iterator Runner = line->triangles.begin(); Runner != line->triangles.end(); Runner++) {
-    for (int i=0;i<3;i++) {
+  DoLog(1) && (Log() << Verbose(1) << "Filling polygon from line " << *line << endl);
+  for (TriangleMap::const_iterator Runner = line->triangles.begin(); Runner != line->triangles.end(); Runner++) {
+    for (int i = 0; i < 3; i++) {
       Tester = endpoints.insert((Runner->second)->endpoints[i]);
       if (Tester.second)
-        Log() << Verbose(1) << "  Inserting endpoint " << *((Runner->second)->endpoints[i]) << endl;
+        DoLog(1) && (Log() << Verbose(1) << "  Inserting endpoint " << *((Runner->second)->endpoints[i]) << endl);
     }
   }
 
   return true;
-};
+}
+;
 
 /** output operator for BoundaryPolygonSet.
@@ -923,13 +947,14 @@
 {
   ost << "[" << a.Nr << "|";
-  for(PointSet::const_iterator Runner = a.endpoints.begin(); Runner != a.endpoints.end();) {
-   ost << (*Runner)->node->Name;
-   Runner++;
-   if (Runner != a.endpoints.end())
-     ost << ",";
-  }
-  ost<< "]";
+  for (PointSet::const_iterator Runner = a.endpoints.begin(); Runner != a.endpoints.end();) {
+    ost << (*Runner)->node->Name;
+    Runner++;
+    if (Runner != a.endpoints.end())
+      ost << ",";
+  }
+  ost << "]";
   return ost;
-};
+}
+;
 
 // =========================================================== class TESSELPOINT ===========================================
@@ -942,6 +967,7 @@
   node = NULL;
   nr = -1;
-  Name =  NULL;
-};
+  Name = NULL;
+}
+;
 
 /** Destructor for class TesselPoint.
@@ -950,70 +976,156 @@
 {
   //Info FunctionInfo(__func__);
-};
+}
+;
 
 /** Prints LCNode to screen.
  */
-ostream & operator << (ostream &ost, const TesselPoint &a)
+ostream & operator <<(ostream &ost, const TesselPoint &a)
 {
   ost << "[" << (a.Name) << "|" << a.Name << " at " << *a.node << "]";
   return ost;
-};
+}
+;
 
 /** Prints LCNode to screen.
  */
-ostream & TesselPoint::operator << (ostream &ost)
-{
-	Info FunctionInfo(__func__);
+ostream & TesselPoint::operator <<(ostream &ost)
+{
+  Info FunctionInfo(__func__);
   ost << "[" << (nr) << "|" << this << "]";
   return ost;
+}
+;
+
+// =========================================================== class POINTCLOUD ============================================
+
+/** Constructor of class PointCloud.
+ */
+PointCloud::PointCloud()
+{
+  //Info FunctionInfo(__func__);
+}
+;
+
+/** Destructor for class PointCloud.
+ */
+PointCloud::~PointCloud()
+{
+  //Info FunctionInfo(__func__);
+}
+;
+
+// ============================ CandidateForTesselation =============================
+
+/** Constructor of class CandidateForTesselation.
+ */
+CandidateForTesselation::CandidateForTesselation(BoundaryLineSet* line) :
+  BaseLine(line), ThirdPoint(NULL), T(NULL), ShortestAngle(2. * M_PI), OtherShortestAngle(2. * M_PI)
+{
+  Info FunctionInfo(__func__);
+}
+;
+
+/** Constructor of class CandidateForTesselation.
+ */
+CandidateForTesselation::CandidateForTesselation(TesselPoint *candidate, BoundaryLineSet* line, BoundaryPointSet* point, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) :
+  BaseLine(line), ThirdPoint(point), T(NULL), ShortestAngle(2. * M_PI), OtherShortestAngle(2. * M_PI)
+{
+	Info FunctionInfo(__func__);
+  OptCenter = OptCandidateCenter;
+  OtherOptCenter = OtherOptCandidateCenter;
 };
 
 
-// =========================================================== class POINTCLOUD ============================================
-
-/** Constructor of class PointCloud.
- */
-PointCloud::PointCloud()
-{
-	//Info FunctionInfo(__func__);
-};
-
-/** Destructor for class PointCloud.
- */
-PointCloud::~PointCloud()
-{
-	//Info FunctionInfo(__func__);
-};
-
-// ============================ CandidateForTesselation =============================
-
-/** Constructor of class CandidateForTesselation.
- */
-CandidateForTesselation::CandidateForTesselation (BoundaryLineSet* line) :
-  BaseLine(line),
-  ShortestAngle(2.*M_PI),
-  OtherShortestAngle(2.*M_PI)
-{
-	Info FunctionInfo(__func__);
-};
-
-
-/** Constructor of class CandidateForTesselation.
- */
-CandidateForTesselation::CandidateForTesselation (TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) :
-    BaseLine(line),
-    ShortestAngle(2.*M_PI),
-    OtherShortestAngle(2.*M_PI)
-{
-	Info FunctionInfo(__func__);
-  OptCenter.CopyVector(&OptCandidateCenter);
-  OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
-};
-
 /** Destructor for class CandidateForTesselation.
  */
-CandidateForTesselation::~CandidateForTesselation() {
-  BaseLine = NULL;
-};
+CandidateForTesselation::~CandidateForTesselation()
+{
+}
+;
+
+/** Checks validity of a given sphere of a candidate line.
+ * Sphere must touch all candidates and the baseline endpoints and there must be no other atoms inside.
+ * \param RADIUS radius of sphere
+ * \param *LC LinkedCell structure with other atoms
+ * \return true - sphere is valid, false - sphere contains other points
+ */
+bool CandidateForTesselation::CheckValidity(const double RADIUS, const LinkedCell *LC) const
+{
+  Info FunctionInfo(__func__);
+
+  const double radiusSquared = RADIUS * RADIUS;
+  list<const Vector *> VectorList;
+  VectorList.push_back(&OptCenter);
+  //VectorList.push_back(&OtherOptCenter);  // don't check the other (wrong) center
+
+  if (!pointlist.empty())
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Checking whether sphere contains candidate list and baseline " << *BaseLine->endpoints[0] << "<->" << *BaseLine->endpoints[1] << " only ..." << endl);
+  else
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Checking whether sphere with no candidates contains baseline " << *BaseLine->endpoints[0] << "<->" << *BaseLine->endpoints[1] << " only ..." << endl);
+  // check baseline for OptCenter and OtherOptCenter being on sphere's surface
+  for (list<const Vector *>::const_iterator VRunner = VectorList.begin(); VRunner != VectorList.end(); ++VRunner) {
+    for (int i = 0; i < 2; i++) {
+      const double distance = fabs((*VRunner)->DistanceSquared(*BaseLine->endpoints[i]->node->node) - radiusSquared);
+      if (distance > HULLEPSILON) {
+        DoeLog(1) && (eLog() << Verbose(1) << "Endpoint " << *BaseLine->endpoints[i] << " is out of sphere at " << *(*VRunner) << " by " << distance << "." << endl);
+        return false;
+      }
+    }
+  }
+
+  // check Candidates for OptCenter and OtherOptCenter being on sphere's surface
+  for (TesselPointList::const_iterator Runner = pointlist.begin(); Runner != pointlist.end(); ++Runner) {
+    const TesselPoint *Walker = *Runner;
+    for (list<const Vector *>::const_iterator VRunner = VectorList.begin(); VRunner != VectorList.end(); ++VRunner) {
+      const double distance = fabs((*VRunner)->DistanceSquared(*Walker->node) - radiusSquared);
+      if (distance > HULLEPSILON) {
+        DoeLog(1) && (eLog() << Verbose(1) << "Candidate " << *Walker << " is out of sphere at " << *(*VRunner) << " by " << distance << "." << endl);
+        return false;
+      } else {
+        DoLog(1) && (Log() << Verbose(1) << "Candidate " << *Walker << " is inside by " << distance << "." << endl);
+      }
+    }
+  }
+
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Checking whether sphere contains no others points ..." << endl);
+  bool flag = true;
+  for (list<const Vector *>::const_iterator VRunner = VectorList.begin(); VRunner != VectorList.end(); ++VRunner) {
+    // get all points inside the sphere
+    TesselPointList *ListofPoints = LC->GetPointsInsideSphere(RADIUS, (*VRunner));
+
+    DoLog(1) && (Log() << Verbose(1) << "The following atoms are inside sphere at " << OtherOptCenter << ":" << endl);
+    for (TesselPointList::const_iterator Runner = ListofPoints->begin(); Runner != ListofPoints->end(); ++Runner)
+      DoLog(1) && (Log() << Verbose(1) << "  " << *(*Runner) << " with distance " << (*Runner)->node->distance(OtherOptCenter) << "." << endl);
+
+    // remove baseline's endpoints and candidates
+    for (int i = 0; i < 2; i++) {
+      DoLog(1) && (Log() << Verbose(1) << "INFO: removing baseline tesselpoint " << *BaseLine->endpoints[i]->node << "." << endl);
+      ListofPoints->remove(BaseLine->endpoints[i]->node);
+    }
+    for (TesselPointList::const_iterator Runner = pointlist.begin(); Runner != pointlist.end(); ++Runner) {
+      DoLog(1) && (Log() << Verbose(1) << "INFO: removing candidate tesselpoint " << *(*Runner) << "." << endl);
+      ListofPoints->remove(*Runner);
+    }
+    if (!ListofPoints->empty()) {
+      DoeLog(1) && (eLog() << Verbose(1) << "CheckValidity: There are still " << ListofPoints->size() << " points inside the sphere." << endl);
+      flag = false;
+      DoeLog(1) && (eLog() << Verbose(1) << "External atoms inside of sphere at " << *(*VRunner) << ":" << endl);
+      for (TesselPointList::const_iterator Runner = ListofPoints->begin(); Runner != ListofPoints->end(); ++Runner)
+        DoeLog(1) && (eLog() << Verbose(1) << "  " << *(*Runner) << endl);
+    }
+    delete (ListofPoints);
+
+    // check with animate_sphere.tcl VMD script
+    if (ThirdPoint != NULL) {
+      DoLog(1) && (Log() << Verbose(1) << "Check by: animate_sphere 0 " << BaseLine->endpoints[0]->Nr + 1 << " " << BaseLine->endpoints[1]->Nr + 1 << " " << ThirdPoint->Nr + 1 << " " << RADIUS << " " << OldCenter[0] << " " << OldCenter[1] << " " << OldCenter[2] << " " << (*VRunner)->at(0) << " " << (*VRunner)->at(1) << " " << (*VRunner)->at(2) << endl);
+    } else {
+      DoLog(1) && (Log() << Verbose(1) << "Check by: ... missing third point ..." << endl);
+      DoLog(1) && (Log() << Verbose(1) << "Check by: animate_sphere 0 " << BaseLine->endpoints[0]->Nr + 1 << " " << BaseLine->endpoints[1]->Nr + 1 << " ??? " << RADIUS << " " << OldCenter[0] << " " << OldCenter[1] << " " << OldCenter[2] << " " << (*VRunner)->at(0) << " " << (*VRunner)->at(1) << " " << (*VRunner)->at(2) << endl);
+    }
+  }
+  return flag;
+}
+;
 
 /** output operator for CandidateForTesselation.
@@ -1021,5 +1133,5 @@
  * \param &a boundary line
  */
-ostream & operator <<(ostream &ost, const  CandidateForTesselation &a)
+ostream & operator <<(ostream &ost, const CandidateForTesselation &a)
 {
   ost << "[" << a.BaseLine->Nr << "|" << a.BaseLine->endpoints[0]->node->Name << "," << a.BaseLine->endpoints[1]->node->Name << "] with ";
@@ -1034,10 +1146,10 @@
     for (TesselPointList::const_iterator Runner = a.pointlist.begin(); Runner != a.pointlist.end(); Runner++)
       ost << *(*Runner) << " ";
-    ost << " at angle " << (a.ShortestAngle)<< ".";
+    ost << " at angle " << (a.ShortestAngle) << ".";
   }
 
   return ost;
-};
-
+}
+;
 
 // =========================================================== class TESSELATION ===========================================
@@ -1046,12 +1158,7 @@
  */
 Tesselation::Tesselation() :
-  PointsOnBoundaryCount(0),
-  LinesOnBoundaryCount(0),
-  TrianglesOnBoundaryCount(0),
-  LastTriangle(NULL),
-  TriangleFilesWritten(0),
-  InternalPointer(PointsOnBoundary.begin())
-{
-	Info FunctionInfo(__func__);
+  PointsOnBoundaryCount(0), LinesOnBoundaryCount(0), TrianglesOnBoundaryCount(0), LastTriangle(NULL), TriangleFilesWritten(0), InternalPointer(PointsOnBoundary.begin())
+{
+  Info FunctionInfo(__func__);
 }
 ;
@@ -1062,6 +1169,6 @@
 Tesselation::~Tesselation()
 {
-	Info FunctionInfo(__func__);
-  Log() << Verbose(0) << "Free'ing TesselStruct ... " << endl;
+  Info FunctionInfo(__func__);
+  DoLog(0) && (Log() << Verbose(0) << "Free'ing TesselStruct ... " << endl);
   for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
     if (runner->second != NULL) {
@@ -1069,7 +1176,7 @@
       runner->second = NULL;
     } else
-      eLog() << Verbose(1) << "The triangle " << runner->first << " has already been free'd." << endl;
-  }
-  Log() << Verbose(0) << "This envelope was written to file " << TriangleFilesWritten << " times(s)." << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "The triangle " << runner->first << " has already been free'd." << endl);
+  }
+  DoLog(0) && (Log() << Verbose(0) << "This envelope was written to file " << TriangleFilesWritten << " times(s)." << endl);
 }
 ;
@@ -1077,66 +1184,72 @@
 /** PointCloud implementation of GetCenter
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 Vector * Tesselation::GetCenter(ofstream *out) const
 {
-	Info FunctionInfo(__func__);
-  Vector *Center = new Vector(0.,0.,0.);
-  int num=0;
+  Info FunctionInfo(__func__);
+  Vector *Center = new Vector(0., 0., 0.);
+  int num = 0;
   for (GoToFirst(); (!IsEnd()); GoToNext()) {
-    Center->AddVector(GetPoint()->node);
+    (*Center) += (*GetPoint()->node);
     num++;
   }
-  Center->Scale(1./num);
+  Center->Scale(1. / num);
   return Center;
-};
+}
+;
 
 /** PointCloud implementation of GoPoint
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 TesselPoint * Tesselation::GetPoint() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   return (InternalPointer->second->node);
-};
+}
+;
 
 /** PointCloud implementation of GetTerminalPoint.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 TesselPoint * Tesselation::GetTerminalPoint() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   PointMap::const_iterator Runner = PointsOnBoundary.end();
   Runner--;
   return (Runner->second->node);
-};
+}
+;
 
 /** PointCloud implementation of GoToNext.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 void Tesselation::GoToNext() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   if (InternalPointer != PointsOnBoundary.end())
     InternalPointer++;
-};
+}
+;
 
 /** PointCloud implementation of GoToPrevious.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 void Tesselation::GoToPrevious() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   if (InternalPointer != PointsOnBoundary.begin())
     InternalPointer--;
-};
+}
+;
 
 /** PointCloud implementation of GoToFirst.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 void Tesselation::GoToFirst() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   InternalPointer = PointsOnBoundary.begin();
-};
+}
+;
 
 /** PointCloud implementation of GoToLast.
@@ -1145,27 +1258,29 @@
 void Tesselation::GoToLast() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   InternalPointer = PointsOnBoundary.end();
   InternalPointer--;
-};
+}
+;
 
 /** PointCloud implementation of IsEmpty.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 bool Tesselation::IsEmpty() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   return (PointsOnBoundary.empty());
-};
+}
+;
 
 /** PointCloud implementation of IsLast.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 bool Tesselation::IsEnd() const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   return (InternalPointer == PointsOnBoundary.end());
-};
-
+}
+;
 
 /** Gueses first starting triangle of the convex envelope.
@@ -1176,5 +1291,5 @@
 void Tesselation::GuessStartingTriangle()
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // 4b. create a starting triangle
   // 4b1. create all distances
@@ -1186,24 +1301,21 @@
 
   // with A chosen, take each pair B,C and sort
-  if (A != PointsOnBoundary.end())
-    {
-      B = A;
-      B++;
-      for (; B != PointsOnBoundary.end(); B++)
-        {
-          C = B;
-          C++;
-          for (; C != PointsOnBoundary.end(); C++)
-            {
-              tmp = A->second->node->node->DistanceSquared(B->second->node->node);
-              distance = tmp * tmp;
-              tmp = A->second->node->node->DistanceSquared(C->second->node->node);
-              distance += tmp * tmp;
-              tmp = B->second->node->node->DistanceSquared(C->second->node->node);
-              distance += tmp * tmp;
-              DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
-            }
-        }
-    }
+  if (A != PointsOnBoundary.end()) {
+    B = A;
+    B++;
+    for (; B != PointsOnBoundary.end(); B++) {
+      C = B;
+      C++;
+      for (; C != PointsOnBoundary.end(); C++) {
+        tmp = A->second->node->node->DistanceSquared(*B->second->node->node);
+        distance = tmp * tmp;
+        tmp = A->second->node->node->DistanceSquared(*C->second->node->node);
+        distance += tmp * tmp;
+        tmp = B->second->node->node->DistanceSquared(*C->second->node->node);
+        distance += tmp * tmp;
+        DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
+      }
+    }
+  }
   //    // listing distances
   //    Log() << Verbose(1) << "Listing DistanceMMap:";
@@ -1215,113 +1327,81 @@
   // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
   DistanceMultiMap::iterator baseline = DistanceMMap.begin();
-  for (; baseline != DistanceMMap.end(); baseline++)
-    {
-      // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
-      // 2. next, we have to check whether all points reside on only one side of the triangle
-      // 3. construct plane vector
-      PlaneVector.MakeNormalVector(A->second->node->node,
-          baseline->second.first->second->node->node,
-          baseline->second.second->second->node->node);
-      Log() << Verbose(2) << "Plane vector of candidate triangle is " << PlaneVector << endl;
-      // 4. loop over all points
-      double sign = 0.;
-      PointMap::iterator checker = PointsOnBoundary.begin();
-      for (; checker != PointsOnBoundary.end(); checker++)
-        {
-          // (neglecting A,B,C)
-          if ((checker == A) || (checker == baseline->second.first) || (checker
-              == baseline->second.second))
-            continue;
-          // 4a. project onto plane vector
-          TrialVector.CopyVector(checker->second->node->node);
-          TrialVector.SubtractVector(A->second->node->node);
-          distance = TrialVector.ScalarProduct(&PlaneVector);
-          if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
-            continue;
-          Log() << Verbose(2) << "Projection of " << checker->second->node->Name << " yields distance of " << distance << "." << endl;
-          tmp = distance / fabs(distance);
-          // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
-          if ((sign != 0) && (tmp != sign))
-            {
-              // 4c. If so, break 4. loop and continue with next candidate in 1. loop
-              Log() << Verbose(2) << "Current candidates: "
-                  << A->second->node->Name << ","
-                  << baseline->second.first->second->node->Name << ","
-                  << baseline->second.second->second->node->Name << " leaves "
-                  << checker->second->node->Name << " outside the convex hull."
-                  << endl;
-              break;
-            }
-          else
-            { // note the sign for later
-              Log() << Verbose(2) << "Current candidates: "
-                  << A->second->node->Name << ","
-                  << baseline->second.first->second->node->Name << ","
-                  << baseline->second.second->second->node->Name << " leave "
-                  << checker->second->node->Name << " inside the convex hull."
-                  << endl;
-              sign = tmp;
-            }
-          // 4d. Check whether the point is inside the triangle (check distance to each node
-          tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
-          int innerpoint = 0;
-          if ((tmp < A->second->node->node->DistanceSquared(
-              baseline->second.first->second->node->node)) && (tmp
-              < A->second->node->node->DistanceSquared(
-                  baseline->second.second->second->node->node)))
-            innerpoint++;
-          tmp = checker->second->node->node->DistanceSquared(
-              baseline->second.first->second->node->node);
-          if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
-              A->second->node->node)) && (tmp
-              < baseline->second.first->second->node->node->DistanceSquared(
-                  baseline->second.second->second->node->node)))
-            innerpoint++;
-          tmp = checker->second->node->node->DistanceSquared(
-              baseline->second.second->second->node->node);
-          if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
-              baseline->second.first->second->node->node)) && (tmp
-              < baseline->second.second->second->node->node->DistanceSquared(
-                  A->second->node->node)))
-            innerpoint++;
-          // 4e. If so, break 4. loop and continue with next candidate in 1. loop
-          if (innerpoint == 3)
-            break;
-        }
-      // 5. come this far, all on same side? Then break 1. loop and construct triangle
-      if (checker == PointsOnBoundary.end())
-        {
-          Log() << Verbose(2) << "Looks like we have a candidate!" << endl;
-          break;
-        }
-    }
-  if (baseline != DistanceMMap.end())
-    {
-      BPS[0] = baseline->second.first->second;
-      BPS[1] = baseline->second.second->second;
-      BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
-      BPS[0] = A->second;
-      BPS[1] = baseline->second.second->second;
-      BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
-      BPS[0] = baseline->second.first->second;
-      BPS[1] = A->second;
-      BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
-
-      // 4b3. insert created triangle
-      BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
-      TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
-      TrianglesOnBoundaryCount++;
-      for (int i = 0; i < NDIM; i++)
-        {
-          LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
-          LinesOnBoundaryCount++;
-        }
-
-      Log() << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
-    }
-  else
-    {
-      eLog() << Verbose(0) << "No starting triangle found." << endl;
-    }
+  for (; baseline != DistanceMMap.end(); baseline++) {
+    // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
+    // 2. next, we have to check whether all points reside on only one side of the triangle
+    // 3. construct plane vector
+    PlaneVector = Plane(*A->second->node->node,
+                        *baseline->second.first->second->node->node,
+                        *baseline->second.second->second->node->node).getNormal();
+    DoLog(2) && (Log() << Verbose(2) << "Plane vector of candidate triangle is " << PlaneVector << endl);
+    // 4. loop over all points
+    double sign = 0.;
+    PointMap::iterator checker = PointsOnBoundary.begin();
+    for (; checker != PointsOnBoundary.end(); checker++) {
+      // (neglecting A,B,C)
+      if ((checker == A) || (checker == baseline->second.first) || (checker == baseline->second.second))
+        continue;
+      // 4a. project onto plane vector
+      TrialVector = (*checker->second->node->node);
+      TrialVector.SubtractVector(*A->second->node->node);
+      distance = TrialVector.ScalarProduct(PlaneVector);
+      if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
+        continue;
+      DoLog(2) && (Log() << Verbose(2) << "Projection of " << checker->second->node->Name << " yields distance of " << distance << "." << endl);
+      tmp = distance / fabs(distance);
+      // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
+      if ((sign != 0) && (tmp != sign)) {
+        // 4c. If so, break 4. loop and continue with next candidate in 1. loop
+        DoLog(2) && (Log() << Verbose(2) << "Current candidates: " << A->second->node->Name << "," << baseline->second.first->second->node->Name << "," << baseline->second.second->second->node->Name << " leaves " << checker->second->node->Name << " outside the convex hull." << endl);
+        break;
+      } else { // note the sign for later
+        DoLog(2) && (Log() << Verbose(2) << "Current candidates: " << A->second->node->Name << "," << baseline->second.first->second->node->Name << "," << baseline->second.second->second->node->Name << " leave " << checker->second->node->Name << " inside the convex hull." << endl);
+        sign = tmp;
+      }
+      // 4d. Check whether the point is inside the triangle (check distance to each node
+      tmp = checker->second->node->node->DistanceSquared(*A->second->node->node);
+      int innerpoint = 0;
+      if ((tmp < A->second->node->node->DistanceSquared(*baseline->second.first->second->node->node)) && (tmp < A->second->node->node->DistanceSquared(*baseline->second.second->second->node->node)))
+        innerpoint++;
+      tmp = checker->second->node->node->DistanceSquared(*baseline->second.first->second->node->node);
+      if ((tmp < baseline->second.first->second->node->node->DistanceSquared(*A->second->node->node)) && (tmp < baseline->second.first->second->node->node->DistanceSquared(*baseline->second.second->second->node->node)))
+        innerpoint++;
+      tmp = checker->second->node->node->DistanceSquared(*baseline->second.second->second->node->node);
+      if ((tmp < baseline->second.second->second->node->node->DistanceSquared(*baseline->second.first->second->node->node)) && (tmp < baseline->second.second->second->node->node->DistanceSquared(*A->second->node->node)))
+        innerpoint++;
+      // 4e. If so, break 4. loop and continue with next candidate in 1. loop
+      if (innerpoint == 3)
+        break;
+    }
+    // 5. come this far, all on same side? Then break 1. loop and construct triangle
+    if (checker == PointsOnBoundary.end()) {
+      DoLog(2) && (Log() << Verbose(2) << "Looks like we have a candidate!" << endl);
+      break;
+    }
+  }
+  if (baseline != DistanceMMap.end()) {
+    BPS[0] = baseline->second.first->second;
+    BPS[1] = baseline->second.second->second;
+    BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
+    BPS[0] = A->second;
+    BPS[1] = baseline->second.second->second;
+    BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
+    BPS[0] = baseline->second.first->second;
+    BPS[1] = A->second;
+    BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
+
+    // 4b3. insert created triangle
+    BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
+    TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
+    TrianglesOnBoundaryCount++;
+    for (int i = 0; i < NDIM; i++) {
+      LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
+      LinesOnBoundaryCount++;
+    }
+
+    DoLog(1) && (Log() << Verbose(1) << "Starting triangle is " << *BTS << "." << endl);
+  } else {
+    DoeLog(0) && (eLog() << Verbose(0) << "No starting triangle found." << endl);
+  }
 }
 ;
@@ -1342,5 +1422,5 @@
 void Tesselation::TesselateOnBoundary(const PointCloud * const cloud)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   bool flag;
   PointMap::iterator winner;
@@ -1361,41 +1441,37 @@
         // get peak point with respect to this base line's only triangle
         BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
-        Log() << Verbose(0) << "Current baseline is between " << *(baseline->second) << "." << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Current baseline is between " << *(baseline->second) << "." << endl);
         for (int i = 0; i < 3; i++)
           if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
             peak = BTS->endpoints[i];
-        Log() << Verbose(1) << " and has peak " << *peak << "." << endl;
+        DoLog(1) && (Log() << Verbose(1) << " and has peak " << *peak << "." << endl);
 
         // prepare some auxiliary vectors
         Vector BaseLineCenter, BaseLine;
-        BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
-        BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
-        BaseLineCenter.Scale(1. / 2.); // points now to center of base line
-        BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
-        BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
+        BaseLineCenter = 0.5 * ((*baseline->second->endpoints[0]->node->node) +
+                                (*baseline->second->endpoints[1]->node->node));
+        BaseLine = (*baseline->second->endpoints[0]->node->node) - (*baseline->second->endpoints[1]->node->node);
 
         // offset to center of triangle
         CenterVector.Zero();
         for (int i = 0; i < 3; i++)
-          CenterVector.AddVector(BTS->endpoints[i]->node->node);
+          CenterVector += (*BTS->endpoints[i]->node->node);
         CenterVector.Scale(1. / 3.);
-        Log() << Verbose(2) << "CenterVector of base triangle is " << CenterVector << endl;
+        DoLog(2) && (Log() << Verbose(2) << "CenterVector of base triangle is " << CenterVector << endl);
 
         // normal vector of triangle
-        NormalVector.CopyVector(Center);
-        NormalVector.SubtractVector(&CenterVector);
+        NormalVector = (*Center) - CenterVector;
         BTS->GetNormalVector(NormalVector);
-        NormalVector.CopyVector(&BTS->NormalVector);
-        Log() << Verbose(2) << "NormalVector of base triangle is " << NormalVector << endl;
+        NormalVector = BTS->NormalVector;
+        DoLog(2) && (Log() << Verbose(2) << "NormalVector of base triangle is " << NormalVector << endl);
 
         // vector in propagation direction (out of triangle)
         // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
-        PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
-        TempVector.CopyVector(&CenterVector);
-        TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
+        PropagationVector = Plane(BaseLine, NormalVector,0).getNormal();
+        TempVector = CenterVector - (*baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
         //Log() << Verbose(0) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
-        if (PropagationVector.ScalarProduct(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
+        if (PropagationVector.ScalarProduct(TempVector) > 0) // make sure normal propagation vector points outward from baseline
           PropagationVector.Scale(-1.);
-        Log() << Verbose(2) << "PropagationVector of base triangle is " << PropagationVector << endl;
+        DoLog(2) && (Log() << Verbose(2) << "PropagationVector of base triangle is " << PropagationVector << endl);
         winner = PointsOnBoundary.end();
 
@@ -1403,17 +1479,16 @@
         for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
           if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
-            Log() << Verbose(1) << "Target point is " << *(target->second) << ":" << endl;
+            DoLog(1) && (Log() << Verbose(1) << "Target point is " << *(target->second) << ":" << endl);
 
             // first check direction, so that triangles don't intersect
-            VirtualNormalVector.CopyVector(target->second->node->node);
-            VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
-            VirtualNormalVector.ProjectOntoPlane(&NormalVector);
-            TempAngle = VirtualNormalVector.Angle(&PropagationVector);
-            Log() << Verbose(2) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
-            if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
-              Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
+            VirtualNormalVector = (*target->second->node->node) - BaseLineCenter;
+            VirtualNormalVector.ProjectOntoPlane(NormalVector);
+            TempAngle = VirtualNormalVector.Angle(PropagationVector);
+            DoLog(2) && (Log() << Verbose(2) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl);
+            if (TempAngle > (M_PI / 2.)) { // no bends bigger than Pi/2 (90 degrees)
+              DoLog(2) && (Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl);
               continue;
             } else
-              Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
+              DoLog(2) && (Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl);
 
             // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
@@ -1421,9 +1496,9 @@
             LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
             if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->triangles.size() == 2))) {
-              Log() << Verbose(2) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->triangles.size() << " triangles." << endl;
+              DoLog(2) && (Log() << Verbose(2) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->triangles.size() << " triangles." << endl);
               continue;
             }
             if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->triangles.size() == 2))) {
-              Log() << Verbose(2) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->triangles.size() << " triangles." << endl;
+              DoLog(2) && (Log() << Verbose(2) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->triangles.size() << " triangles." << endl);
               continue;
             }
@@ -1431,16 +1506,14 @@
             // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
             if ((((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (GetCommonEndpoint(LineChecker[0]->second, LineChecker[1]->second) == peak)))) {
-              Log() << Verbose(4) << "Current target is peak!" << endl;
+              DoLog(4) && (Log() << Verbose(4) << "Current target is peak!" << endl);
               continue;
             }
 
             // check for linear dependence
-            TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
-            TempVector.SubtractVector(target->second->node->node);
-            helper.CopyVector(baseline->second->endpoints[1]->node->node);
-            helper.SubtractVector(target->second->node->node);
-            helper.ProjectOntoPlane(&TempVector);
+            TempVector = (*baseline->second->endpoints[0]->node->node) - (*target->second->node->node);
+            helper = (*baseline->second->endpoints[1]->node->node) - (*target->second->node->node);
+            helper.ProjectOntoPlane(TempVector);
             if (fabs(helper.NormSquared()) < MYEPSILON) {
-              Log() << Verbose(2) << "Chosen set of vectors is linear dependent." << endl;
+              DoLog(2) && (Log() << Verbose(2) << "Chosen set of vectors is linear dependent." << endl);
               continue;
             }
@@ -1448,42 +1521,40 @@
             // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
             flag = true;
-            VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
-            TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
-            TempVector.AddVector(baseline->second->endpoints[1]->node->node);
-            TempVector.AddVector(target->second->node->node);
-            TempVector.Scale(1./3.);
-            TempVector.SubtractVector(Center);
+            VirtualNormalVector = Plane(*(baseline->second->endpoints[0]->node->node),
+                                        *(baseline->second->endpoints[1]->node->node),
+                                        *(target->second->node->node)).getNormal();
+            TempVector = (1./3.) * ((*baseline->second->endpoints[0]->node->node) +
+                                    (*baseline->second->endpoints[1]->node->node) +
+                                    (*target->second->node->node));
+            TempVector -= (*Center);
             // make it always point outward
-            if (VirtualNormalVector.ScalarProduct(&TempVector) < 0)
+            if (VirtualNormalVector.ScalarProduct(TempVector) < 0)
               VirtualNormalVector.Scale(-1.);
             // calculate angle
-            TempAngle = NormalVector.Angle(&VirtualNormalVector);
-            Log() << Verbose(2) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
+            TempAngle = NormalVector.Angle(VirtualNormalVector);
+            DoLog(2) && (Log() << Verbose(2) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl);
             if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
               SmallestAngle = TempAngle;
               winner = target;
-              Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
+              DoLog(2) && (Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl);
             } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
               // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
-              helper.CopyVector(target->second->node->node);
-              helper.SubtractVector(&BaseLineCenter);
-              helper.ProjectOntoPlane(&BaseLine);
+              helper = (*target->second->node->node) - BaseLineCenter;
+              helper.ProjectOntoPlane(BaseLine);
               // ...the one with the smaller angle is the better candidate
-              TempVector.CopyVector(target->second->node->node);
-              TempVector.SubtractVector(&BaseLineCenter);
-              TempVector.ProjectOntoPlane(&VirtualNormalVector);
-              TempAngle = TempVector.Angle(&helper);
-              TempVector.CopyVector(winner->second->node->node);
-              TempVector.SubtractVector(&BaseLineCenter);
-              TempVector.ProjectOntoPlane(&VirtualNormalVector);
-              if (TempAngle < TempVector.Angle(&helper)) {
-                TempAngle = NormalVector.Angle(&VirtualNormalVector);
+              TempVector = (*target->second->node->node) - BaseLineCenter;
+              TempVector.ProjectOntoPlane(VirtualNormalVector);
+              TempAngle = TempVector.Angle(helper);
+              TempVector = (*winner->second->node->node) - BaseLineCenter;
+              TempVector.ProjectOntoPlane(VirtualNormalVector);
+              if (TempAngle < TempVector.Angle(helper)) {
+                TempAngle = NormalVector.Angle(VirtualNormalVector);
                 SmallestAngle = TempAngle;
                 winner = target;
-                Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
+                DoLog(2) && (Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl);
               } else
-                Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
+                DoLog(2) && (Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl);
             } else
-              Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
+              DoLog(2) && (Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl);
           }
         } // end of loop over all boundary points
@@ -1491,5 +1562,5 @@
         // 5b. The point of the above whose triangle has the greatest angle with the triangle the current line belongs to (it only belongs to one, remember!): New triangle
         if (winner != PointsOnBoundary.end()) {
-          Log() << Verbose(0) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl);
           // create the lins of not yet present
           BLS[0] = baseline->second;
@@ -1515,21 +1586,22 @@
           BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
           BTS->GetCenter(&helper);
-          helper.SubtractVector(Center);
-          helper.Scale(-1);
+          helper -= (*Center);
+          helper *= -1;
           BTS->GetNormalVector(helper);
           TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
           TrianglesOnBoundaryCount++;
         } else {
-          eLog() << Verbose(2) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
+          DoeLog(2) && (eLog() << Verbose(2) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl);
         }
 
         // 5d. If the set of lines is not yet empty, go to 5. and continue
       } else
-        Log() << Verbose(0) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->triangles.size() << "." << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->triangles.size() << "." << endl);
   } while (flag);
 
   // exit
-  delete(Center);
-};
+  delete (Center);
+}
+;
 
 /** Inserts all points outside of the tesselated surface into it by adding new triangles.
@@ -1541,5 +1613,5 @@
 bool Tesselation::InsertStraddlingPoints(const PointCloud *cloud, const LinkedCell *LC)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   Vector Intersection, Normal;
   TesselPoint *Walker = NULL;
@@ -1551,68 +1623,68 @@
   cloud->GoToFirst();
   BoundaryPoints = new LinkedCell(this, 5.);
-  while (!cloud->IsEnd()) {  // we only have to go once through all points, as boundary can become only bigger
+  while (!cloud->IsEnd()) { // we only have to go once through all points, as boundary can become only bigger
     if (AddFlag) {
-      delete(BoundaryPoints);
+      delete (BoundaryPoints);
       BoundaryPoints = new LinkedCell(this, 5.);
       AddFlag = false;
     }
     Walker = cloud->GetPoint();
-    Log() << Verbose(0) << "Current point is " << *Walker << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Current point is " << *Walker << "." << endl);
     // get the next triangle
     triangles = FindClosestTrianglesToVector(Walker->node, BoundaryPoints);
     BTS = triangles->front();
     if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
-      Log() << Verbose(0) << "No triangles found, probably a tesselation point itself." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "No triangles found, probably a tesselation point itself." << endl);
       cloud->GoToNext();
       continue;
     } else {
     }
-    Log() << Verbose(0) << "Closest triangle is " << *BTS << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Closest triangle is " << *BTS << "." << endl);
     // get the intersection point
     if (BTS->GetIntersectionInsideTriangle(Center, Walker->node, &Intersection)) {
-      Log() << Verbose(0) << "We have an intersection at " << Intersection << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "We have an intersection at " << Intersection << "." << endl);
       // we have the intersection, check whether in- or outside of boundary
-      if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
+      if ((Center->DistanceSquared(*Walker->node) - Center->DistanceSquared(Intersection)) < -MYEPSILON) {
         // inside, next!
-        Log() << Verbose(0) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
+        DoLog(0) && (Log() << Verbose(0) << *Walker << " is inside wrt triangle " << *BTS << "." << endl);
       } else {
         // outside!
-        Log() << Verbose(0) << *Walker << " is outside wrt triangle " << *BTS << "." << endl;
+        DoLog(0) && (Log() << Verbose(0) << *Walker << " is outside wrt triangle " << *BTS << "." << endl);
         class BoundaryLineSet *OldLines[3], *NewLines[3];
         class BoundaryPointSet *OldPoints[3], *NewPoint;
         // store the three old lines and old points
-        for (int i=0;i<3;i++) {
+        for (int i = 0; i < 3; i++) {
           OldLines[i] = BTS->lines[i];
           OldPoints[i] = BTS->endpoints[i];
         }
-        Normal.CopyVector(&BTS->NormalVector);
+        Normal = BTS->NormalVector;
         // add Walker to boundary points
-        Log() << Verbose(0) << "Adding " << *Walker << " to BoundaryPoints." << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Adding " << *Walker << " to BoundaryPoints." << endl);
         AddFlag = true;
-        if (AddBoundaryPoint(Walker,0))
+        if (AddBoundaryPoint(Walker, 0))
           NewPoint = BPS[0];
         else
           continue;
         // remove triangle
-        Log() << Verbose(0) << "Erasing triangle " << *BTS << "." << endl;
+        DoLog(0) && (Log() << Verbose(0) << "Erasing triangle " << *BTS << "." << endl);
         TrianglesOnBoundary.erase(BTS->Nr);
-        delete(BTS);
+        delete (BTS);
         // create three new boundary lines
-        for (int i=0;i<3;i++) {
+        for (int i = 0; i < 3; i++) {
           BPS[0] = NewPoint;
           BPS[1] = OldPoints[i];
           NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
-          Log() << Verbose(1) << "Creating new line " << *NewLines[i] << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "Creating new line " << *NewLines[i] << "." << endl);
           LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
           LinesOnBoundaryCount++;
         }
         // create three new triangle with new point
-        for (int i=0;i<3;i++) { // find all baselines
+        for (int i = 0; i < 3; i++) { // find all baselines
           BLS[0] = OldLines[i];
           int n = 1;
-          for (int j=0;j<3;j++) {
+          for (int j = 0; j < 3; j++) {
             if (NewLines[j]->IsConnectedTo(BLS[0])) {
-              if (n>2) {
-                eLog() << Verbose(2) << BLS[0] << " connects to all of the new lines?!" << endl;
+              if (n > 2) {
+                DoeLog(2) && (eLog() << Verbose(2) << BLS[0] << " connects to all of the new lines?!" << endl);
                 return false;
               } else
@@ -1625,5 +1697,5 @@
           BTS->GetNormalVector(Normal);
           Normal.Scale(-1.);
-          Log() << Verbose(0) << "Created new triangle " << *BTS << "." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "Created new triangle " << *BTS << "." << endl);
           TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
           TrianglesOnBoundaryCount++;
@@ -1631,5 +1703,5 @@
       }
     } else { // something is wrong with FindClosestTriangleToPoint!
-      eLog() << Verbose(1) << "The closest triangle did not produce an intersection!" << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "The closest triangle did not produce an intersection!" << endl);
       return false;
     }
@@ -1638,7 +1710,8 @@
 
   // exit
-  delete(Center);
+  delete (Center);
   return true;
-};
+}
+;
 
 /** Adds a point to the tesselation::PointsOnBoundary list.
@@ -1649,5 +1722,5 @@
 bool Tesselation::AddBoundaryPoint(TesselPoint * Walker, const int n)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   PointTestPair InsertUnique;
   BPS[n] = new class BoundaryPointSet(Walker);
@@ -1657,5 +1730,5 @@
     return true;
   } else {
-    delete(BPS[n]);
+    delete (BPS[n]);
     BPS[n] = InsertUnique.first->second;
     return false;
@@ -1671,5 +1744,5 @@
 void Tesselation::AddTesselationPoint(TesselPoint* Candidate, const int n)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   PointTestPair InsertUnique;
   TPS[n] = new class BoundaryPointSet(Candidate);
@@ -1679,5 +1752,5 @@
   } else {
     delete TPS[n];
-    Log() << Verbose(0) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl);
     TPS[n] = (InsertUnique.first)->second;
   }
@@ -1692,5 +1765,5 @@
 void Tesselation::SetTesselationPoint(TesselPoint* Candidate, const int n) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidate->nr);
   if (FindPoint != PointsOnBoundary.end())
@@ -1698,44 +1771,47 @@
   else
     TPS[n] = NULL;
-};
+}
+;
 
 /** Function tries to add line from current Points in BPS to BoundaryLineSet.
  * If successful it raises the line count and inserts the new line into the BLS,
  * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
+ * @param *OptCenter desired OptCenter if there are more than one candidate line
+ * @param *candidate third point of the triangle to be, for checking between multiple open line candidates
  * @param *a first endpoint
  * @param *b second endpoint
  * @param n index of Tesselation::BLS giving the line with both endpoints
  */
-void Tesselation::AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n) {
+void Tesselation::AddTesselationLine(const Vector * const OptCenter, const BoundaryPointSet * const candidate, class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
+{
   bool insertNewLine = true;
-
   LineMap::iterator FindLine = a->lines.find(b->node->nr);
+  BoundaryLineSet *WinningLine = NULL;
   if (FindLine != a->lines.end()) {
-    Log() << Verbose(1) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
-
-    pair<LineMap::iterator,LineMap::iterator> FindPair;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl);
+
+    pair<LineMap::iterator, LineMap::iterator> FindPair;
     FindPair = a->lines.equal_range(b->node->nr);
 
-    for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
+    for (FindLine = FindPair.first; (FindLine != FindPair.second) && (insertNewLine); FindLine++) {
+      DoLog(1) && (Log() << Verbose(1) << "INFO: Checking line " << *(FindLine->second) << " ..." << endl);
       // If there is a line with less than two attached triangles, we don't need a new line.
-      if (FindLine->second->triangles.size() < 2) {
-        insertNewLine = false;
-        Log() << Verbose(0) << "Using existing line " << *FindLine->second << endl;
-
-        BPS[0] = FindLine->second->endpoints[0];
-        BPS[1] = FindLine->second->endpoints[1];
-        BLS[n] = FindLine->second;
-
-        // remove existing line from OpenLines
-        CandidateMap::iterator CandidateLine = OpenLines.find(BLS[n]);
-        if (CandidateLine != OpenLines.end()) {
-          Log() << Verbose(1) << " Removing line from OpenLines." << endl;
-          delete(CandidateLine->second);
-          OpenLines.erase(CandidateLine);
-        } else {
-          eLog() << Verbose(1) << "Line exists and is attached to less than two triangles, but not in OpenLines!" << endl;
+      if (FindLine->second->triangles.size() == 1) {
+        CandidateMap::iterator Finder = OpenLines.find(FindLine->second);
+        if (!Finder->second->pointlist.empty())
+          DoLog(1) && (Log() << Verbose(1) << "INFO: line " << *(FindLine->second) << " is open with candidate " << **(Finder->second->pointlist.begin()) << "." << endl);
+        else
+          DoLog(1) && (Log() << Verbose(1) << "INFO: line " << *(FindLine->second) << " is open with no candidate." << endl);
+        // get open line
+        for (TesselPointList::const_iterator CandidateChecker = Finder->second->pointlist.begin(); CandidateChecker != Finder->second->pointlist.end(); ++CandidateChecker) {
+          if ((*(CandidateChecker) == candidate->node) && (OptCenter == NULL || OptCenter->DistanceSquared(Finder->second->OptCenter) < MYEPSILON )) { // stop searching if candidate matches
+            DoLog(1) && (Log() << Verbose(1) << "ACCEPT: Candidate " << *(*CandidateChecker) << " has the right center " << Finder->second->OptCenter << "." << endl);
+            insertNewLine = false;
+            WinningLine = FindLine->second;
+            break;
+          } else {
+            DoLog(1) && (Log() << Verbose(1) << "REJECT: Candidate " << *(*CandidateChecker) << "'s center " << Finder->second->OptCenter << " does not match desired on " << *OptCenter << "." << endl);
+          }
         }
-
-        break;
       }
     }
@@ -1743,5 +1819,7 @@
 
   if (insertNewLine) {
-    AlwaysAddTesselationTriangleLine(a, b, n);
+    AddNewTesselationTriangleLine(a, b, n);
+  } else {
+    AddExistingTesselationTriangleLine(WinningLine, n);
   }
 }
@@ -1756,11 +1834,11 @@
  * @param n index of Tesselation::BLS giving the line with both endpoints
  */
-void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
-{
-	Info FunctionInfo(__func__);
-  Log() << Verbose(0) << "Adding open line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
+void Tesselation::AddNewTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
+{
+  Info FunctionInfo(__func__);
+  DoLog(0) && (Log() << Verbose(0) << "Adding open line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl);
   BPS[0] = a;
   BPS[1] = b;
-  BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);  // this also adds the line to the local maps
+  BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
   // add line to global map
   LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
@@ -1769,6 +1847,33 @@
   // also add to open lines
   CandidateForTesselation *CFT = new CandidateForTesselation(BLS[n]);
-  OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (BLS[n], CFT));
-};
+  OpenLines.insert(pair<BoundaryLineSet *, CandidateForTesselation *> (BLS[n], CFT));
+}
+;
+
+/** Uses an existing line for a new triangle.
+ * Sets Tesselation::BLS[\a n] and removes the lines from Tesselation::OpenLines.
+ * \param *FindLine the line to add
+ * \param n index of the line to set in Tesselation::BLS
+ */
+void Tesselation::AddExistingTesselationTriangleLine(class BoundaryLineSet *Line, int n)
+{
+  Info FunctionInfo(__func__);
+  DoLog(0) && (Log() << Verbose(0) << "Using existing line " << *Line << endl);
+
+  // set endpoints and line
+  BPS[0] = Line->endpoints[0];
+  BPS[1] = Line->endpoints[1];
+  BLS[n] = Line;
+  // remove existing line from OpenLines
+  CandidateMap::iterator CandidateLine = OpenLines.find(BLS[n]);
+  if (CandidateLine != OpenLines.end()) {
+    DoLog(1) && (Log() << Verbose(1) << " Removing line from OpenLines." << endl);
+    delete (CandidateLine->second);
+    OpenLines.erase(CandidateLine);
+  } else {
+    DoeLog(1) && (eLog() << Verbose(1) << "Line exists and is attached to less than two triangles, but not in OpenLines!" << endl);
+  }
+}
+;
 
 /** Function adds triangle to global list.
@@ -1777,6 +1882,6 @@
 void Tesselation::AddTesselationTriangle()
 {
-	Info FunctionInfo(__func__);
-  Log() << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
+  Info FunctionInfo(__func__);
+  DoLog(1) && (Log() << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl);
 
   // add triangle to global map
@@ -1788,5 +1893,6 @@
 
   // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
-};
+}
+;
 
 /** Function adds triangle to global list.
@@ -1796,6 +1902,6 @@
 void Tesselation::AddTesselationTriangle(const int nr)
 {
-	Info FunctionInfo(__func__);
-  Log() << Verbose(0) << "Adding triangle to global TrianglesOnBoundary map." << endl;
+  Info FunctionInfo(__func__);
+  DoLog(0) && (Log() << Verbose(0) << "Adding triangle to global TrianglesOnBoundary map." << endl);
 
   // add triangle to global map
@@ -1806,5 +1912,6 @@
 
   // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
-};
+}
+;
 
 /** Removes a triangle from the tesselation.
@@ -1815,36 +1922,37 @@
 void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   if (triangle == NULL)
     return;
   for (int i = 0; i < 3; i++) {
     if (triangle->lines[i] != NULL) {
-      Log() << Verbose(0) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl);
       triangle->lines[i]->triangles.erase(triangle->Nr);
       if (triangle->lines[i]->triangles.empty()) {
-          Log() << Verbose(0) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
-          RemoveTesselationLine(triangle->lines[i]);
+        DoLog(0) && (Log() << Verbose(0) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl);
+        RemoveTesselationLine(triangle->lines[i]);
       } else {
-        Log() << Verbose(0) << *triangle->lines[i] << " is still attached to another triangle: ";
-        OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (triangle->lines[i], NULL));
-        for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
-          Log() << Verbose(0) << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
-        Log() << Verbose(0) << endl;
-//        for (int j=0;j<2;j++) {
-//          Log() << Verbose(0) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
-//          for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
-//            Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
-//          Log() << Verbose(0) << endl;
-//        }
+        DoLog(0) && (Log() << Verbose(0) << *triangle->lines[i] << " is still attached to another triangle: ");
+        OpenLines.insert(pair<BoundaryLineSet *, CandidateForTesselation *> (triangle->lines[i], NULL));
+        for (TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
+          DoLog(0) && (Log() << Verbose(0) << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t");
+        DoLog(0) && (Log() << Verbose(0) << endl);
+        //        for (int j=0;j<2;j++) {
+        //          Log() << Verbose(0) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
+        //          for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
+        //            Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
+        //          Log() << Verbose(0) << endl;
+        //        }
       }
-      triangle->lines[i] = NULL;  // free'd or not: disconnect
+      triangle->lines[i] = NULL; // free'd or not: disconnect
     } else
-      eLog() << Verbose(1) << "This line " << i << " has already been free'd." << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "This line " << i << " has already been free'd." << endl);
   }
 
   if (TrianglesOnBoundary.erase(triangle->Nr))
-    Log() << Verbose(0) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
-  delete(triangle);
-};
+    DoLog(0) && (Log() << Verbose(0) << "Removing triangle Nr. " << triangle->Nr << "." << endl);
+  delete (triangle);
+}
+;
 
 /** Removes a line from the tesselation.
@@ -1854,5 +1962,5 @@
 void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   int Numbers[2];
 
@@ -1875,5 +1983,5 @@
         for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
           if ((*Runner).second == line) {
-            Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
+            DoLog(0) && (Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl);
             line->endpoints[i]->lines.erase(Runner);
             break;
@@ -1881,26 +1989,27 @@
       } else { // there's just a single line left
         if (line->endpoints[i]->lines.erase(line->Nr))
-          Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl);
       }
       if (line->endpoints[i]->lines.empty()) {
-        Log() << Verbose(0) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
+        DoLog(0) && (Log() << Verbose(0) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl);
         RemoveTesselationPoint(line->endpoints[i]);
       } else {
-        Log() << Verbose(0) << *line->endpoints[i] << " has still lines it's attached to: ";
-        for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
-          Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
-        Log() << Verbose(0) << endl;
+        DoLog(0) && (Log() << Verbose(0) << *line->endpoints[i] << " has still lines it's attached to: ");
+        for (LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
+          DoLog(0) && (Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t");
+        DoLog(0) && (Log() << Verbose(0) << endl);
       }
-      line->endpoints[i] = NULL;  // free'd or not: disconnect
+      line->endpoints[i] = NULL; // free'd or not: disconnect
     } else
-      eLog() << Verbose(1) << "Endpoint " << i << " has already been free'd." << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "Endpoint " << i << " has already been free'd." << endl);
   }
   if (!line->triangles.empty())
-    eLog() << Verbose(2) << "Memory Leak! I " << *line << " am still connected to some triangles." << endl;
+    DoeLog(2) && (eLog() << Verbose(2) << "Memory Leak! I " << *line << " am still connected to some triangles." << endl);
 
   if (LinesOnBoundary.erase(line->Nr))
-    Log() << Verbose(0) << "Removing line Nr. " << line->Nr << "." << endl;
-  delete(line);
-};
+    DoLog(0) && (Log() << Verbose(0) << "Removing line Nr. " << line->Nr << "." << endl);
+  delete (line);
+}
+;
 
 /** Removes a point from the tesselation.
@@ -1911,11 +2020,57 @@
 void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   if (point == NULL)
     return;
   if (PointsOnBoundary.erase(point->Nr))
-    Log() << Verbose(0) << "Removing point Nr. " << point->Nr << "." << endl;
-  delete(point);
-};
+    DoLog(0) && (Log() << Verbose(0) << "Removing point Nr. " << point->Nr << "." << endl);
+  delete (point);
+}
+;
+
+/** Checks validity of a given sphere of a candidate line.
+ * \sa CandidateForTesselation::CheckValidity(), which is more evolved.
+ * We check CandidateForTesselation::OtherOptCenter
+ * \param &CandidateLine contains other degenerated candidates which we have to subtract as well
+ * \param RADIUS radius of sphere
+ * \param *LC LinkedCell structure with other atoms
+ * \return true - candidate triangle is degenerated, false - candidate triangle is not degenerated
+ */
+bool Tesselation::CheckDegeneracy(CandidateForTesselation &CandidateLine, const double RADIUS, const LinkedCell *LC) const
+{
+  Info FunctionInfo(__func__);
+
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Checking whether sphere contains no others points ..." << endl);
+  bool flag = true;
+
+  DoLog(1) && (Log() << Verbose(1) << "Check by: draw sphere {" << CandidateLine.OtherOptCenter[0] << " " << CandidateLine.OtherOptCenter[1] << " " << CandidateLine.OtherOptCenter[2] << "} radius " << RADIUS << " resolution 30" << endl);
+  // get all points inside the sphere
+  TesselPointList *ListofPoints = LC->GetPointsInsideSphere(RADIUS, &CandidateLine.OtherOptCenter);
+
+  DoLog(1) && (Log() << Verbose(1) << "The following atoms are inside sphere at " << CandidateLine.OtherOptCenter << ":" << endl);
+  for (TesselPointList::const_iterator Runner = ListofPoints->begin(); Runner != ListofPoints->end(); ++Runner)
+    DoLog(1) && (Log() << Verbose(1) << "  " << *(*Runner) << " with distance " << (*Runner)->node->distance(CandidateLine.OtherOptCenter) << "." << endl);
+
+  // remove triangles's endpoints
+  for (int i = 0; i < 2; i++)
+    ListofPoints->remove(CandidateLine.BaseLine->endpoints[i]->node);
+
+  // remove other candidates
+  for (TesselPointList::const_iterator Runner = CandidateLine.pointlist.begin(); Runner != CandidateLine.pointlist.end(); ++Runner)
+    ListofPoints->remove(*Runner);
+
+  // check for other points
+  if (!ListofPoints->empty()) {
+    DoLog(1) && (Log() << Verbose(1) << "CheckDegeneracy: There are still " << ListofPoints->size() << " points inside the sphere." << endl);
+    flag = false;
+    DoLog(1) && (Log() << Verbose(1) << "External atoms inside of sphere at " << CandidateLine.OtherOptCenter << ":" << endl);
+    for (TesselPointList::const_iterator Runner = ListofPoints->begin(); Runner != ListofPoints->end(); ++Runner)
+      DoLog(1) && (Log() << Verbose(1) << "  " << *(*Runner) << " with distance " << (*Runner)->node->distance(CandidateLine.OtherOptCenter) << "." << endl);
+  }
+  delete (ListofPoints);
+
+  return flag;
+}
+;
 
 /** Checks whether the triangle consisting of the three points is already present.
@@ -1930,5 +2085,5 @@
 int Tesselation::CheckPresenceOfTriangle(TesselPoint *Candidates[3]) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   int adjacentTriangleCount = 0;
   class BoundaryPointSet *Points[3];
@@ -1952,5 +2107,5 @@
           for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
             TriangleMap *triangles = &FindLine->second->triangles;
-            Log() << Verbose(1) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
+            DoLog(1) && (Log() << Verbose(1) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl);
             for (TriangleMap::const_iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
               if (FindTriangle->second->IsPresentTupel(Points)) {
@@ -1958,5 +2113,5 @@
               }
             }
-            Log() << Verbose(1) << "end." << endl;
+            DoLog(1) && (Log() << Verbose(1) << "end." << endl);
           }
           // Only one of the triangle lines must be considered for the triangle count.
@@ -1968,7 +2123,8 @@
   }
 
-  Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl);
   return adjacentTriangleCount;
-};
+}
+;
 
 /** Checks whether the triangle consisting of the three points is already present.
@@ -1982,5 +2138,5 @@
 class BoundaryTriangleSet * Tesselation::GetPresentTriangle(TesselPoint *Candidates[3])
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   class BoundaryTriangleSet *triangle = NULL;
   class BoundaryPointSet *Points[3];
@@ -2020,6 +2176,6 @@
 
   return triangle;
-};
-
+}
+;
 
 /** Finds the starting triangle for FindNonConvexBorder().
@@ -2030,17 +2186,18 @@
  * \param RADIUS radius of virtual rolling sphere
  * \param *LC LinkedCell structure with neighbouring TesselPoint's
- */
-void Tesselation::FindStartingTriangle(const double RADIUS, const LinkedCell *LC)
-{
-	Info FunctionInfo(__func__);
+ * \return true - a starting triangle has been created, false - no valid triple of points found
+ */
+bool Tesselation::FindStartingTriangle(const double RADIUS, const LinkedCell *LC)
+{
+  Info FunctionInfo(__func__);
   int i = 0;
   TesselPoint* MaxPoint[NDIM];
   TesselPoint* Temporary;
   double maxCoordinate[NDIM];
-  BoundaryLineSet BaseLine;
+  BoundaryLineSet *BaseLine = NULL;
   Vector helper;
   Vector Chord;
   Vector SearchDirection;
-  Vector CircleCenter;  // center of the circle, i.e. of the band of sphere's centers
+  Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
   Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
   Vector SphereCenter;
@@ -2055,93 +2212,100 @@
 
   // 1. searching topmost point with respect to each axis
-  for (int i=0;i<NDIM;i++) { // each axis
-    LC->n[i] = LC->N[i]-1; // current axis is topmost cell
-    for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
-      for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
-        const LinkedNodes *List = LC->GetCurrentCell();
+  for (int i = 0; i < NDIM; i++) { // each axis
+    LC->n[i] = LC->N[i] - 1; // current axis is topmost cell
+    for (LC->n[(i + 1) % NDIM] = 0; LC->n[(i + 1) % NDIM] < LC->N[(i + 1) % NDIM]; LC->n[(i + 1) % NDIM]++)
+      for (LC->n[(i + 2) % NDIM] = 0; LC->n[(i + 2) % NDIM] < LC->N[(i + 2) % NDIM]; LC->n[(i + 2) % NDIM]++) {
+        const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
         //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
         if (List != NULL) {
-          for (LinkedNodes::const_iterator Runner = List->begin();Runner != List->end();Runner++) {
-            if ((*Runner)->node->x[i] > maxCoordinate[i]) {
-              Log() << Verbose(1) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
-              maxCoordinate[i] = (*Runner)->node->x[i];
+          for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+            if ((*Runner)->node->at(i) > maxCoordinate[i]) {
+              DoLog(1) && (Log() << Verbose(1) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl);
+              maxCoordinate[i] = (*Runner)->node->at(i);
               MaxPoint[i] = (*Runner);
             }
           }
         } else {
-          eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
+          DoeLog(1) && (eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl);
         }
       }
   }
 
-  Log() << Verbose(1) << "Found maximum coordinates: ";
-  for (int i=0;i<NDIM;i++)
-    Log() << Verbose(0) << i << ": " << *MaxPoint[i] << "\t";
-  Log() << Verbose(0) << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Found maximum coordinates: ");
+  for (int i = 0; i < NDIM; i++)
+    DoLog(0) && (Log() << Verbose(0) << i << ": " << *MaxPoint[i] << "\t");
+  DoLog(0) && (Log() << Verbose(0) << endl);
 
   BTS = NULL;
-  for (int k=0;k<NDIM;k++) {
+  for (int k = 0; k < NDIM; k++) {
     NormalVector.Zero();
-    NormalVector.x[k] = 1.;
-    BaseLine.endpoints[0] = new BoundaryPointSet(MaxPoint[k]);
-    Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
+    NormalVector[k] = 1.;
+    BaseLine = new BoundaryLineSet();
+    BaseLine->endpoints[0] = new BoundaryPointSet(MaxPoint[k]);
+    DoLog(0) && (Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine->endpoints[0]->node << "." << endl);
 
     double ShortestAngle;
     ShortestAngle = 999999.; // This will contain the angle, which will be always positive (when looking for second point), when looking for third point this will be the quadrant.
 
-    FindSecondPointForTesselation(BaseLine.endpoints[0]->node, NormalVector, Temporary, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
-    if (Temporary == NULL)  // have we found a second point?
+    Temporary = NULL;
+    FindSecondPointForTesselation(BaseLine->endpoints[0]->node, NormalVector, Temporary, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
+    if (Temporary == NULL) {
+      // have we found a second point?
+      delete BaseLine;
       continue;
-    BaseLine.endpoints[1] = new BoundaryPointSet(Temporary);
+    }
+    BaseLine->endpoints[1] = new BoundaryPointSet(Temporary);
 
     // construct center of circle
-    CircleCenter.CopyVector(BaseLine.endpoints[0]->node->node);
-    CircleCenter.AddVector(BaseLine.endpoints[1]->node->node);
-    CircleCenter.Scale(0.5);
+    CircleCenter = 0.5 * ((*BaseLine->endpoints[0]->node->node) + (*BaseLine->endpoints[1]->node->node));
 
     // construct normal vector of circle
-    CirclePlaneNormal.CopyVector(BaseLine.endpoints[0]->node->node);
-    CirclePlaneNormal.SubtractVector(BaseLine.endpoints[1]->node->node);
+    CirclePlaneNormal = (*BaseLine->endpoints[0]->node->node) - (*BaseLine->endpoints[1]->node->node);
 
     double radius = CirclePlaneNormal.NormSquared();
-    double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
-
-    NormalVector.ProjectOntoPlane(&CirclePlaneNormal);
+    double CircleRadius = sqrt(RADIUS * RADIUS - radius / 4.);
+
+    NormalVector.ProjectOntoPlane(CirclePlaneNormal);
     NormalVector.Normalize();
-    ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
-
-    SphereCenter.CopyVector(&NormalVector);
-    SphereCenter.Scale(CircleRadius);
-    SphereCenter.AddVector(&CircleCenter);
+    ShortestAngle = 2. * M_PI; // This will indicate the quadrant.
+
+    SphereCenter = (CircleRadius * NormalVector) +  CircleCenter;
     // Now, NormalVector and SphereCenter are two orthonormalized vectors in the plane defined by CirclePlaneNormal (not normalized)
 
     // look in one direction of baseline for initial candidate
-    SearchDirection.MakeNormalVector(&CirclePlaneNormal, &NormalVector);  // whether we look "left" first or "right" first is not important ...
+    SearchDirection = Plane(CirclePlaneNormal, NormalVector,0).getNormal();  // whether we look "left" first or "right" first is not important ...
 
     // adding point 1 and point 2 and add the line between them
-    Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
-    Log() << Verbose(0) << "Found second point is at " << *BaseLine.endpoints[1]->node << ".\n";
+    DoLog(0) && (Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine->endpoints[0]->node << "." << endl);
+    DoLog(0) && (Log() << Verbose(0) << "Found second point is at " << *BaseLine->endpoints[1]->node << ".\n");
 
     //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << helper << ".\n";
-    CandidateForTesselation OptCandidates(&BaseLine);
+    CandidateForTesselation OptCandidates(BaseLine);
     FindThirdPointForTesselation(NormalVector, SearchDirection, SphereCenter, OptCandidates, NULL, RADIUS, LC);
-    Log() << Verbose(0) << "List of third Points is:" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "List of third Points is:" << endl);
     for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); it++) {
-        Log() << Verbose(0) << " " << *(*it) << endl;
-    }
-
-    BTS = NULL;
-    AddCandidateTriangle(OptCandidates);
-//    delete(BaseLine.endpoints[0]);
-//    delete(BaseLine.endpoints[1]);
-
-    if (BTS != NULL) // we have created one starting triangle
+      DoLog(0) && (Log() << Verbose(0) << " " << *(*it) << endl);
+    }
+    if (!OptCandidates.pointlist.empty()) {
+      BTS = NULL;
+      AddCandidatePolygon(OptCandidates, RADIUS, LC);
+    } else {
+      delete BaseLine;
+      continue;
+    }
+
+    if (BTS != NULL) { // we have created one starting triangle
+      delete BaseLine;
       break;
-    else {
+    } else {
       // remove all candidates from the list and then the list itself
       OptCandidates.pointlist.clear();
     }
-  }
-};
+    delete BaseLine;
+  }
+
+  return (BTS != NULL);
+}
+;
 
 /** Checks for a given baseline and a third point candidate whether baselines of the found triangle don't have even better candidates.
@@ -2214,5 +2378,5 @@
 //            if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
 //              // rotated the wrong way!
-//              eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
+//              DoeLog(1) && (eLog()<< Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl);
 //            }
 //
@@ -2271,5 +2435,5 @@
 //          }
 //        } else {
-//          eLog() << Verbose(2) << "Baseline is connected to two triangles already?" << endl;
+//          DoeLog(2) && (eLog()<< Verbose(2) << "Baseline is connected to two triangles already?" << endl);
 //        }
 //      } else {
@@ -2278,5 +2442,5 @@
 //    }
 //  } else {
-//    eLog() << Verbose(1) << "Could not find the TesselPoint " << *ThirdNode << "." << endl;
+//    DoeLog(1) && (eLog()<< Verbose(1) << "Could not find the TesselPoint " << *ThirdNode << "." << endl);
 //  }
 //
@@ -2292,9 +2456,7 @@
  * @param *LC LinkedCell structure with neighbouring points
  */
-bool Tesselation::FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
-{
-	Info FunctionInfo(__func__);
-  bool result = true;
-
+bool Tesselation::FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, const BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
+{
+  Info FunctionInfo(__func__);
   Vector CircleCenter;
   Vector CirclePlaneNormal;
@@ -2302,161 +2464,107 @@
   Vector SearchDirection;
   Vector helper;
-  TesselPoint *ThirdNode = NULL;
+  BoundaryPointSet *ThirdPoint = NULL;
   LineMap::iterator testline;
   double radius, CircleRadius;
 
-  for (int i=0;i<3;i++)
-    if ((T.endpoints[i]->node != CandidateLine.BaseLine->endpoints[0]->node) && (T.endpoints[i]->node != CandidateLine.BaseLine->endpoints[1]->node)) {
-      ThirdNode = T.endpoints[i]->node;
+  for (int i = 0; i < 3; i++)
+    if ((T.endpoints[i] != CandidateLine.BaseLine->endpoints[0]) && (T.endpoints[i] != CandidateLine.BaseLine->endpoints[1])) {
+      ThirdPoint = T.endpoints[i];
       break;
     }
-  Log() << Verbose(0) << "Current baseline is " << *CandidateLine.BaseLine << " with ThirdNode " << *ThirdNode << " of triangle " << T << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Current baseline is " << *CandidateLine.BaseLine << " with ThirdPoint " << *ThirdPoint << " of triangle " << T << "." << endl);
+
+  CandidateLine.T = &T;
 
   // construct center of circle
-  CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
-  CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
-  CircleCenter.Scale(0.5);
+  CircleCenter = 0.5 * ((*CandidateLine.BaseLine->endpoints[0]->node->node) +
+                        (*CandidateLine.BaseLine->endpoints[1]->node->node));
 
   // construct normal vector of circle
-  CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
-  CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
+  CirclePlaneNormal = (*CandidateLine.BaseLine->endpoints[0]->node->node) -
+                      (*CandidateLine.BaseLine->endpoints[1]->node->node);
 
   // calculate squared radius of circle
-  radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
-  if (radius/4. < RADIUS*RADIUS) {
+  radius = CirclePlaneNormal.ScalarProduct(CirclePlaneNormal);
+  if (radius / 4. < RADIUS * RADIUS) {
     // construct relative sphere center with now known CircleCenter
-    RelativeSphereCenter.CopyVector(&T.SphereCenter);
-    RelativeSphereCenter.SubtractVector(&CircleCenter);
-
-    CircleRadius = RADIUS*RADIUS - radius/4.;
+    RelativeSphereCenter = T.SphereCenter - CircleCenter;
+
+    CircleRadius = RADIUS * RADIUS - radius / 4.;
     CirclePlaneNormal.Normalize();
-    Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
-
-    Log() << Verbose(1) << "INFO: OldSphereCenter is at " << T.SphereCenter << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl);
+
+    DoLog(1) && (Log() << Verbose(1) << "INFO: OldSphereCenter is at " << T.SphereCenter << "." << endl);
 
     // construct SearchDirection and an "outward pointer"
-    SearchDirection.MakeNormalVector(&RelativeSphereCenter, &CirclePlaneNormal);
-    helper.CopyVector(&CircleCenter);
-    helper.SubtractVector(ThirdNode->node);
-    if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
+    SearchDirection = Plane(RelativeSphereCenter, CirclePlaneNormal,0).getNormal();
+    helper = CircleCenter - (*ThirdPoint->node->node);
+    if (helper.ScalarProduct(SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
       SearchDirection.Scale(-1.);
-    Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
-    if (fabs(RelativeSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
+    DoLog(1) && (Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl);
+    if (fabs(RelativeSphereCenter.ScalarProduct(SearchDirection)) > HULLEPSILON) {
       // rotated the wrong way!
-      eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl);
     }
 
     // add third point
-    FindThirdPointForTesselation(T.NormalVector, SearchDirection, T.SphereCenter, CandidateLine, ThirdNode, RADIUS, LC);
+    FindThirdPointForTesselation(T.NormalVector, SearchDirection, T.SphereCenter, CandidateLine, ThirdPoint, RADIUS, LC);
 
   } else {
-    Log() << Verbose(0) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and base triangle " << T << " is too big!" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and base triangle " << T << " is too big!" << endl);
   }
 
   if (CandidateLine.pointlist.empty()) {
-    eLog() << Verbose(2) << "Could not find a suitable candidate." << endl;
+    DoeLog(2) && (eLog() << Verbose(2) << "Could not find a suitable candidate." << endl);
     return false;
   }
-  Log() << Verbose(0) << "Third Points are: " << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Third Points are: " << endl);
   for (TesselPointList::iterator it = CandidateLine.pointlist.begin(); it != CandidateLine.pointlist.end(); ++it) {
-    Log() << Verbose(0) << " " << *(*it) << endl;
+    DoLog(0) && (Log() << Verbose(0) << " " << *(*it) << endl);
   }
 
   return true;
-
-//  BoundaryLineSet *BaseRay = CandidateLine.BaseLine;
-//  for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
-//    Log() << Verbose(0) << "Third point candidate is " << *(*it)->point
-//    << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
-//    Log() << Verbose(0) << "Baseline is " << *BaseRay << endl;
-//
-//    // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
-//    TesselPoint *PointCandidates[3];
-//    PointCandidates[0] = (*it)->point;
-//    PointCandidates[1] = BaseRay->endpoints[0]->node;
-//    PointCandidates[2] = BaseRay->endpoints[1]->node;
-//    int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
-//
-//    BTS = NULL;
-//    // check for present edges and whether we reach better candidates from them
-//    //if (HasOtherBaselineBetterCandidate(BaseRay, (*it)->point, ShortestAngle, RADIUS, LC) ) {
-//    if (0) {
-//      result = false;
-//      break;
-//    } else {
-//      // If there is no triangle, add it regularly.
-//      if (existentTrianglesCount == 0) {
-//        AddTesselationPoint((*it)->point, 0);
-//        AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
-//        AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
-//
-//        if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
-//          CandidateLine.point = (*it)->point;
-//          CandidateLine.OptCenter.CopyVector(&((*it)->OptCenter));
-//          CandidateLine.OtherOptCenter.CopyVector(&((*it)->OtherOptCenter));
-//          CandidateLine.ShortestAngle = ShortestAngle;
-//        } else {
-////          eLog() << Verbose(1) << "This triangle consisting of ";
-////          Log() << Verbose(0) << *(*it)->point << ", ";
-////          Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
-////          Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
-////          Log() << Verbose(0) << "exists and is not added, as it 0x80000000006fc150(does not seem helpful!" << endl;
-//          result = false;
-//        }
-//      } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
-//          AddTesselationPoint((*it)->point, 0);
-//          AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
-//          AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
-//
-//          // We demand that at most one new degenerate line is created and that this line also already exists (which has to be the case due to existentTrianglesCount == 1)
-//          // i.e. at least one of the three lines must be present with TriangleCount <= 1
-//          if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS) || CandidateLine.BaseLine->skipped) {
-//            CandidateLine.point = (*it)->point;
-//            CandidateLine.OptCenter.CopyVector(&(*it)->OptCenter);
-//            CandidateLine.OtherOptCenter.CopyVector(&(*it)->OtherOptCenter);
-//            CandidateLine.ShortestAngle = ShortestAngle+2.*M_PI;
-//
-//          } else {
-////            eLog() << Verbose(1) << "This triangle consisting of " << *(*it)->point << ", " << *BaseRay->endpoints[0]->node << " and " << *BaseRay->endpoints[1]->node << " " << "exists and is not added, as it does not seem helpful!" << endl;
-//            result = false;
-//          }
-//      } else {
-////        Log() << Verbose(1) << "This triangle consisting of ";
-////        Log() << Verbose(0) << *(*it)->point << ", ";
-////        Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
-////        Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
-////        Log() << Verbose(0) << "is invalid!" << endl;
-//        result = false;
-//      }
-//    }
-//
-//    // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
-//    BaseRay = BLS[0];
-//    if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
-//      eLog() << Verbose(1) << "Triangle " << *BTS << " has zero normal vector!" << endl;
-//      exit(255);
-//    }
-//
-//  }
-//
-//  // remove all candidates from the list and then the list itself
-//  class CandidateForTesselation *remover = NULL;
-//  for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
-//    remover = *it;
-//    delete(remover);
-//  }
-//  delete(OptCandidates);
-  return result;
-};
+}
+;
+
+/** Walks through Tesselation::OpenLines() and finds candidates for newly created ones.
+ * \param *&LCList atoms in LinkedCell list
+ * \param RADIUS radius of the virtual sphere
+ * \return true - for all open lines without candidates so far, a candidate has been found,
+ *         false - at least one open line without candidate still
+ */
+bool Tesselation::FindCandidatesforOpenLines(const double RADIUS, const LinkedCell *&LCList)
+{
+  bool TesselationFailFlag = true;
+  CandidateForTesselation *baseline = NULL;
+  BoundaryTriangleSet *T = NULL;
+
+  for (CandidateMap::iterator Runner = OpenLines.begin(); Runner != OpenLines.end(); Runner++) {
+    baseline = Runner->second;
+    if (baseline->pointlist.empty()) {
+      assert((baseline->BaseLine->triangles.size() == 1) && ("Open line without exactly one attached triangle"));
+      T = (((baseline->BaseLine->triangles.begin()))->second);
+      DoLog(1) && (Log() << Verbose(1) << "Finding best candidate for open line " << *baseline->BaseLine << " of triangle " << *T << endl);
+      TesselationFailFlag = TesselationFailFlag && FindNextSuitableTriangle(*baseline, *T, RADIUS, LCList); //the line is there, so there is a triangle, but only one.
+    }
+  }
+  return TesselationFailFlag;
+}
+;
 
 /** Adds the present line and candidate point from \a &CandidateLine to the Tesselation.
  * \param CandidateLine triangle to add
- * \NOTE we need the copy operator here as the original CandidateForTesselation is removed in AddTesselationLine()
- */
-void Tesselation::AddCandidateTriangle(CandidateForTesselation CandidateLine)
-{
-	Info FunctionInfo(__func__);
+ * \param RADIUS Radius of sphere
+ * \param *LC LinkedCell structure
+ * \NOTE we need the copy operator here as the original CandidateForTesselation is removed in
+ * AddTesselationLine() in AddCandidateTriangle()
+ */
+void Tesselation::AddCandidatePolygon(CandidateForTesselation CandidateLine, const double RADIUS, const LinkedCell *LC)
+{
+  Info FunctionInfo(__func__);
   Vector Center;
   TesselPoint * const TurningPoint = CandidateLine.BaseLine->endpoints[0]->node;
+  TesselPointList::iterator Runner;
+  TesselPointList::iterator Sprinter;
 
   // fill the set of neighbours
@@ -2467,39 +2575,194 @@
   TesselPointList *connectedClosestPoints = GetCircleOfSetOfPoints(&SetOfNeighbours, TurningPoint, CandidateLine.BaseLine->endpoints[1]->node->node);
 
+  DoLog(0) && (Log() << Verbose(0) << "List of Candidates for Turning Point " << *TurningPoint << ":" << endl);
+  for (TesselPointList::iterator TesselRunner = connectedClosestPoints->begin(); TesselRunner != connectedClosestPoints->end(); ++TesselRunner)
+    DoLog(0) && (Log() << Verbose(0) << " " << **TesselRunner << endl);
+
   // go through all angle-sorted candidates (in degenerate n-nodes case we may have to add multiple triangles)
-  Log() << Verbose(0) << "List of Candidates for Turning Point: " << *TurningPoint << "." << endl;
-  for (TesselPointList::iterator TesselRunner = connectedClosestPoints->begin(); TesselRunner != connectedClosestPoints->end(); ++TesselRunner)
-    Log() << Verbose(0) << **TesselRunner << endl;
-  TesselPointList::iterator Runner = connectedClosestPoints->begin();
-  TesselPointList::iterator Sprinter = Runner;
+  Runner = connectedClosestPoints->begin();
+  Sprinter = Runner;
   Sprinter++;
-  while(Sprinter != connectedClosestPoints->end()) {
-    // add the points
+  while (Sprinter != connectedClosestPoints->end()) {
+    DoLog(0) && (Log() << Verbose(0) << "Current Runner is " << *(*Runner) << " and sprinter is " << *(*Sprinter) << "." << endl);
+
     AddTesselationPoint(TurningPoint, 0);
-    AddTesselationPoint((*Runner), 1);
-    AddTesselationPoint((*Sprinter), 2);
-
-    // add the lines
-    AddTesselationLine(TPS[0], TPS[1], 0);
-    AddTesselationLine(TPS[0], TPS[2], 1);
-    AddTesselationLine(TPS[1], TPS[2], 2);
-
-    // add the triangles
-    BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
-    AddTesselationTriangle();
-    BTS->GetCenter(&Center);
-    Center.SubtractVector(&CandidateLine.OptCenter);
-    BTS->SphereCenter.CopyVector(&CandidateLine.OptCenter);
-    BTS->GetNormalVector(Center);
-
-    Log() << Verbose(0) << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector << "." << endl;
+    AddTesselationPoint(*Runner, 1);
+    AddTesselationPoint(*Sprinter, 2);
+
+    AddCandidateTriangle(CandidateLine, Opt);
+
     Runner = Sprinter;
     Sprinter++;
-    Log() << Verbose(0) << "Current Runner is " << **Runner << "." << endl;
-    if (Sprinter != connectedClosestPoints->end())
-      Log() << Verbose(0) << " There are still more triangles to add." << endl;
-  }
-  delete(connectedClosestPoints);
+    if (Sprinter != connectedClosestPoints->end()) {
+      // fill the internal open lines with its respective candidate (otherwise lines in degenerate case are not picked)
+      FindDegeneratedCandidatesforOpenLines(*Sprinter, &CandidateLine.OptCenter); // Assume BTS contains last triangle
+      DoLog(0) && (Log() << Verbose(0) << " There are still more triangles to add." << endl);
+    }
+    // pick candidates for other open lines as well
+    FindCandidatesforOpenLines(RADIUS, LC);
+
+    // check whether we add a degenerate or a normal triangle
+    if (CheckDegeneracy(CandidateLine, RADIUS, LC)) {
+      // add normal and degenerate triangles
+      DoLog(1) && (Log() << Verbose(1) << "Triangle of endpoints " << *TPS[0] << "," << *TPS[1] << " and " << *TPS[2] << " is degenerated, adding both sides." << endl);
+      AddCandidateTriangle(CandidateLine, OtherOpt);
+
+      if (Sprinter != connectedClosestPoints->end()) {
+        // fill the internal open lines with its respective candidate (otherwise lines in degenerate case are not picked)
+        FindDegeneratedCandidatesforOpenLines(*Sprinter, &CandidateLine.OtherOptCenter);
+      }
+      // pick candidates for other open lines as well
+      FindCandidatesforOpenLines(RADIUS, LC);
+    }
+  }
+  delete (connectedClosestPoints);
 };
+
+/** for polygons (multiple candidates for a baseline) sets internal edges to the correct next candidate.
+ * \param *Sprinter next candidate to which internal open lines are set
+ * \param *OptCenter OptCenter for this candidate
+ */
+void Tesselation::FindDegeneratedCandidatesforOpenLines(TesselPoint * const Sprinter, const Vector * const OptCenter)
+{
+  Info FunctionInfo(__func__);
+
+  pair<LineMap::iterator, LineMap::iterator> FindPair = TPS[0]->lines.equal_range(TPS[2]->node->nr);
+  for (LineMap::const_iterator FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Checking line " << *(FindLine->second) << " ..." << endl);
+    // If there is a line with less than two attached triangles, we don't need a new line.
+    if (FindLine->second->triangles.size() == 1) {
+      CandidateMap::iterator Finder = OpenLines.find(FindLine->second);
+      if (!Finder->second->pointlist.empty())
+        DoLog(1) && (Log() << Verbose(1) << "INFO: line " << *(FindLine->second) << " is open with candidate " << **(Finder->second->pointlist.begin()) << "." << endl);
+      else {
+        DoLog(1) && (Log() << Verbose(1) << "INFO: line " << *(FindLine->second) << " is open with no candidate, setting to next Sprinter" << (*Sprinter) << endl);
+        Finder->second->T = BTS;  // is last triangle
+        Finder->second->pointlist.push_back(Sprinter);
+        Finder->second->ShortestAngle = 0.;
+        Finder->second->OptCenter = *OptCenter;
+      }
+    }
+  }
+};
+
+/** If a given \a *triangle is degenerated, this adds both sides.
+ * i.e. the triangle with same BoundaryPointSet's but NormalVector in opposite direction.
+ * Note that endpoints are stored in Tesselation::TPS
+ * \param CandidateLine CanddiateForTesselation structure for the desired BoundaryLine
+ * \param RADIUS radius of sphere
+ * \param *LC pointer to LinkedCell structure
+ */
+void Tesselation::AddDegeneratedTriangle(CandidateForTesselation &CandidateLine, const double RADIUS, const LinkedCell *LC)
+{
+  Info FunctionInfo(__func__);
+  Vector Center;
+  CandidateMap::const_iterator CandidateCheck = OpenLines.end();
+  BoundaryTriangleSet *triangle = NULL;
+
+  /// 1. Create or pick the lines for the first triangle
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Creating/Picking lines for first triangle ..." << endl);
+  for (int i = 0; i < 3; i++) {
+    BLS[i] = NULL;
+    DoLog(0) && (Log() << Verbose(0) << "Current line is between " << *TPS[(i + 0) % 3] << " and " << *TPS[(i + 1) % 3] << ":" << endl);
+    AddTesselationLine(&CandidateLine.OptCenter, TPS[(i + 2) % 3], TPS[(i + 0) % 3], TPS[(i + 1) % 3], i);
+  }
+
+  /// 2. create the first triangle and NormalVector and so on
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Adding first triangle with center at " << CandidateLine.OptCenter << " ..." << endl);
+  BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
+  AddTesselationTriangle();
+
+  // create normal vector
+  BTS->GetCenter(&Center);
+  Center -= CandidateLine.OptCenter;
+  BTS->SphereCenter = CandidateLine.OptCenter;
+  BTS->GetNormalVector(Center);
+  // give some verbose output about the whole procedure
+  if (CandidateLine.T != NULL)
+    DoLog(0) && (Log() << Verbose(0) << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector << ", from " << *CandidateLine.T << " and angle " << CandidateLine.ShortestAngle << "." << endl);
+  else
+    DoLog(0) && (Log() << Verbose(0) << "--> New starting triangle with " << *BTS << " and normal vector " << BTS->NormalVector << " and no top triangle." << endl);
+  triangle = BTS;
+
+  /// 3. Gather candidates for each new line
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Adding candidates to new lines ..." << endl);
+  for (int i = 0; i < 3; i++) {
+    DoLog(0) && (Log() << Verbose(0) << "Current line is between " << *TPS[(i + 0) % 3] << " and " << *TPS[(i + 1) % 3] << ":" << endl);
+    CandidateCheck = OpenLines.find(BLS[i]);
+    if ((CandidateCheck != OpenLines.end()) && (CandidateCheck->second->pointlist.empty())) {
+      if (CandidateCheck->second->T == NULL)
+        CandidateCheck->second->T = triangle;
+      FindNextSuitableTriangle(*(CandidateCheck->second), *CandidateCheck->second->T, RADIUS, LC);
+    }
+  }
+
+  /// 4. Create or pick the lines for the second triangle
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Creating/Picking lines for second triangle ..." << endl);
+  for (int i = 0; i < 3; i++) {
+    DoLog(0) && (Log() << Verbose(0) << "Current line is between " << *TPS[(i + 0) % 3] << " and " << *TPS[(i + 1) % 3] << ":" << endl);
+    AddTesselationLine(&CandidateLine.OtherOptCenter, TPS[(i + 2) % 3], TPS[(i + 0) % 3], TPS[(i + 1) % 3], i);
+  }
+
+  /// 5. create the second triangle and NormalVector and so on
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Adding second triangle with center at " << CandidateLine.OtherOptCenter << " ..." << endl);
+  BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
+  AddTesselationTriangle();
+
+  BTS->SphereCenter = CandidateLine.OtherOptCenter;
+  // create normal vector in other direction
+  BTS->GetNormalVector(triangle->NormalVector);
+  BTS->NormalVector.Scale(-1.);
+  // give some verbose output about the whole procedure
+  if (CandidateLine.T != NULL)
+    DoLog(0) && (Log() << Verbose(0) << "--> New degenerate triangle with " << *BTS << " and normal vector " << BTS->NormalVector << ", from " << *CandidateLine.T << " and angle " << CandidateLine.ShortestAngle << "." << endl);
+  else
+    DoLog(0) && (Log() << Verbose(0) << "--> New degenerate starting triangle with " << *BTS << " and normal vector " << BTS->NormalVector << " and no top triangle." << endl);
+
+  /// 6. Adding triangle to new lines
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Adding second triangles to new lines ..." << endl);
+  for (int i = 0; i < 3; i++) {
+    DoLog(0) && (Log() << Verbose(0) << "Current line is between " << *TPS[(i + 0) % 3] << " and " << *TPS[(i + 1) % 3] << ":" << endl);
+    CandidateCheck = OpenLines.find(BLS[i]);
+    if ((CandidateCheck != OpenLines.end()) && (CandidateCheck->second->pointlist.empty())) {
+      if (CandidateCheck->second->T == NULL)
+        CandidateCheck->second->T = BTS;
+    }
+  }
+}
+;
+
+/** Adds a triangle to the Tesselation structure from three given TesselPoint's.
+ * Note that endpoints are in Tesselation::TPS.
+ * \param CandidateLine CandidateForTesselation structure contains other information
+ * \param type which opt center to add (i.e. which side) and thus which NormalVector to take
+ */
+void Tesselation::AddCandidateTriangle(CandidateForTesselation &CandidateLine, enum centers type)
+{
+  Info FunctionInfo(__func__);
+  Vector Center;
+  Vector *OptCenter = (type == Opt) ? &CandidateLine.OptCenter : &CandidateLine.OtherOptCenter;
+
+  // add the lines
+  AddTesselationLine(OptCenter, TPS[2], TPS[0], TPS[1], 0);
+  AddTesselationLine(OptCenter, TPS[1], TPS[0], TPS[2], 1);
+  AddTesselationLine(OptCenter, TPS[0], TPS[1], TPS[2], 2);
+
+  // add the triangles
+  BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
+  AddTesselationTriangle();
+
+  // create normal vector
+  BTS->GetCenter(&Center);
+  Center.SubtractVector(*OptCenter);
+  BTS->SphereCenter = *OptCenter;
+  BTS->GetNormalVector(Center);
+
+  // give some verbose output about the whole procedure
+  if (CandidateLine.T != NULL)
+    DoLog(0) && (Log() << Verbose(0) << "--> New" << ((type == OtherOpt) ? " degenerate " : " ") << "triangle with " << *BTS << " and normal vector " << BTS->NormalVector << ", from " << *CandidateLine.T << " and angle " << CandidateLine.ShortestAngle << "." << endl);
+  else
+    DoLog(0) && (Log() << Verbose(0) << "--> New" << ((type == OtherOpt) ? " degenerate " : " ") << "starting triangle with " << *BTS << " and normal vector " << BTS->NormalVector << " and no top triangle." << endl);
+}
+;
 
 /** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
@@ -2512,18 +2775,18 @@
 class BoundaryPointSet *Tesselation::IsConvexRectangle(class BoundaryLineSet *Base)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   class BoundaryPointSet *Spot = NULL;
   class BoundaryLineSet *OtherBase;
   Vector *ClosestPoint;
 
-  int m=0;
-  for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
-    for (int j=0;j<3;j++) // all of their endpoints and baselines
+  int m = 0;
+  for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
+    for (int j = 0; j < 3; j++) // all of their endpoints and baselines
       if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
         BPS[m++] = runner->second->endpoints[j];
-  OtherBase = new class BoundaryLineSet(BPS,-1);
-
-  Log() << Verbose(1) << "INFO: Current base line is " << *Base << "." << endl;
-  Log() << Verbose(1) << "INFO: Other base line is " << *OtherBase << "." << endl;
+  OtherBase = new class BoundaryLineSet(BPS, -1);
+
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Current base line is " << *Base << "." << endl);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Other base line is " << *OtherBase << "." << endl);
 
   // get the closest point on each line to the other line
@@ -2531,19 +2794,17 @@
 
   // delete the temporary other base line
-  delete(OtherBase);
+  delete (OtherBase);
 
   // get the distance vector from Base line to OtherBase line
   Vector DistanceToIntersection[2], BaseLine;
   double distance[2];
-  BaseLine.CopyVector(Base->endpoints[1]->node->node);
-  BaseLine.SubtractVector(Base->endpoints[0]->node->node);
-  for (int i=0;i<2;i++) {
-    DistanceToIntersection[i].CopyVector(ClosestPoint);
-    DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
-    distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
-  }
-  delete(ClosestPoint);
-  if ((distance[0] * distance[1]) > 0)  { // have same sign?
-    Log() << Verbose(1) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1]  << ". " << *Base << "' rectangle is concave." << endl;
+  BaseLine = (*Base->endpoints[1]->node->node) - (*Base->endpoints[0]->node->node);
+  for (int i = 0; i < 2; i++) {
+    DistanceToIntersection[i] = (*ClosestPoint) - (*Base->endpoints[i]->node->node);
+    distance[i] = BaseLine.ScalarProduct(DistanceToIntersection[i]);
+  }
+  delete (ClosestPoint);
+  if ((distance[0] * distance[1]) > 0) { // have same sign?
+    DoLog(1) && (Log() << Verbose(1) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl);
     if (distance[0] < distance[1]) {
       Spot = Base->endpoints[0];
@@ -2552,37 +2813,41 @@
     }
     return Spot;
-  } else {  // different sign, i.e. we are in between
-    Log() << Verbose(0) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
+  } else { // different sign, i.e. we are in between
+    DoLog(0) && (Log() << Verbose(0) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl);
     return NULL;
   }
 
-};
+}
+;
 
 void Tesselation::PrintAllBoundaryPoints(ofstream *out) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // print all lines
-  Log() << Verbose(0) << "Printing all boundary points for debugging:" << endl;
-  for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
-    Log() << Verbose(0) << *(PointRunner->second) << endl;
-};
+  DoLog(0) && (Log() << Verbose(0) << "Printing all boundary points for debugging:" << endl);
+  for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin(); PointRunner != PointsOnBoundary.end(); PointRunner++)
+    DoLog(0) && (Log() << Verbose(0) << *(PointRunner->second) << endl);
+}
+;
 
 void Tesselation::PrintAllBoundaryLines(ofstream *out) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // print all lines
-  Log() << Verbose(0) << "Printing all boundary lines for debugging:" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Printing all boundary lines for debugging:" << endl);
   for (LineMap::const_iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
-    Log() << Verbose(0) << *(LineRunner->second) << endl;
-};
+    DoLog(0) && (Log() << Verbose(0) << *(LineRunner->second) << endl);
+}
+;
 
 void Tesselation::PrintAllBoundaryTriangles(ofstream *out) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // print all triangles
-  Log() << Verbose(0) << "Printing all boundary triangles for debugging:" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Printing all boundary triangles for debugging:" << endl);
   for (TriangleMap::const_iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
-    Log() << Verbose(0) << *(TriangleRunner->second) << endl;
-};
+    DoLog(0) && (Log() << Verbose(0) << *(TriangleRunner->second) << endl);
+}
+;
 
 /** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
@@ -2593,18 +2858,18 @@
 double Tesselation::PickFarthestofTwoBaselines(class BoundaryLineSet *Base)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   class BoundaryLineSet *OtherBase;
   Vector *ClosestPoint[2];
   double volume;
 
-  int m=0;
-  for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
-    for (int j=0;j<3;j++) // all of their endpoints and baselines
+  int m = 0;
+  for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
+    for (int j = 0; j < 3; j++) // all of their endpoints and baselines
       if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
         BPS[m++] = runner->second->endpoints[j];
-  OtherBase = new class BoundaryLineSet(BPS,-1);
-
-  Log() << Verbose(0) << "INFO: Current base line is " << *Base << "." << endl;
-  Log() << Verbose(0) << "INFO: Other base line is " << *OtherBase << "." << endl;
+  OtherBase = new class BoundaryLineSet(BPS, -1);
+
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Current base line is " << *Base << "." << endl);
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Other base line is " << *OtherBase << "." << endl);
 
   // get the closest point on each line to the other line
@@ -2613,7 +2878,5 @@
 
   // get the distance vector from Base line to OtherBase line
-  Vector Distance;
-  Distance.CopyVector(ClosestPoint[1]);
-  Distance.SubtractVector(ClosestPoint[0]);
+  Vector Distance = (*ClosestPoint[1]) - (*ClosestPoint[0]);
 
   // calculate volume
@@ -2621,10 +2884,10 @@
 
   // delete the temporary other base line and the closest points
-  delete(ClosestPoint[0]);
-  delete(ClosestPoint[1]);
-  delete(OtherBase);
+  delete (ClosestPoint[0]);
+  delete (ClosestPoint[1]);
+  delete (OtherBase);
 
   if (Distance.NormSquared() < MYEPSILON) { // check for intersection
-    Log() << Verbose(0) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "REJECT: Both lines have an intersection: Nothing to do." << endl);
     return false;
   } else { // check for sign against BaseLineNormal
@@ -2632,23 +2895,24 @@
     BaseLineNormal.Zero();
     if (Base->triangles.size() < 2) {
-      eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl);
       return 0.;
     }
     for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
-      Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
-      BaseLineNormal.AddVector(&(runner->second->NormalVector));
-    }
-    BaseLineNormal.Scale(1./2.);
-
-    if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
-      Log() << Verbose(0) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl);
+      BaseLineNormal += (runner->second->NormalVector);
+    }
+    BaseLineNormal.Scale(1. / 2.);
+
+    if (Distance.ScalarProduct(BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
+      DoLog(0) && (Log() << Verbose(0) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl);
       // calculate volume summand as a general tetraeder
       return volume;
-    } else {  // Base higher than OtherBase -> do nothing
-      Log() << Verbose(0) << "REJECT: Base line is higher: Nothing to do." << endl;
+    } else { // Base higher than OtherBase -> do nothing
+      DoLog(0) && (Log() << Verbose(0) << "REJECT: Base line is higher: Nothing to do." << endl);
       return 0.;
     }
   }
-};
+}
+;
 
 /** For a given baseline and its two connected triangles, flips the baseline.
@@ -2661,70 +2925,70 @@
 class BoundaryLineSet * Tesselation::FlipBaseline(class BoundaryLineSet *Base)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   class BoundaryLineSet *OldLines[4], *NewLine;
   class BoundaryPointSet *OldPoints[2];
   Vector BaseLineNormal;
   int OldTriangleNrs[2], OldBaseLineNr;
-  int i,m;
+  int i, m;
 
   // calculate NormalVector for later use
   BaseLineNormal.Zero();
   if (Base->triangles.size() < 2) {
-    eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl);
     return NULL;
   }
   for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
-    Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
-    BaseLineNormal.AddVector(&(runner->second->NormalVector));
-  }
-  BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl);
+    BaseLineNormal += (runner->second->NormalVector);
+  }
+  BaseLineNormal.Scale(-1. / 2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
 
   // get the two triangles
   // gather four endpoints and four lines
-  for (int j=0;j<4;j++)
+  for (int j = 0; j < 4; j++)
     OldLines[j] = NULL;
-  for (int j=0;j<2;j++)
+  for (int j = 0; j < 2; j++)
     OldPoints[j] = NULL;
-  i=0;
-  m=0;
-  Log() << Verbose(0) << "The four old lines are: ";
-  for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
-    for (int j=0;j<3;j++) // all of their endpoints and baselines
+  i = 0;
+  m = 0;
+  DoLog(0) && (Log() << Verbose(0) << "The four old lines are: ");
+  for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
+    for (int j = 0; j < 3; j++) // all of their endpoints and baselines
       if (runner->second->lines[j] != Base) { // pick not the central baseline
         OldLines[i++] = runner->second->lines[j];
-        Log() << Verbose(0) << *runner->second->lines[j] << "\t";
+        DoLog(0) && (Log() << Verbose(0) << *runner->second->lines[j] << "\t");
       }
-  Log() << Verbose(0) << endl;
-  Log() << Verbose(0) << "The two old points are: ";
-  for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
-    for (int j=0;j<3;j++) // all of their endpoints and baselines
+  DoLog(0) && (Log() << Verbose(0) << endl);
+  DoLog(0) && (Log() << Verbose(0) << "The two old points are: ");
+  for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
+    for (int j = 0; j < 3; j++) // all of their endpoints and baselines
       if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
         OldPoints[m++] = runner->second->endpoints[j];
-        Log() << Verbose(0) << *runner->second->endpoints[j] << "\t";
+        DoLog(0) && (Log() << Verbose(0) << *runner->second->endpoints[j] << "\t");
       }
-  Log() << Verbose(0) << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
 
   // check whether everything is in place to create new lines and triangles
-  if (i<4) {
-    eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
+  if (i < 4) {
+    DoeLog(1) && (eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl);
     return NULL;
   }
-  for (int j=0;j<4;j++)
+  for (int j = 0; j < 4; j++)
     if (OldLines[j] == NULL) {
-      eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl);
       return NULL;
     }
-  for (int j=0;j<2;j++)
+  for (int j = 0; j < 2; j++)
     if (OldPoints[j] == NULL) {
-      eLog() << Verbose(1) << "We have not gathered enough endpoints!" << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "We have not gathered enough endpoints!" << endl);
       return NULL;
     }
 
   // remove triangles and baseline removes itself
-  Log() << Verbose(0) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Deleting baseline " << *Base << " from global list." << endl);
   OldBaseLineNr = Base->Nr;
-  m=0;
-  for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
-    Log() << Verbose(0) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
+  m = 0;
+  for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
+    DoLog(0) && (Log() << Verbose(0) << "INFO: Deleting triangle " << *(runner->second) << "." << endl);
     OldTriangleNrs[m++] = runner->second->Nr;
     RemoveTesselationTriangle(runner->second);
@@ -2736,13 +3000,13 @@
   NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
   LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
-  Log() << Verbose(0) << "INFO: Created new baseline " << *NewLine << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "INFO: Created new baseline " << *NewLine << "." << endl);
 
   // construct new triangles with flipped baseline
-  i=-1;
+  i = -1;
   if (OldLines[0]->IsConnectedTo(OldLines[2]))
-    i=2;
+    i = 2;
   if (OldLines[0]->IsConnectedTo(OldLines[3]))
-    i=3;
-  if (i!=-1) {
+    i = 3;
+  if (i != -1) {
     BLS[0] = OldLines[0];
     BLS[1] = OldLines[i];
@@ -2751,7 +3015,7 @@
     BTS->GetNormalVector(BaseLineNormal);
     AddTesselationTriangle(OldTriangleNrs[0]);
-    Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
-
-    BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
+    DoLog(0) && (Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl);
+
+    BLS[0] = (i == 2 ? OldLines[3] : OldLines[2]);
     BLS[1] = OldLines[1];
     BLS[2] = NewLine;
@@ -2759,13 +3023,13 @@
     BTS->GetNormalVector(BaseLineNormal);
     AddTesselationTriangle(OldTriangleNrs[1]);
-    Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl);
   } else {
-    eLog() << Verbose(0) << "The four old lines do not connect, something's utterly wrong here!" << endl;
+    DoeLog(0) && (eLog() << Verbose(0) << "The four old lines do not connect, something's utterly wrong here!" << endl);
     return NULL;
   }
 
   return NewLine;
-};
-
+}
+;
 
 /** Finds the second point of starting triangle.
@@ -2779,5 +3043,5 @@
 void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell *LC)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   Vector AngleCheck;
   class TesselPoint* Candidate = NULL;
@@ -2788,26 +3052,25 @@
   int Nupper[NDIM];
 
-  if (LC->SetIndexToNode(a)) {  // get cell for the starting point
-    for(int i=0;i<NDIM;i++) // store indices of this cell
+  if (LC->SetIndexToNode(a)) { // get cell for the starting point
+    for (int i = 0; i < NDIM; i++) // store indices of this cell
       N[i] = LC->n[i];
   } else {
-    eLog() << Verbose(1) << "Point " << *a << " is not found in cell " << LC->index << "." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "Point " << *a << " is not found in cell " << LC->index << "." << endl);
     return;
   }
   // then go through the current and all neighbouring cells and check the contained points for possible candidates
-  for (int i=0;i<NDIM;i++) {
-    Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
-    Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
-  }
-  Log() << Verbose(0) << "LC Intervals from [" << N[0] << "<->" << LC->N[0] << ", " << N[1] << "<->" << LC->N[1] << ", " << N[2] << "<->" << LC->N[2] << "] :"
-    << " [" << Nlower[0] << "," << Nupper[0] << "], " << " [" << Nlower[1] << "," << Nupper[1] << "], " << " [" << Nlower[2] << "," << Nupper[2] << "], " << endl;
+  for (int i = 0; i < NDIM; i++) {
+    Nlower[i] = ((N[i] - 1) >= 0) ? N[i] - 1 : 0;
+    Nupper[i] = ((N[i] + 1) < LC->N[i]) ? N[i] + 1 : LC->N[i] - 1;
+  }
+  DoLog(0) && (Log() << Verbose(0) << "LC Intervals from [" << N[0] << "<->" << LC->N[0] << ", " << N[1] << "<->" << LC->N[1] << ", " << N[2] << "<->" << LC->N[2] << "] :" << " [" << Nlower[0] << "," << Nupper[0] << "], " << " [" << Nlower[1] << "," << Nupper[1] << "], " << " [" << Nlower[2] << "," << Nupper[2] << "], " << endl);
 
   for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
     for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
       for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-        const LinkedNodes *List = LC->GetCurrentCell();
+        const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
         //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
         if (List != NULL) {
-          for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+          for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
             Candidate = (*Runner);
             // check if we only have one unique point yet ...
@@ -2817,8 +3080,7 @@
               double distance, scaleFactor;
 
-              OrthogonalizedOben.CopyVector(&Oben);
-              aCandidate.CopyVector(a->node);
-              aCandidate.SubtractVector(Candidate->node);
-              OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
+              OrthogonalizedOben = Oben;
+              aCandidate = (*a->node) - (*Candidate->node);
+              OrthogonalizedOben.ProjectOntoPlane(aCandidate);
               OrthogonalizedOben.Normalize();
               distance = 0.5 * aCandidate.Norm();
@@ -2826,18 +3088,15 @@
               OrthogonalizedOben.Scale(scaleFactor);
 
-              Center.CopyVector(Candidate->node);
-              Center.AddVector(a->node);
-              Center.Scale(0.5);
-              Center.AddVector(&OrthogonalizedOben);
-
-              AngleCheck.CopyVector(&Center);
-              AngleCheck.SubtractVector(a->node);
+              Center = 0.5 * ((*Candidate->node) + (*a->node));
+              Center += OrthogonalizedOben;
+
+              AngleCheck = Center - (*a->node);
               norm = aCandidate.Norm();
               // second point shall have smallest angle with respect to Oben vector
-              if (norm < RADIUS*2.) {
-                angle = AngleCheck.Angle(&Oben);
+              if (norm < RADIUS * 2.) {
+                angle = AngleCheck.Angle(Oben);
                 if (angle < Storage[0]) {
                   //Log() << Verbose(1) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
-                  Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
+                  DoLog(1) && (Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n");
                   OptCandidate = Candidate;
                   Storage[0] = angle;
@@ -2854,9 +3113,9 @@
           }
         } else {
-          Log() << Verbose(0) << "Linked cell list is empty." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "Linked cell list is empty." << endl);
         }
       }
-};
-
+}
+;
 
 /** This recursive function finds a third point, to form a triangle with two given ones.
@@ -2886,17 +3145,17 @@
  * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
  * @param CandidateLine CandidateForTesselation with the current base line and list of candidates and ShortestAngle
- * @param ThirdNode third point to avoid in search
+ * @param ThirdPoint third point to avoid in search
  * @param RADIUS radius of sphere
  * @param *LC LinkedCell structure with neighbouring points
  */
-void Tesselation::FindThirdPointForTesselation(Vector &NormalVector, Vector &SearchDirection, Vector &OldSphereCenter, CandidateForTesselation &CandidateLine, const class TesselPoint  * const ThirdNode, const double RADIUS, const LinkedCell *LC) const
-{
-	Info FunctionInfo(__func__);
-  Vector CircleCenter;  // center of the circle, i.e. of the band of sphere's centers
+void Tesselation::FindThirdPointForTesselation(const Vector &NormalVector, const Vector &SearchDirection, const Vector &OldSphereCenter, CandidateForTesselation &CandidateLine, const class BoundaryPointSet * const ThirdPoint, const double RADIUS, const LinkedCell *LC) const
+{
+  Info FunctionInfo(__func__);
+  Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
   Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
   Vector SphereCenter;
-  Vector NewSphereCenter;   // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
-  Vector OtherNewSphereCenter;   // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
-  Vector NewNormalVector;   // normal vector of the Candidate's triangle
+  Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
+  Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
+  Vector NewNormalVector; // normal vector of the Candidate's triangle
   Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
   Vector RelativeOldSphereCenter;
@@ -2909,54 +3168,57 @@
   TesselPoint *Candidate = NULL;
 
-  Log() << Verbose(1) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl);
+
+  // copy old center
+  CandidateLine.OldCenter = OldSphereCenter;
+  CandidateLine.ThirdPoint = ThirdPoint;
+  CandidateLine.pointlist.clear();
 
   // construct center of circle
-  CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
-  CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
-  CircleCenter.Scale(0.5);
+  CircleCenter = 0.5 * ((*CandidateLine.BaseLine->endpoints[0]->node->node) +
+                        (*CandidateLine.BaseLine->endpoints[1]->node->node));
 
   // construct normal vector of circle
-  CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
-  CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
-
-  RelativeOldSphereCenter.CopyVector(&OldSphereCenter);
-  RelativeOldSphereCenter.SubtractVector(&CircleCenter);
-
-  // calculate squared radius TesselPoint *ThirdNode,f circle
-  radius = CirclePlaneNormal.NormSquared()/4.;
-  if (radius < RADIUS*RADIUS) {
-    CircleRadius = RADIUS*RADIUS - radius;
+  CirclePlaneNormal = (*CandidateLine.BaseLine->endpoints[0]->node->node) -
+                      (*CandidateLine.BaseLine->endpoints[1]->node->node);
+
+  RelativeOldSphereCenter = OldSphereCenter - CircleCenter;
+
+  // calculate squared radius TesselPoint *ThirdPoint,f circle
+  radius = CirclePlaneNormal.NormSquared() / 4.;
+  if (radius < RADIUS * RADIUS) {
+    CircleRadius = RADIUS * RADIUS - radius;
     CirclePlaneNormal.Normalize();
-    Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl);
 
     // test whether old center is on the band's plane
-    if (fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
-      eLog() << Verbose(1) << "Something's very wrong here: RelativeOldSphereCenter is not on the band's plane as desired by " << fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
-      RelativeOldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
+    if (fabs(RelativeOldSphereCenter.ScalarProduct(CirclePlaneNormal)) > HULLEPSILON) {
+      DoeLog(1) && (eLog() << Verbose(1) << "Something's very wrong here: RelativeOldSphereCenter is not on the band's plane as desired by " << fabs(RelativeOldSphereCenter.ScalarProduct(CirclePlaneNormal)) << "!" << endl);
+      RelativeOldSphereCenter.ProjectOntoPlane(CirclePlaneNormal);
     }
     radius = RelativeOldSphereCenter.NormSquared();
     if (fabs(radius - CircleRadius) < HULLEPSILON) {
-      Log() << Verbose(1) << "INFO: RelativeOldSphereCenter is at " << RelativeOldSphereCenter << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "INFO: RelativeOldSphereCenter is at " << RelativeOldSphereCenter << "." << endl);
 
       // check SearchDirection
-      Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
-      if (fabs(RelativeOldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {  // rotated the wrong way!
-        eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
+      DoLog(1) && (Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl);
+      if (fabs(RelativeOldSphereCenter.ScalarProduct(SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
+        DoeLog(1) && (eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl);
       }
 
       // get cell for the starting point
       if (LC->SetIndexToVector(&CircleCenter)) {
-        for(int i=0;i<NDIM;i++) // store indices of this cell
-        N[i] = LC->n[i];
+        for (int i = 0; i < NDIM; i++) // store indices of this cell
+          N[i] = LC->n[i];
         //Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
       } else {
-        eLog() << Verbose(1) << "Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
+        DoeLog(1) && (eLog() << Verbose(1) << "Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl);
         return;
       }
       // then go through the current and all neighbouring cells and check the contained points for possible candidates
       //Log() << Verbose(1) << "LC Intervals:";
-      for (int i=0;i<NDIM;i++) {
-        Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
-        Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
+      for (int i = 0; i < NDIM; i++) {
+        Nlower[i] = ((N[i] - 1) >= 0) ? N[i] - 1 : 0;
+        Nupper[i] = ((N[i] + 1) < LC->N[i]) ? N[i] + 1 : LC->N[i] - 1;
         //Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
       }
@@ -2965,90 +3227,94 @@
         for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
           for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-            const LinkedNodes *List = LC->GetCurrentCell();
+            const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
             //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
             if (List != NULL) {
-              for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+              for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
                 Candidate = (*Runner);
 
                 // check for three unique points
-                Log() << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " for BaseLine " << *CandidateLine.BaseLine << " with OldSphereCenter " << OldSphereCenter << "." << endl;
-                if ((Candidate != CandidateLine.BaseLine->endpoints[0]->node) && (Candidate != CandidateLine.BaseLine->endpoints[1]->node) ){
+                DoLog(2) && (Log() << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " for BaseLine " << *CandidateLine.BaseLine << " with OldSphereCenter " << OldSphereCenter << "." << endl);
+                if ((Candidate != CandidateLine.BaseLine->endpoints[0]->node) && (Candidate != CandidateLine.BaseLine->endpoints[1]->node)) {
 
                   // find center on the plane
                   GetCenterofCircumcircle(&NewPlaneCenter, *CandidateLine.BaseLine->endpoints[0]->node->node, *CandidateLine.BaseLine->endpoints[1]->node->node, *Candidate->node);
-                  Log() << Verbose(1) << "INFO: NewPlaneCenter is " << NewPlaneCenter << "." << endl;
-
-                  if (NewNormalVector.MakeNormalVector(CandidateLine.BaseLine->endpoints[0]->node->node, CandidateLine.BaseLine->endpoints[1]->node->node, Candidate->node)
-                  && (fabs(NewNormalVector.NormSquared()) > HULLEPSILON)
-                  ) {
-                    Log() << Verbose(1) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
-                    radius = CandidateLine.BaseLine->endpoints[0]->node->node->DistanceSquared(&NewPlaneCenter);
-                    Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
-                    Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
-                    Log() << Verbose(1) << "INFO: Radius of CircumCenterCircle is " << radius << "." << endl;
-                    if (radius < RADIUS*RADIUS) {
-                      otherradius = CandidateLine.BaseLine->endpoints[1]->node->node->DistanceSquared(&NewPlaneCenter);
-                      if (fabs(radius - otherradius) > HULLEPSILON) {
-                        eLog() << Verbose(1) << "Distance to center of circumcircle is not the same from each corner of the triangle: " << fabs(radius-otherradius) << endl;
-                      }
-                      // construct both new centers
-                      NewSphereCenter.CopyVector(&NewPlaneCenter);
-                      OtherNewSphereCenter.CopyVector(&NewPlaneCenter);
-                      helper.CopyVector(&NewNormalVector);
-                      helper.Scale(sqrt(RADIUS*RADIUS - radius));
-                      Log() << Verbose(2) << "INFO: Distance of NewPlaneCenter " << NewPlaneCenter << " to either NewSphereCenter is " << helper.Norm() << " of vector " << helper << " with sphere radius " << RADIUS << "." << endl;
-                      NewSphereCenter.AddVector(&helper);
-                      Log() << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
-                      // OtherNewSphereCenter is created by the same vector just in the other direction
-                      helper.Scale(-1.);
-                      OtherNewSphereCenter.AddVector(&helper);
-                      Log() << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
-
-                      alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
-                      Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
-                      alpha = min(alpha, Otheralpha);
-
-                      // if there is a better candidate, drop the current list and add the new candidate
-                      // otherwise ignore the new candidate and keep the list
-                      if (CandidateLine.ShortestAngle > (alpha - HULLEPSILON)) {
-                        if (fabs(alpha - Otheralpha) > MYEPSILON) {
-                          CandidateLine.OptCenter.CopyVector(&NewSphereCenter);
-                          CandidateLine.OtherOptCenter.CopyVector(&OtherNewSphereCenter);
+                  DoLog(1) && (Log() << Verbose(1) << "INFO: NewPlaneCenter is " << NewPlaneCenter << "." << endl);
+
+                  try {
+                    NewNormalVector = Plane(*(CandidateLine.BaseLine->endpoints[0]->node->node),
+                                            *(CandidateLine.BaseLine->endpoints[1]->node->node),
+                                            *(Candidate->node)).getNormal();
+                    DoLog(1) && (Log() << Verbose(1) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl);
+                    radius = CandidateLine.BaseLine->endpoints[0]->node->node->DistanceSquared(NewPlaneCenter);
+                    DoLog(1) && (Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl);
+                    DoLog(1) && (Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl);
+                    DoLog(1) && (Log() << Verbose(1) << "INFO: Radius of CircumCenterCircle is " << radius << "." << endl);
+                    if (radius < RADIUS * RADIUS) {
+                      otherradius = CandidateLine.BaseLine->endpoints[1]->node->node->DistanceSquared(NewPlaneCenter);
+                      if (fabs(radius - otherradius) < HULLEPSILON) {
+                        // construct both new centers
+                        NewSphereCenter = NewPlaneCenter;
+                        OtherNewSphereCenter= NewPlaneCenter;
+                        helper = NewNormalVector;
+                        helper.Scale(sqrt(RADIUS * RADIUS - radius));
+                        DoLog(2) && (Log() << Verbose(2) << "INFO: Distance of NewPlaneCenter " << NewPlaneCenter << " to either NewSphereCenter is " << helper.Norm() << " of vector " << helper << " with sphere radius " << RADIUS << "." << endl);
+                        NewSphereCenter += helper;
+                        DoLog(2) && (Log() << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl);
+                        // OtherNewSphereCenter is created by the same vector just in the other direction
+                        helper.Scale(-1.);
+                        OtherNewSphereCenter += helper;
+                        DoLog(2) && (Log() << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl);
+                        alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
+                        Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
+                        if ((ThirdPoint != NULL) && (Candidate == ThirdPoint->node)) { // in that case only the other circlecenter is valid
+                          if (OldSphereCenter.DistanceSquared(NewSphereCenter) < OldSphereCenter.DistanceSquared(OtherNewSphereCenter))
+                            alpha = Otheralpha;
+                        } else
+                          alpha = min(alpha, Otheralpha);
+                        // if there is a better candidate, drop the current list and add the new candidate
+                        // otherwise ignore the new candidate and keep the list
+                        if (CandidateLine.ShortestAngle > (alpha - HULLEPSILON)) {
+                          if (fabs(alpha - Otheralpha) > MYEPSILON) {
+                            CandidateLine.OptCenter = NewSphereCenter;
+                            CandidateLine.OtherOptCenter = OtherNewSphereCenter;
+                          } else {
+                            CandidateLine.OptCenter = OtherNewSphereCenter;
+                            CandidateLine.OtherOptCenter = NewSphereCenter;
+                          }
+                          // if there is an equal candidate, add it to the list without clearing the list
+                          if ((CandidateLine.ShortestAngle - HULLEPSILON) < alpha) {
+                            CandidateLine.pointlist.push_back(Candidate);
+                            DoLog(0) && (Log() << Verbose(0) << "ACCEPT: We have found an equally good candidate: " << *(Candidate) << " with " << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl);
+                          } else {
+                            // remove all candidates from the list and then the list itself
+                            CandidateLine.pointlist.clear();
+                            CandidateLine.pointlist.push_back(Candidate);
+                            DoLog(0) && (Log() << Verbose(0) << "ACCEPT: We have found a better candidate: " << *(Candidate) << " with " << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl);
+                          }
+                          CandidateLine.ShortestAngle = alpha;
+                          DoLog(0) && (Log() << Verbose(0) << "INFO: There are " << CandidateLine.pointlist.size() << " candidates in the list now." << endl);
                         } else {
-                          CandidateLine.OptCenter.CopyVector(&OtherNewSphereCenter);
-                          CandidateLine.OtherOptCenter.CopyVector(&NewSphereCenter);
+                          if ((Candidate != NULL) && (CandidateLine.pointlist.begin() != CandidateLine.pointlist.end())) {
+                            DoLog(1) && (Log() << Verbose(1) << "REJECT: Old candidate " << *(*CandidateLine.pointlist.begin()) << " with " << CandidateLine.ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl);
+                          } else {
+                            DoLog(1) && (Log() << Verbose(1) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl);
+                          }
                         }
-                        // if there is an equal candidate, add it to the list without clearing the list
-                        if ((CandidateLine.ShortestAngle - HULLEPSILON) < alpha) {
-                          CandidateLine.pointlist.push_back(Candidate);
-                          Log() << Verbose(0) << "ACCEPT: We have found an equally good candidate: " << *(Candidate) << " with "
-                            << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
-                        } else {
-                          // remove all candidates from the list and then the list itself
-                          CandidateLine.pointlist.clear();
-                          CandidateLine.pointlist.push_back(Candidate);
-                          Log() << Verbose(0) << "ACCEPT: We have found a better candidate: " << *(Candidate) << " with "
-                            << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
-                        }
-                        CandidateLine.ShortestAngle = alpha;
-                        Log() << Verbose(0) << "INFO: There are " << CandidateLine.pointlist.size() << " candidates in the list now." << endl;
                       } else {
-                        if ((Candidate != NULL) && (CandidateLine.pointlist.begin() != CandidateLine.pointlist.end())) {
-                          Log() << Verbose(1) << "REJECT: Old candidate " << *(Candidate) << " with " << CandidateLine.ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
-                        } else {
-                          Log() << Verbose(1) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
-                        }
+                        DoLog(1) && (Log() << Verbose(1) << "REJECT: Distance to center of circumcircle is not the same from each corner of the triangle: " << fabs(radius - otherradius) << endl);
                       }
                     } else {
-                      Log() << Verbose(1) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
+                      DoLog(1) && (Log() << Verbose(1) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl);
                     }
-                  } else {
+                  }
+                  catch (LinearDependenceException &excp){
+                    Log() << Verbose(1) << excp;
                     Log() << Verbose(1) << "REJECT: Three points from " << *CandidateLine.BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
                   }
                 } else {
-                  if (ThirdNode != NULL) {
-                    Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
+                  if (ThirdPoint != NULL) {
+                    DoLog(1) && (Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " and " << *ThirdPoint << " contains Candidate " << *Candidate << "." << endl);
                   } else {
-                    Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " contains Candidate " << *Candidate << "." << endl;
+                    DoLog(1) && (Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " contains Candidate " << *Candidate << "." << endl);
                   }
                 }
@@ -3057,19 +3323,25 @@
           }
     } else {
-      eLog() << Verbose(1) << "The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl);
     }
   } else {
-    if (ThirdNode != NULL)
-      Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
+    if (ThirdPoint != NULL)
+      DoLog(1) && (Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and third node " << *ThirdPoint << " is too big!" << endl);
     else
-      Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " is too big!" << endl;
-  }
-
-  Log() << Verbose(1) << "INFO: Sorting candidate list ..." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " is too big!" << endl);
+  }
+
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Sorting candidate list ..." << endl);
   if (CandidateLine.pointlist.size() > 1) {
     CandidateLine.pointlist.unique();
     CandidateLine.pointlist.sort(); //SortCandidates);
   }
-};
+
+  if ((!CandidateLine.pointlist.empty()) && (!CandidateLine.CheckValidity(RADIUS, LC))) {
+    DoeLog(0) && (eLog() << Verbose(0) << "There were other points contained in the rolling sphere as well!" << endl);
+    performCriticalExit();
+  }
+}
+;
 
 /** Finds the endpoint two lines are sharing.
@@ -3080,5 +3352,5 @@
 class BoundaryPointSet *Tesselation::GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   const BoundaryLineSet * lines[2] = { line1, line2 };
   class BoundaryPointSet *node = NULL;
@@ -3087,20 +3359,17 @@
   for (int i = 0; i < 2; i++)
     // for both lines
-    for (int j = 0; j < 2; j++)
-      { // for both endpoints
-        OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
-            lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
-        if (!OrderTest.second)
-          { // if insertion fails, we have common endpoint
-            node = OrderTest.first->second;
-            Log() << Verbose(1) << "Common endpoint of lines " << *line1
-                << " and " << *line2 << " is: " << *node << "." << endl;
-            j = 2;
-            i = 2;
-            break;
-          }
+    for (int j = 0; j < 2; j++) { // for both endpoints
+      OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
+      if (!OrderTest.second) { // if insertion fails, we have common endpoint
+        node = OrderTest.first->second;
+        DoLog(1) && (Log() << Verbose(1) << "Common endpoint of lines " << *line1 << " and " << *line2 << " is: " << *node << "." << endl);
+        j = 2;
+        i = 2;
+        break;
       }
+    }
   return node;
-};
+}
+;
 
 /** Finds the boundary points that are closest to a given Vector \a *x.
@@ -3116,5 +3385,5 @@
 
   if (LinesOnBoundary.empty()) {
-    eLog() << Verbose(1) << "There is no tesselation structure to compare the point with, please create one first." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "There is no tesselation structure to compare the point with, please create one first." << endl);
     return NULL;
   }
@@ -3122,8 +3391,7 @@
   // gather all points close to the desired one
   LC->SetIndexToVector(x); // ignore status as we calculate bounds below sensibly
-  for(int i=0;i<NDIM;i++) // store indices of this cell
+  for (int i = 0; i < NDIM; i++) // store indices of this cell
     N[i] = LC->n[i];
-  Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
-
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl);
   DistanceToPointMap * points = new DistanceToPointMap;
   LC->GetNeighbourBounds(Nlower, Nupper);
@@ -3132,16 +3400,16 @@
     for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
       for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-        const LinkedNodes *List = LC->GetCurrentCell();
+        const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
         //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
         if (List != NULL) {
-          for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+          for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
             FindPoint = PointsOnBoundary.find((*Runner)->nr);
             if (FindPoint != PointsOnBoundary.end()) {
-              points->insert(DistanceToPointPair (FindPoint->second->node->node->DistanceSquared(x), FindPoint->second) );
-              Log() << Verbose(1) << "INFO: Putting " << *FindPoint->second << " into the list." << endl;
+              points->insert(DistanceToPointPair(FindPoint->second->node->node->DistanceSquared(*x), FindPoint->second));
+              DoLog(1) && (Log() << Verbose(1) << "INFO: Putting " << *FindPoint->second << " into the list." << endl);
             }
           }
         } else {
-          eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
+          DoeLog(1) && (eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl);
         }
       }
@@ -3149,10 +3417,11 @@
   // check whether we found some points
   if (points->empty()) {
-    eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
-    delete(points);
+    DoeLog(1) && (eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl);
+    delete (points);
     return NULL;
   }
   return points;
-};
+}
+;
 
 /** Finds the boundary line that is closest to a given Vector \a *x.
@@ -3164,14 +3433,13 @@
 {
   Info FunctionInfo(__func__);
-
   // get closest points
-  DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x,LC);
+  DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x, LC);
   if (points == NULL) {
-    eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl);
     return NULL;
   }
 
   // for each point, check its lines, remember closest
-  Log() << Verbose(1) << "Finding closest BoundaryLine to " << *x << " ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Finding closest BoundaryLine to " << *x << " ... " << endl);
   BoundaryLineSet *ClosestLine = NULL;
   double MinDistance = -1.;
@@ -3182,44 +3450,38 @@
     for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
       // calculate closest point on line to desired point
-      helper.CopyVector((LineRunner->second)->endpoints[0]->node->node);
-      helper.AddVector((LineRunner->second)->endpoints[1]->node->node);
-      helper.Scale(0.5);
-      Center.CopyVector(x);
-      Center.SubtractVector(&helper);
-      BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
-      BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
-      Center.ProjectOntoPlane(&BaseLine);
+      helper = 0.5 * ((*(LineRunner->second)->endpoints[0]->node->node) +
+                      (*(LineRunner->second)->endpoints[1]->node->node));
+      Center = (*x) - helper;
+      BaseLine = (*(LineRunner->second)->endpoints[0]->node->node) -
+                 (*(LineRunner->second)->endpoints[1]->node->node);
+      Center.ProjectOntoPlane(BaseLine);
       const double distance = Center.NormSquared();
       if ((ClosestLine == NULL) || (distance < MinDistance)) {
         // additionally calculate intersection on line (whether it's on the line section or not)
-        helper.CopyVector(x);
-        helper.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
-        helper.SubtractVector(&Center);
-        const double lengthA = helper.ScalarProduct(&BaseLine);
-        helper.CopyVector(x);
-        helper.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
-        helper.SubtractVector(&Center);
-        const double lengthB = helper.ScalarProduct(&BaseLine);
-        if (lengthB*lengthA < 0) {  // if have different sign
+        helper = (*x) - (*(LineRunner->second)->endpoints[0]->node->node) - Center;
+        const double lengthA = helper.ScalarProduct(BaseLine);
+        helper = (*x) - (*(LineRunner->second)->endpoints[1]->node->node) - Center;
+        const double lengthB = helper.ScalarProduct(BaseLine);
+        if (lengthB * lengthA < 0) { // if have different sign
           ClosestLine = LineRunner->second;
           MinDistance = distance;
-          Log() << Verbose(1) << "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl);
         } else {
-          Log() << Verbose(1) << "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << "." << endl);
         }
       } else {
-        Log() << Verbose(1) << "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << "." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << "." << endl);
       }
     }
   }
-  delete(points);
+  delete (points);
   // check whether closest line is "too close" :), then it's inside
   if (ClosestLine == NULL) {
-    Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl);
     return NULL;
   }
   return ClosestLine;
-};
-
+}
+;
 
 /** Finds the triangle that is closest to a given Vector \a *x.
@@ -3230,15 +3492,14 @@
 TriangleList * Tesselation::FindClosestTrianglesToVector(const Vector *x, const LinkedCell* LC) const
 {
-	Info FunctionInfo(__func__);
-
-	// get closest points
-	DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x,LC);
+  Info FunctionInfo(__func__);
+  // get closest points
+  DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x, LC);
   if (points == NULL) {
-    eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl);
     return NULL;
   }
 
   // for each point, check its lines, remember closest
-  Log() << Verbose(1) << "Finding closest BoundaryTriangle to " << *x << " ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Finding closest BoundaryTriangle to " << *x << " ... " << endl);
   LineSet ClosestLines;
   double MinDistance = 1e+16;
@@ -3250,17 +3511,15 @@
     for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
 
-      BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
-      BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
+      BaseLine = (*(LineRunner->second)->endpoints[0]->node->node) -
+                 (*(LineRunner->second)->endpoints[1]->node->node);
       const double lengthBase = BaseLine.NormSquared();
 
-      BaseLineIntersection.CopyVector(x);
-      BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
+      BaseLineIntersection = (*x) - (*(LineRunner->second)->endpoints[0]->node->node);
       const double lengthEndA = BaseLineIntersection.NormSquared();
 
-      BaseLineIntersection.CopyVector(x);
-      BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
+      BaseLineIntersection = (*x) - (*(LineRunner->second)->endpoints[1]->node->node);
       const double lengthEndB = BaseLineIntersection.NormSquared();
 
-      if ((lengthEndA > lengthBase) || (lengthEndB > lengthBase) || ((lengthEndA < MYEPSILON) || (lengthEndB < MYEPSILON))) {  // intersection would be outside, take closer endpoint
+      if ((lengthEndA > lengthBase) || (lengthEndB > lengthBase) || ((lengthEndA < MYEPSILON) || (lengthEndB < MYEPSILON))) { // intersection would be outside, take closer endpoint
         const double lengthEnd = Min(lengthEndA, lengthEndB);
         if (lengthEnd - MinDistance < -MYEPSILON) { // new best line
@@ -3268,37 +3527,36 @@
           ClosestLines.insert(LineRunner->second);
           MinDistance = lengthEnd;
-          Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[0]->node << " is closer with " << lengthEnd << "." << endl;
-        } else if  (fabs(lengthEnd - MinDistance) < MYEPSILON) { // additional best candidate
+          DoLog(1) && (Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[0]->node << " is closer with " << lengthEnd << "." << endl);
+        } else if (fabs(lengthEnd - MinDistance) < MYEPSILON) { // additional best candidate
           ClosestLines.insert(LineRunner->second);
-          Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[1]->node << " is equally good with " << lengthEnd << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[1]->node << " is equally good with " << lengthEnd << "." << endl);
         } else { // line is worse
-          Log() << Verbose(1) << "REJECT: Line " << *LineRunner->second << " to either endpoints is further away than present closest line candidate: " << lengthEndA << ", " << lengthEndB << ", and distance is longer than baseline:" << lengthBase << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "REJECT: Line " << *LineRunner->second << " to either endpoints is further away than present closest line candidate: " << lengthEndA << ", " << lengthEndB << ", and distance is longer than baseline:" << lengthBase << "." << endl);
         }
       } else { // intersection is closer, calculate
         // calculate closest point on line to desired point
-        BaseLineIntersection.CopyVector(x);
-        BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
-        Center.CopyVector(&BaseLineIntersection);
-        Center.ProjectOntoPlane(&BaseLine);
-        BaseLineIntersection.SubtractVector(&Center);
+        BaseLineIntersection = (*x) - (*(LineRunner->second)->endpoints[1]->node->node);
+        Center = BaseLineIntersection;
+        Center.ProjectOntoPlane(BaseLine);
+        BaseLineIntersection -= Center;
         const double distance = BaseLineIntersection.NormSquared();
         if (Center.NormSquared() > BaseLine.NormSquared()) {
-          eLog() << Verbose(0) << "Algorithmic error: In second case we have intersection outside of baseline!" << endl;
+          DoeLog(0) && (eLog() << Verbose(0) << "Algorithmic error: In second case we have intersection outside of baseline!" << endl);
         }
         if ((ClosestLines.empty()) || (distance < MinDistance)) {
           ClosestLines.insert(LineRunner->second);
           MinDistance = distance;
-          Log() << Verbose(1) << "ACCEPT: Intersection in between endpoints, new closest line " << *LineRunner->second << " is " << *ClosestLines.begin() << " with projected distance " << MinDistance << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "ACCEPT: Intersection in between endpoints, new closest line " << *LineRunner->second << " is " << *ClosestLines.begin() << " with projected distance " << MinDistance << "." << endl);
         } else {
-          Log() << Verbose(2) << "REJECT: Point is further away from line " << *LineRunner->second << " than present closest line: " << distance << " >> " << MinDistance << "." << endl;
+          DoLog(2) && (Log() << Verbose(2) << "REJECT: Point is further away from line " << *LineRunner->second << " than present closest line: " << distance << " >> " << MinDistance << "." << endl);
         }
       }
     }
   }
-  delete(points);
+  delete (points);
 
   // check whether closest line is "too close" :), then it's inside
   if (ClosestLines.empty()) {
-    Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl);
     return NULL;
   }
@@ -3306,8 +3564,9 @@
   for (LineSet::iterator LineRunner = ClosestLines.begin(); LineRunner != ClosestLines.end(); LineRunner++)
     for (TriangleMap::iterator Runner = (*LineRunner)->triangles.begin(); Runner != (*LineRunner)->triangles.end(); Runner++) {
-    candidates->push_back(Runner->second);
-  }
+      candidates->push_back(Runner->second);
+    }
   return candidates;
-};
+}
+;
 
 /** Finds closest triangle to a point.
@@ -3315,9 +3574,10 @@
  * \param *out output stream for debugging
  * \param *x Vector to look from
+ * \param &distance contains found distance on return
  * \return list of BoundaryTriangleSet of nearest triangles or NULL.
  */
 class BoundaryTriangleSet * Tesselation::FindClosestTriangleToVector(const Vector *x, const LinkedCell* LC) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   class BoundaryTriangleSet *result = NULL;
   TriangleList *triangles = FindClosestTrianglesToVector(x, LC);
@@ -3330,22 +3590,22 @@
 
   // go through all and pick the one with the best alignment to x
-  double MinAlignment = 2.*M_PI;
+  double MinAlignment = 2. * M_PI;
   for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++) {
     (*Runner)->GetCenter(&Center);
-    helper.CopyVector(x);
-    helper.SubtractVector(&Center);
-    const double Alignment = helper.Angle(&(*Runner)->NormalVector);
+    helper = (*x) - Center;
+    const double Alignment = helper.Angle((*Runner)->NormalVector);
     if (Alignment < MinAlignment) {
       result = *Runner;
       MinAlignment = Alignment;
-      Log() << Verbose(1) << "ACCEPT: Triangle " << *result << " is better aligned with " << MinAlignment << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "ACCEPT: Triangle " << *result << " is better aligned with " << MinAlignment << "." << endl);
     } else {
-      Log() << Verbose(1) << "REJECT: Triangle " << *result << " is worse aligned with " << MinAlignment << "." << endl;
-    }
-  }
-  delete(triangles);
+      DoLog(1) && (Log() << Verbose(1) << "REJECT: Triangle " << *result << " is worse aligned with " << MinAlignment << "." << endl);
+    }
+  }
+  delete (triangles);
 
   return result;
-};
+}
+;
 
 /** Checks whether the provided Vector is within the Tesselation structure.
@@ -3358,6 +3618,10 @@
 bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell* const LC) const
 {
-  return (GetDistanceSquaredToSurface(Point, LC) < MYEPSILON);
-}
+  Info FunctionInfo(__func__);
+  TriangleIntersectionList Intersections(&Point, this, LC);
+
+  return Intersections.IsInside();
+}
+;
 
 /** Returns the distance to the surface given by the tesselation.
@@ -3389,29 +3653,26 @@
 
   if (triangle == NULL) {// is boundary point or only point in point cloud?
-    Log() << Verbose(1) << "No triangle given!" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "No triangle given!" << endl);
     return -1.;
   } else {
-    Log() << Verbose(1) << "INFO: Closest triangle found is " << *triangle << " with normal vector " << triangle->NormalVector << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Closest triangle found is " << *triangle << " with normal vector " << triangle->NormalVector << "." << endl);
   }
 
   triangle->GetCenter(&Center);
-  Log() << Verbose(2) << "INFO: Central point of the triangle is " << Center << "." << endl;
-  DistanceToCenter.CopyVector(&Center);
-  DistanceToCenter.SubtractVector(&Point);
-  Log() << Verbose(2) << "INFO: Vector from point to test to center is " << DistanceToCenter << "." << endl;
+  DoLog(2) && (Log() << Verbose(2) << "INFO: Central point of the triangle is " << Center << "." << endl);
+  DistanceToCenter = Center - Point;
+  DoLog(2) && (Log() << Verbose(2) << "INFO: Vector from point to test to center is " << DistanceToCenter << "." << endl);
 
   // check whether we are on boundary
-  if (fabs(DistanceToCenter.ScalarProduct(&triangle->NormalVector)) < MYEPSILON) {
+  if (fabs(DistanceToCenter.ScalarProduct(triangle->NormalVector)) < MYEPSILON) {
     // calculate whether inside of triangle
-    DistanceToCenter.CopyVector(&Point);
-    Center.CopyVector(&Point);
-    Center.SubtractVector(&triangle->NormalVector); // points towards MolCenter
-    DistanceToCenter.AddVector(&triangle->NormalVector); // points outside
-    Log() << Verbose(1) << "INFO: Calling Intersection with " << Center << " and " << DistanceToCenter << "." << endl;
+    DistanceToCenter = Point + triangle->NormalVector; // points outside
+    Center = Point - triangle->NormalVector; // points towards MolCenter
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Calling Intersection with " << Center << " and " << DistanceToCenter << "." << endl);
     if (triangle->GetIntersectionInsideTriangle(&Center, &DistanceToCenter, &Intersection)) {
-      Log() << Verbose(1) << Point << " is inner point: sufficiently close to boundary, " << Intersection << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << Point << " is inner point: sufficiently close to boundary, " << Intersection << "." << endl);
       return 0.;
     } else {
-      Log() << Verbose(1) << Point << " is NOT an inner point: on triangle plane but outside of triangle bounds." << endl;
+      DoLog(1) && (Log() << Verbose(1) << Point << " is NOT an inner point: on triangle plane but outside of triangle bounds." << endl);
       return false;
     }
@@ -3419,18 +3680,19 @@
     // calculate smallest distance
     distance = triangle->GetClosestPointInsideTriangle(&Point, &Intersection);
-    Log() << Verbose(1) << "Closest point on triangle is " << Intersection << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Closest point on triangle is " << Intersection << "." << endl);
 
     // then check direction to boundary
-    if (DistanceToCenter.ScalarProduct(&triangle->NormalVector) > MYEPSILON) {
-      Log() << Verbose(1) << Point << " is an inner point, " << distance << " below surface." << endl;
+    if (DistanceToCenter.ScalarProduct(triangle->NormalVector) > MYEPSILON) {
+      DoLog(1) && (Log() << Verbose(1) << Point << " is an inner point, " << distance << " below surface." << endl);
       return -distance;
     } else {
-      Log() << Verbose(1) << Point << " is NOT an inner point, " << distance << " above surface." << endl;
+      DoLog(1) && (Log() << Verbose(1) << Point << " is NOT an inner point, " << distance << " above surface." << endl);
       return +distance;
     }
   }
-};
-
-/** Calculates distance to a tesselated surface.
+}
+;
+
+/** Calculates minimum distance from \a&Point to a tesselated surface.
  * Combines \sa FindClosestTrianglesToVector() and \sa GetDistanceSquaredToTriangle().
  * \param &Point point to calculate distance from
@@ -3438,10 +3700,27 @@
  * \return distance squared to closest point on surface
  */
-double Tesselation::GetDistanceSquaredToSurface(const Vector &Point, const LinkedCell* const LC) const
-{
-  BoundaryTriangleSet *triangle = FindClosestTriangleToVector(&Point, LC);
-  const double distance = GetDistanceSquaredToTriangle(Point, triangle);
-  return Min(distance, LC->RADIUS);
-};
+double Tesselation::GetDistanceToSurface(const Vector &Point, const LinkedCell* const LC) const
+{
+  Info FunctionInfo(__func__);
+  TriangleIntersectionList Intersections(&Point, this, LC);
+
+  return Intersections.GetSmallestDistance();
+}
+;
+
+/** Calculates minimum distance from \a&Point to a tesselated surface.
+ * Combines \sa FindClosestTrianglesToVector() and \sa GetDistanceSquaredToTriangle().
+ * \param &Point point to calculate distance from
+ * \param *LC needed for finding closest points fast
+ * \return distance squared to closest point on surface
+ */
+BoundaryTriangleSet * Tesselation::GetClosestTriangleOnSurface(const Vector &Point, const LinkedCell* const LC) const
+{
+  Info FunctionInfo(__func__);
+  TriangleIntersectionList Intersections(&Point, this, LC);
+
+  return Intersections.GetClosestTriangle();
+}
+;
 
 /** Gets all points connected to the provided point by triangulation lines.
@@ -3453,10 +3732,9 @@
 TesselPointSet * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
 {
-	Info FunctionInfo(__func__);
-	TesselPointSet *connectedPoints = new TesselPointSet;
+  Info FunctionInfo(__func__);
+  TesselPointSet *connectedPoints = new TesselPointSet;
   class BoundaryPointSet *ReferencePoint = NULL;
   TesselPoint* current;
   bool takePoint = false;
-
   // find the respective boundary point
   PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
@@ -3464,5 +3742,5 @@
     ReferencePoint = PointRunner->second;
   } else {
-    eLog() << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
+    DoeLog(2) && (eLog() << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl);
     ReferencePoint = NULL;
   }
@@ -3470,5 +3748,6 @@
   // little trick so that we look just through lines connect to the BoundaryPoint
   // OR fall-back to look through all lines if there is no such BoundaryPoint
-  const LineMap *Lines;;
+  const LineMap *Lines;
+  ;
   if (ReferencePoint != NULL)
     Lines = &(ReferencePoint->lines);
@@ -3477,30 +3756,30 @@
   LineMap::const_iterator findLines = Lines->begin();
   while (findLines != Lines->end()) {
-   takePoint = false;
-
-   if (findLines->second->endpoints[0]->Nr == Point->nr) {
-     takePoint = true;
-     current = findLines->second->endpoints[1]->node;
-   } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
-     takePoint = true;
-     current = findLines->second->endpoints[0]->node;
-   }
-
-   if (takePoint) {
-     Log() << Verbose(1) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
-     connectedPoints->insert(current);
-   }
-
-   findLines++;
+    takePoint = false;
+
+    if (findLines->second->endpoints[0]->Nr == Point->nr) {
+      takePoint = true;
+      current = findLines->second->endpoints[1]->node;
+    } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
+      takePoint = true;
+      current = findLines->second->endpoints[0]->node;
+    }
+
+    if (takePoint) {
+      DoLog(1) && (Log() << Verbose(1) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl);
+      connectedPoints->insert(current);
+    }
+
+    findLines++;
   }
 
   if (connectedPoints->empty()) { // if have not found any points
-    eLog() << Verbose(1) << "We have not found any connected points to " << *Point<< "." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "We have not found any connected points to " << *Point << "." << endl);
     return NULL;
   }
 
   return connectedPoints;
-};
-
+}
+;
 
 /** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
@@ -3518,5 +3797,5 @@
 TesselPointList * Tesselation::GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   map<double, TesselPoint*> anglesOfPoints;
   TesselPointList *connectedCircle = new TesselPointList;
@@ -3525,10 +3804,10 @@
   Vector OrthogonalVector;
   Vector helper;
-  const TesselPoint * const TrianglePoints[3] = {Point, NULL, NULL};
+  const TesselPoint * const TrianglePoints[3] = { Point, NULL, NULL };
   TriangleList *triangles = NULL;
 
   if (SetOfNeighbours == NULL) {
-    eLog() << Verbose(2) << "Could not find any connected points!" << endl;
-    delete(connectedCircle);
+    DoeLog(2) && (eLog() << Verbose(2) << "Could not find any connected points!" << endl);
+    delete (connectedCircle);
     return NULL;
   }
@@ -3538,47 +3817,44 @@
   if ((triangles != NULL) && (!triangles->empty())) {
     for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
-      PlaneNormal.AddVector(&(*Runner)->NormalVector);
+      PlaneNormal += (*Runner)->NormalVector;
   } else {
-    eLog() << Verbose(0) << "Could not find any triangles for point " << *Point << "." << endl;
+    DoeLog(0) && (eLog() << Verbose(0) << "Could not find any triangles for point " << *Point << "." << endl);
     performCriticalExit();
   }
-  PlaneNormal.Scale(1.0/triangles->size());
-  Log() << Verbose(1) << "INFO: Calculated PlaneNormal of all circle points is " << PlaneNormal << "." << endl;
+  PlaneNormal.Scale(1.0 / triangles->size());
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Calculated PlaneNormal of all circle points is " << PlaneNormal << "." << endl);
   PlaneNormal.Normalize();
 
   // construct one orthogonal vector
   if (Reference != NULL) {
-    AngleZero.CopyVector(Reference);
-    AngleZero.SubtractVector(Point->node);
-    AngleZero.ProjectOntoPlane(&PlaneNormal);
-  }
-  if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
-    Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
-    AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
-    AngleZero.SubtractVector(Point->node);
-    AngleZero.ProjectOntoPlane(&PlaneNormal);
+    AngleZero = (*Reference) - (*Point->node);
+    AngleZero.ProjectOntoPlane(PlaneNormal);
+  }
+  if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON)) {
+    DoLog(1) && (Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl);
+    AngleZero = (*(*SetOfNeighbours->begin())->node) - (*Point->node);
+    AngleZero.ProjectOntoPlane(PlaneNormal);
     if (AngleZero.NormSquared() < MYEPSILON) {
-      eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
+      DoeLog(0) && (eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl);
       performCriticalExit();
     }
   }
-  Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl);
   if (AngleZero.NormSquared() > MYEPSILON)
-    OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
+    OrthogonalVector = Plane(PlaneNormal, AngleZero,0).getNormal();
   else
-    OrthogonalVector.MakeNormalVector(&PlaneNormal);
-  Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
+    OrthogonalVector.MakeNormalTo(PlaneNormal);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl);
 
   // go through all connected points and calculate angle
   for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
-    helper.CopyVector((*listRunner)->node);
-    helper.SubtractVector(Point->node);
-    helper.ProjectOntoPlane(&PlaneNormal);
+    helper = (*(*listRunner)->node) - (*Point->node);
+    helper.ProjectOntoPlane(PlaneNormal);
     double angle = GetAngle(helper, AngleZero, OrthogonalVector);
-    Log() << Verbose(0) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
-    anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
-  }
-
-  for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
+    DoLog(0) && (Log() << Verbose(0) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl);
+    anglesOfPoints.insert(pair<double, TesselPoint*> (angle, (*listRunner)));
+  }
+
+  for (map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
     connectedCircle->push_back(AngleRunner->second);
   }
@@ -3610,6 +3886,6 @@
 
   if (SetOfNeighbours == NULL) {
-    eLog() << Verbose(2) << "Could not find any connected points!" << endl;
-    delete(connectedCircle);
+    DoeLog(2) && (eLog() << Verbose(2) << "Could not find any connected points!" << endl);
+    delete (connectedCircle);
     return NULL;
   }
@@ -3622,7 +3898,6 @@
   }
 
-  Log() << Verbose(1) << "INFO: Point is " << *Point << " and Reference is " << *Reference << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Point is " << *Point << " and Reference is " << *Reference << "." << endl);
   // calculate central point
-
   TesselPointSet::const_iterator TesselA = SetOfNeighbours->begin();
   TesselPointSet::const_iterator TesselB = SetOfNeighbours->begin();
@@ -3633,64 +3908,63 @@
   int counter = 0;
   while (TesselC != SetOfNeighbours->end()) {
-    helper.MakeNormalVector((*TesselA)->node, (*TesselB)->node, (*TesselC)->node);
-    Log() << Verbose(0) << "Making normal vector out of " << *(*TesselA) << ", " << *(*TesselB) << " and " << *(*TesselC) << ":" << helper << endl;
+    helper = Plane(*((*TesselA)->node),
+                   *((*TesselB)->node),
+                   *((*TesselC)->node)).getNormal();
+    DoLog(0) && (Log() << Verbose(0) << "Making normal vector out of " << *(*TesselA) << ", " << *(*TesselB) << " and " << *(*TesselC) << ":" << helper << endl);
     counter++;
     TesselA++;
     TesselB++;
     TesselC++;
-    PlaneNormal.AddVector(&helper);
+    PlaneNormal += helper;
   }
   //Log() << Verbose(0) << "Summed vectors " << center << "; number of points " << connectedPoints.size()
   //  << "; scale factor " << counter;
-  PlaneNormal.Scale(1.0/(double)counter);
-//  Log() << Verbose(1) << "INFO: Calculated center of all circle points is " << center << "." << endl;
-//
-//  // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
-//  PlaneNormal.CopyVector(Point->node);
-//  PlaneNormal.SubtractVector(&center);
-//  PlaneNormal.Normalize();
-  Log() << Verbose(1) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
+  PlaneNormal.Scale(1.0 / (double) counter);
+  //  Log() << Verbose(1) << "INFO: Calculated center of all circle points is " << center << "." << endl;
+  //
+  //  // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
+  //  PlaneNormal.CopyVector(Point->node);
+  //  PlaneNormal.SubtractVector(&center);
+  //  PlaneNormal.Normalize();
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl);
 
   // construct one orthogonal vector
   if (Reference != NULL) {
-    AngleZero.CopyVector(Reference);
-    AngleZero.SubtractVector(Point->node);
-    AngleZero.ProjectOntoPlane(&PlaneNormal);
+    AngleZero = (*Reference) - (*Point->node);
+    AngleZero.ProjectOntoPlane(PlaneNormal);
   }
   if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
-    Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
-    AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
-    AngleZero.SubtractVector(Point->node);
-    AngleZero.ProjectOntoPlane(&PlaneNormal);
+    DoLog(1) && (Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl);
+    AngleZero = (*(*SetOfNeighbours->begin())->node) - (*Point->node);
+    AngleZero.ProjectOntoPlane(PlaneNormal);
     if (AngleZero.NormSquared() < MYEPSILON) {
-      eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
+      DoeLog(0) && (eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl);
       performCriticalExit();
     }
   }
-  Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl);
   if (AngleZero.NormSquared() > MYEPSILON)
-    OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
+    OrthogonalVector = Plane(PlaneNormal, AngleZero,0).getNormal();
   else
-    OrthogonalVector.MakeNormalVector(&PlaneNormal);
-  Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
+    OrthogonalVector.MakeNormalTo(PlaneNormal);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl);
 
   // go through all connected points and calculate angle
-  pair <map<double, TesselPoint*>::iterator, bool > InserterTest;
+  pair<map<double, TesselPoint*>::iterator, bool> InserterTest;
   for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
-    helper.CopyVector((*listRunner)->node);
-    helper.SubtractVector(Point->node);
-    helper.ProjectOntoPlane(&PlaneNormal);
+    helper = (*(*listRunner)->node) - (*Point->node);
+    helper.ProjectOntoPlane(PlaneNormal);
     double angle = GetAngle(helper, AngleZero, OrthogonalVector);
     if (angle > M_PI) // the correction is of no use here (and not desired)
-      angle = 2.*M_PI - angle;
-    Log() << Verbose(0) << "INFO: Calculated angle between " << helper << " and " << AngleZero << " is " << angle << " for point " << **listRunner << "." << endl;
-    InserterTest = anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
+      angle = 2. * M_PI - angle;
+    DoLog(0) && (Log() << Verbose(0) << "INFO: Calculated angle between " << helper << " and " << AngleZero << " is " << angle << " for point " << **listRunner << "." << endl);
+    InserterTest = anglesOfPoints.insert(pair<double, TesselPoint*> (angle, (*listRunner)));
     if (!InserterTest.second) {
-      eLog() << Verbose(0) << "GetCircleOfSetOfPoints() got two atoms with same angle: " << *((InserterTest.first)->second) << " and " << (*listRunner) << endl;
+      DoeLog(0) && (eLog() << Verbose(0) << "GetCircleOfSetOfPoints() got two atoms with same angle: " << *((InserterTest.first)->second) << " and " << (*listRunner) << endl);
       performCriticalExit();
     }
   }
 
-  for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
+  for (map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
     connectedCircle->push_back(AngleRunner->second);
   }
@@ -3707,7 +3981,7 @@
 ListOfTesselPointList * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   map<double, TesselPoint*> anglesOfPoints;
-  list< TesselPointList *> *ListOfPaths = new list< TesselPointList *>;
+  list<TesselPointList *> *ListOfPaths = new list<TesselPointList *> ;
   TesselPointList *connectedPath = NULL;
   Vector center;
@@ -3721,5 +3995,4 @@
   class BoundaryLineSet *CurrentLine = NULL;
   class BoundaryLineSet *StartLine = NULL;
-
   // find the respective boundary point
   PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
@@ -3727,16 +4000,16 @@
     ReferencePoint = PointRunner->second;
   } else {
-    eLog() << Verbose(1) << "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl);
     return NULL;
   }
 
-  map <class BoundaryLineSet *, bool> TouchedLine;
-  map <class BoundaryTriangleSet *, bool> TouchedTriangle;
-  map <class BoundaryLineSet *, bool>::iterator LineRunner;
-  map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
+  map<class BoundaryLineSet *, bool> TouchedLine;
+  map<class BoundaryTriangleSet *, bool> TouchedTriangle;
+  map<class BoundaryLineSet *, bool>::iterator LineRunner;
+  map<class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
   for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
-    TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
+    TouchedLine.insert(pair<class BoundaryLineSet *, bool> (Runner->second, false));
     for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
-      TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
+      TouchedTriangle.insert(pair<class BoundaryTriangleSet *, bool> (Sprinter->second, false));
   }
   if (!ReferencePoint->lines.empty()) {
@@ -3744,5 +4017,5 @@
       LineRunner = TouchedLine.find(runner->second);
       if (LineRunner == TouchedLine.end()) {
-        eLog() << Verbose(1) << "I could not find " << *runner->second << " in the touched list." << endl;
+        DoeLog(1) && (eLog() << Verbose(1) << "I could not find " << *runner->second << " in the touched list." << endl);
       } else if (!LineRunner->second) {
         LineRunner->second = true;
@@ -3752,13 +4025,13 @@
         StartLine = CurrentLine;
         CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
-        Log() << Verbose(1)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl);
         do {
           // push current one
-          Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl);
           connectedPath->push_back(CurrentPoint->node);
 
           // find next triangle
           for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
-            Log() << Verbose(1) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
+            DoLog(1) && (Log() << Verbose(1) << "INFO: Inspecting triangle " << *Runner->second << "." << endl);
             if ((Runner->second != triangle)) { // look for first triangle not equal to old one
               triangle = Runner->second;
@@ -3767,12 +4040,12 @@
                 if (!TriangleRunner->second) {
                   TriangleRunner->second = true;
-                  Log() << Verbose(1) << "INFO: Connecting triangle is " << *triangle << "." << endl;
+                  DoLog(1) && (Log() << Verbose(1) << "INFO: Connecting triangle is " << *triangle << "." << endl);
                   break;
                 } else {
-                  Log() << Verbose(1) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
+                  DoLog(1) && (Log() << Verbose(1) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl);
                   triangle = NULL;
                 }
               } else {
-                eLog() << Verbose(1) << "I could not find " << *triangle << " in the touched list." << endl;
+                DoeLog(1) && (eLog() << Verbose(1) << "I could not find " << *triangle << " in the touched list." << endl);
                 triangle = NULL;
               }
@@ -3782,8 +4055,8 @@
             break;
           // find next line
-          for (int i=0;i<3;i++) {
+          for (int i = 0; i < 3; i++) {
             if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
               CurrentLine = triangle->lines[i];
-              Log() << Verbose(1) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
+              DoLog(1) && (Log() << Verbose(1) << "INFO: Connecting line is " << *CurrentLine << "." << endl);
               break;
             }
@@ -3791,5 +4064,5 @@
           LineRunner = TouchedLine.find(CurrentLine);
           if (LineRunner == TouchedLine.end())
-            eLog() << Verbose(1) << "I could not find " << *CurrentLine << " in the touched list." << endl;
+            DoeLog(1) && (eLog() << Verbose(1) << "I could not find " << *CurrentLine << " in the touched list." << endl);
           else
             LineRunner->second = true;
@@ -3799,5 +4072,5 @@
         } while (CurrentLine != StartLine);
         // last point is missing, as it's on start line
-        Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl);
         if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
           connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
@@ -3805,9 +4078,9 @@
         ListOfPaths->push_back(connectedPath);
       } else {
-        Log() << Verbose(1) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl);
       }
     }
   } else {
-    eLog() << Verbose(1) << "There are no lines attached to " << *ReferencePoint << "." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "There are no lines attached to " << *ReferencePoint << "." << endl);
   }
 
@@ -3823,23 +4096,20 @@
 ListOfTesselPointList * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   list<TesselPointList *> *ListofPaths = GetPathsOfConnectedPoints(Point);
-  list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *>;
+  list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *> ;
   TesselPointList *connectedPath = NULL;
   TesselPointList *newPath = NULL;
   int count = 0;
-
-
   TesselPointList::iterator CircleRunner;
   TesselPointList::iterator CircleStart;
 
-  for(list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
+  for (list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
     connectedPath = *ListRunner;
 
-    Log() << Verbose(1) << "INFO: Current path is " << connectedPath << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Current path is " << connectedPath << "." << endl);
 
     // go through list, look for reappearance of starting Point and count
     CircleStart = connectedPath->begin();
-
     // go through list, look for reappearance of starting Point and create list
     TesselPointList::iterator Marker = CircleStart;
@@ -3847,12 +4117,12 @@
       if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
         // we have a closed circle from Marker to new Marker
-        Log() << Verbose(1) << count+1 << ". closed path consists of: ";
+        DoLog(1) && (Log() << Verbose(1) << count + 1 << ". closed path consists of: ");
         newPath = new TesselPointList;
         TesselPointList::iterator CircleSprinter = Marker;
         for (; CircleSprinter != CircleRunner; CircleSprinter++) {
           newPath->push_back(*CircleSprinter);
-          Log() << Verbose(0) << (**CircleSprinter) << " <-> ";
+          DoLog(0) && (Log() << Verbose(0) << (**CircleSprinter) << " <-> ");
         }
-        Log() << Verbose(0) << ".." << endl;
+        DoLog(0) && (Log() << Verbose(0) << ".." << endl);
         count++;
         Marker = CircleRunner;
@@ -3863,5 +4133,5 @@
     }
   }
-  Log() << Verbose(1) << "INFO: " << count << " closed additional path(s) have been created." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: " << count << " closed additional path(s) have been created." << endl);
 
   // delete list of paths
@@ -3869,12 +4139,12 @@
     connectedPath = *(ListofPaths->begin());
     ListofPaths->remove(connectedPath);
-    delete(connectedPath);
-  }
-  delete(ListofPaths);
+    delete (connectedPath);
+  }
+  delete (ListofPaths);
 
   // exit
   return ListofClosedPaths;
-};
-
+}
+;
 
 /** Gets all belonging triangles for a given BoundaryPointSet.
@@ -3885,20 +4155,20 @@
 TriangleSet *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
 {
-	Info FunctionInfo(__func__);
-	TriangleSet *connectedTriangles = new TriangleSet;
+  Info FunctionInfo(__func__);
+  TriangleSet *connectedTriangles = new TriangleSet;
 
   if (Point == NULL) {
-    eLog() << Verbose(1) << "Point given is NULL." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "Point given is NULL." << endl);
   } else {
     // go through its lines and insert all triangles
     for (LineMap::const_iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
       for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
-      connectedTriangles->insert(TriangleRunner->second);
-    }
+        connectedTriangles->insert(TriangleRunner->second);
+      }
   }
 
   return connectedTriangles;
-};
-
+}
+;
 
 /** Removes a boundary point from the envelope while keeping it closed.
@@ -3913,5 +4183,6 @@
  * \return volume added to the volume inside the tesselated surface by the removal
  */
-double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point) {
+double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point)
+{
   class BoundaryLineSet *line = NULL;
   class BoundaryTriangleSet *triangle = NULL;
@@ -3921,15 +4192,15 @@
 
   if (point == NULL) {
-    eLog() << Verbose(1) << "Cannot remove the point " << point << ", it's NULL!" << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "Cannot remove the point " << point << ", it's NULL!" << endl);
     return 0.;
   } else
-    Log() << Verbose(0) << "Removing point " << *point << " from tesselated boundary ..." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Removing point " << *point << " from tesselated boundary ..." << endl);
 
   // copy old location for the volume
-  OldPoint.CopyVector(point->node->node);
+  OldPoint = (*point->node->node);
 
   // get list of connected points
   if (point->lines.empty()) {
-    eLog() << Verbose(1) << "Cannot remove the point " << *point << ", it's connected to no lines!" << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "Cannot remove the point " << *point << ", it's connected to no lines!" << endl);
     return 0.;
   }
@@ -3940,5 +4211,5 @@
   // gather all triangles
   for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
-    count+=LineRunner->second->triangles.size();
+    count += LineRunner->second->triangles.size();
   TriangleMap Candidates;
   for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
@@ -3946,18 +4217,18 @@
     for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
       triangle = TriangleRunner->second;
-      Candidates.insert( TrianglePair (triangle->Nr, triangle) );
+      Candidates.insert(TrianglePair(triangle->Nr, triangle));
     }
   }
 
   // remove all triangles
-  count=0;
+  count = 0;
   NormalVector.Zero();
   for (TriangleMap::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
-    Log() << Verbose(1) << "INFO: Removing triangle " << *(Runner->second) << "." << endl;
-    NormalVector.SubtractVector(&Runner->second->NormalVector); // has to point inward
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Removing triangle " << *(Runner->second) << "." << endl);
+    NormalVector -= Runner->second->NormalVector; // has to point inward
     RemoveTesselationTriangle(Runner->second);
     count++;
   }
-  Log() << Verbose(1) << count << " triangles were removed." << endl;
+  DoLog(1) && (Log() << Verbose(1) << count << " triangles were removed." << endl);
 
   list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
@@ -3968,21 +4239,20 @@
   double smallestangle;
   Vector Point, Reference, OrthogonalVector;
-  if (count > 2) {  // less than three triangles, then nothing will be created
+  if (count > 2) { // less than three triangles, then nothing will be created
     class TesselPoint *TriangleCandidates[3];
     count = 0;
-    for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) {  // go through all closed paths
+    for (; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
       if (ListAdvance != ListOfClosedPaths->end())
         ListAdvance++;
 
       connectedPath = *ListRunner;
-
       // re-create all triangles by going through connected points list
       LineList NewLines;
-      for (;!connectedPath->empty();) {
+      for (; !connectedPath->empty();) {
         // search middle node with widest angle to next neighbours
         EndNode = connectedPath->end();
         smallestangle = 0.;
         for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
-          Log() << Verbose(1) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "INFO: MiddleNode is " << **MiddleNode << "." << endl);
           // construct vectors to next and previous neighbour
           StartNode = MiddleNode;
@@ -3991,6 +4261,5 @@
           StartNode--;
           //Log() << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
-          Point.CopyVector((*StartNode)->node);
-          Point.SubtractVector((*MiddleNode)->node);
+          Point = (*(*StartNode)->node) - (*(*MiddleNode)->node);
           StartNode = MiddleNode;
           StartNode++;
@@ -3998,19 +4267,17 @@
             StartNode = connectedPath->begin();
           //Log() << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
-          Reference.CopyVector((*StartNode)->node);
-          Reference.SubtractVector((*MiddleNode)->node);
-          OrthogonalVector.CopyVector((*MiddleNode)->node);
-          OrthogonalVector.SubtractVector(&OldPoint);
-          OrthogonalVector.MakeNormalVector(&Reference);
+          Reference = (*(*StartNode)->node) - (*(*MiddleNode)->node);
+          OrthogonalVector = (*(*MiddleNode)->node) - OldPoint;
+          OrthogonalVector.MakeNormalTo(Reference);
           angle = GetAngle(Point, Reference, OrthogonalVector);
           //if (angle < M_PI)  // no wrong-sided triangles, please?
-            if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) {  // get straightest angle (i.e. construct those triangles with smallest area first)
-              smallestangle = angle;
-              EndNode = MiddleNode;
-            }
+          if (fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
+            smallestangle = angle;
+            EndNode = MiddleNode;
+          }
         }
         MiddleNode = EndNode;
         if (MiddleNode == connectedPath->end()) {
-          eLog() << Verbose(0) << "CRITICAL: Could not find a smallest angle!" << endl;
+          DoeLog(0) && (eLog() << Verbose(0) << "CRITICAL: Could not find a smallest angle!" << endl);
           performCriticalExit();
         }
@@ -4022,8 +4289,8 @@
         if (EndNode == connectedPath->end())
           EndNode = connectedPath->begin();
-        Log() << Verbose(2) << "INFO: StartNode is " << **StartNode << "." << endl;
-        Log() << Verbose(2) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
-        Log() << Verbose(2) << "INFO: EndNode is " << **EndNode << "." << endl;
-        Log() << Verbose(1) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "INFO: StartNode is " << **StartNode << "." << endl);
+        DoLog(2) && (Log() << Verbose(2) << "INFO: MiddleNode is " << **MiddleNode << "." << endl);
+        DoLog(2) && (Log() << Verbose(2) << "INFO: EndNode is " << **EndNode << "." << endl);
+        DoLog(1) && (Log() << Verbose(1) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl);
         TriangleCandidates[0] = *StartNode;
         TriangleCandidates[1] = *MiddleNode;
@@ -4031,5 +4298,5 @@
         triangle = GetPresentTriangle(TriangleCandidates);
         if (triangle != NULL) {
-          eLog() << Verbose(0) << "New triangle already present, skipping!" << endl;
+          DoeLog(0) && (eLog() << Verbose(0) << "New triangle already present, skipping!" << endl);
           StartNode++;
           MiddleNode++;
@@ -4043,13 +4310,13 @@
           continue;
         }
-        Log() << Verbose(3) << "Adding new triangle points."<< endl;
+        DoLog(3) && (Log() << Verbose(3) << "Adding new triangle points." << endl);
         AddTesselationPoint(*StartNode, 0);
         AddTesselationPoint(*MiddleNode, 1);
         AddTesselationPoint(*EndNode, 2);
-        Log() << Verbose(3) << "Adding new triangle lines."<< endl;
-        AddTesselationLine(TPS[0], TPS[1], 0);
-        AddTesselationLine(TPS[0], TPS[2], 1);
+        DoLog(3) && (Log() << Verbose(3) << "Adding new triangle lines." << endl);
+        AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
+        AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
         NewLines.push_back(BLS[1]);
-        AddTesselationLine(TPS[1], TPS[2], 2);
+        AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
         BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
         BTS->GetNormalVector(NormalVector);
@@ -4062,5 +4329,5 @@
         // prepare nodes for next triangle
         StartNode = EndNode;
-        Log() << Verbose(2) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
+        DoLog(2) && (Log() << Verbose(2) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl);
         connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
         if (connectedPath->size() == 2) { // we are done
@@ -4069,5 +4336,5 @@
           break;
         } else if (connectedPath->size() < 2) { // something's gone wrong!
-          eLog() << Verbose(0) << "CRITICAL: There are only two endpoints left!" << endl;
+          DoeLog(0) && (eLog() << Verbose(0) << "CRITICAL: There are only two endpoints left!" << endl);
           performCriticalExit();
         } else {
@@ -4089,5 +4356,5 @@
         do {
           maxgain = 0;
-          for(LineList::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
+          for (LineList::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
             tmp = PickFarthestofTwoBaselines(*Runner);
             if (maxgain < tmp) {
@@ -4098,5 +4365,5 @@
           if (maxgain != 0) {
             volume += maxgain;
-            Log() << Verbose(1) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
+            DoLog(1) && (Log() << Verbose(1) << "Flipping baseline with highest volume" << **Candidate << "." << endl);
             OtherBase = FlipBaseline(*Candidate);
             NewLines.erase(Candidate);
@@ -4107,7 +4374,7 @@
 
       ListOfClosedPaths->remove(connectedPath);
-      delete(connectedPath);
-    }
-    Log() << Verbose(0) << count << " triangles were created." << endl;
+      delete (connectedPath);
+    }
+    DoLog(0) && (Log() << Verbose(0) << count << " triangles were created." << endl);
   } else {
     while (!ListOfClosedPaths->empty()) {
@@ -4115,16 +4382,15 @@
       connectedPath = *ListRunner;
       ListOfClosedPaths->remove(connectedPath);
-      delete(connectedPath);
-    }
-    Log() << Verbose(0) << "No need to create any triangles." << endl;
-  }
-  delete(ListOfClosedPaths);
-
-  Log() << Verbose(0) << "Removed volume is " << volume << "." << endl;
+      delete (connectedPath);
+    }
+    DoLog(0) && (Log() << Verbose(0) << "No need to create any triangles." << endl);
+  }
+  delete (ListOfClosedPaths);
+
+  DoLog(0) && (Log() << Verbose(0) << "Removed volume is " << volume << "." << endl);
 
   return volume;
-};
-
-
+}
+;
 
 /**
@@ -4138,6 +4404,6 @@
 TriangleList *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
 {
-	Info FunctionInfo(__func__);
-	TriangleList *result = new TriangleList;
+  Info FunctionInfo(__func__);
+  TriangleList *result = new TriangleList;
   LineMap::const_iterator FindLine;
   TriangleMap::const_iterator FindTriangle;
@@ -4163,12 +4429,9 @@
       for (int i = 0; i < 3; i++) {
         if (TrianglePoints[i] != NULL) {
-          for (int j = i+1; j < 3; j++) {
+          for (int j = i + 1; j < 3; j++) {
             if (TrianglePoints[j] != NULL) {
               for (FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr); // is a multimap!
-                  (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->nr);
-                  FindLine++) {
-                for (FindTriangle = FindLine->second->triangles.begin();
-                    FindTriangle != FindLine->second->triangles.end();
-                    FindTriangle++) {
+              (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->nr); FindLine++) {
+                for (FindTriangle = FindLine->second->triangles.begin(); FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
                   if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
                     result->push_back(FindTriangle->second);
@@ -4185,14 +4448,11 @@
     case 1: // copy all triangles of the respective line
     {
-      int i=0;
+      int i = 0;
       for (; i < 3; i++)
         if (TrianglePoints[i] == NULL)
           break;
-      for (FindLine = TrianglePoints[(i+1)%3]->lines.find(TrianglePoints[(i+2)%3]->node->nr); // is a multimap!
-          (FindLine != TrianglePoints[(i+1)%3]->lines.end()) && (FindLine->first == TrianglePoints[(i+2)%3]->node->nr);
-          FindLine++) {
-        for (FindTriangle = FindLine->second->triangles.begin();
-            FindTriangle != FindLine->second->triangles.end();
-            FindTriangle++) {
+      for (FindLine = TrianglePoints[(i + 1) % 3]->lines.find(TrianglePoints[(i + 2) % 3]->node->nr); // is a multimap!
+      (FindLine != TrianglePoints[(i + 1) % 3]->lines.end()) && (FindLine->first == TrianglePoints[(i + 2) % 3]->node->nr); FindLine++) {
+        for (FindTriangle = FindLine->second->triangles.begin(); FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
           if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
             result->push_back(FindTriangle->second);
@@ -4204,5 +4464,5 @@
     case 2: // copy all triangles of the respective point
     {
-      int i=0;
+      int i = 0;
       for (; i < 3; i++)
         if (TrianglePoints[i] != NULL)
@@ -4222,5 +4482,5 @@
     }
     default:
-      eLog() << Verbose(0) << "Number of wildcards is greater than 3, cannot happen!" << endl;
+      DoeLog(0) && (eLog() << Verbose(0) << "Number of wildcards is greater than 3, cannot happen!" << endl);
       performCriticalExit();
       break;
@@ -4230,6 +4490,8 @@
 }
 
-struct BoundaryLineSetCompare {
-  bool operator() (const BoundaryLineSet * const a, const BoundaryLineSet * const b) {
+struct BoundaryLineSetCompare
+{
+  bool operator()(const BoundaryLineSet * const a, const BoundaryLineSet * const b)
+  {
     int lowerNra = -1;
     int lowerNrb = -1;
@@ -4249,12 +4511,13 @@
     else if (a->endpoints[lowerNra] > b->endpoints[lowerNrb])
       return false;
-    else {  // both lower-numbered endpoints are the same ...
-     if (a->endpoints[(lowerNra+1)%2] < b->endpoints[(lowerNrb+1)%2])
-       return true;
-     else if (a->endpoints[(lowerNra+1)%2] > b->endpoints[(lowerNrb+1)%2])
-       return false;
+    else { // both lower-numbered endpoints are the same ...
+      if (a->endpoints[(lowerNra + 1) % 2] < b->endpoints[(lowerNrb + 1) % 2])
+        return true;
+      else if (a->endpoints[(lowerNra + 1) % 2] > b->endpoints[(lowerNrb + 1) % 2])
+        return false;
     }
     return false;
-  };
+  }
+  ;
 };
 
@@ -4269,21 +4532,20 @@
 IndexToIndex * Tesselation::FindAllDegeneratedLines()
 {
-	Info FunctionInfo(__func__);
-	UniqueLines AllLines;
+  Info FunctionInfo(__func__);
+  UniqueLines AllLines;
   IndexToIndex * DegeneratedLines = new IndexToIndex;
 
   // sanity check
   if (LinesOnBoundary.empty()) {
-    eLog() << Verbose(2) << "FindAllDegeneratedTriangles() was called without any tesselation structure.";
+    DoeLog(2) && (eLog() << Verbose(2) << "FindAllDegeneratedTriangles() was called without any tesselation structure.");
     return DegeneratedLines;
   }
-
   LineMap::iterator LineRunner1;
-  pair< UniqueLines::iterator, bool> tester;
+  pair<UniqueLines::iterator, bool> tester;
   for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
-    tester = AllLines.insert( LineRunner1->second );
+    tester = AllLines.insert(LineRunner1->second);
     if (!tester.second) { // found degenerated line
-      DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, (*tester.first)->Nr) );
-      DegeneratedLines->insert ( pair<int, int> ((*tester.first)->Nr, LineRunner1->second->Nr) );
+      DegeneratedLines->insert(pair<int, int> (LineRunner1->second->Nr, (*tester.first)->Nr));
+      DegeneratedLines->insert(pair<int, int> ((*tester.first)->Nr, LineRunner1->second->Nr));
     }
   }
@@ -4291,5 +4553,5 @@
   AllLines.clear();
 
-  Log() << Verbose(0) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl);
   IndexToIndex::iterator it;
   for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++) {
@@ -4297,7 +4559,7 @@
     const LineMap::const_iterator Line2 = LinesOnBoundary.find((*it).second);
     if (Line1 != LinesOnBoundary.end() && Line2 != LinesOnBoundary.end())
-      Log() << Verbose(0) << *Line1->second << " => " << *Line2->second << endl;
+      DoLog(0) && (Log() << Verbose(0) << *Line1->second << " => " << *Line2->second << endl);
     else
-      eLog() << Verbose(1) << "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!" << endl;
+      DoeLog(1) && (eLog() << Verbose(1) << "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!" << endl);
   }
 
@@ -4313,8 +4575,7 @@
 IndexToIndex * Tesselation::FindAllDegeneratedTriangles()
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   IndexToIndex * DegeneratedLines = FindAllDegeneratedLines();
   IndexToIndex * DegeneratedTriangles = new IndexToIndex;
-
   TriangleMap::iterator TriangleRunner1, TriangleRunner2;
   LineMap::iterator Liner;
@@ -4331,18 +4592,17 @@
     for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
       for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
-        if ((TriangleRunner1->second != TriangleRunner2->second)
-          && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
-          DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
-          DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
+        if ((TriangleRunner1->second != TriangleRunner2->second) && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
+          DegeneratedTriangles->insert(pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr));
+          DegeneratedTriangles->insert(pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr));
         }
       }
     }
   }
-  delete(DegeneratedLines);
-
-  Log() << Verbose(0) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
+  delete (DegeneratedLines);
+
+  DoLog(0) && (Log() << Verbose(0) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl);
   IndexToIndex::iterator it;
   for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
-      Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
+    DoLog(0) && (Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl);
 
   return DegeneratedTriangles;
@@ -4355,13 +4615,11 @@
 void Tesselation::RemoveDegeneratedTriangles()
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   IndexToIndex * DegeneratedTriangles = FindAllDegeneratedTriangles();
   TriangleMap::iterator finder;
   BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
-  int count  = 0;
-
-  for (IndexToIndex::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
-    TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
-  ) {
+  int count = 0;
+
+  for (IndexToIndex::iterator TriangleKeyRunner = DegeneratedTriangles->begin(); TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner) {
     finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
     if (finder != TrianglesOnBoundary.end())
@@ -4380,9 +4638,5 @@
         trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
 
-    if (trianglesShareLine
-      && (triangle->endpoints[1]->LinesCount > 2)
-      && (triangle->endpoints[2]->LinesCount > 2)
-      && (triangle->endpoints[0]->LinesCount > 2)
-    ) {
+    if (trianglesShareLine && (triangle->endpoints[1]->LinesCount > 2) && (triangle->endpoints[2]->LinesCount > 2) && (triangle->endpoints[0]->LinesCount > 2)) {
       // check whether we have to fix lines
       BoundaryTriangleSet *Othertriangle = NULL;
@@ -4404,6 +4658,6 @@
             // the line of triangle receives the degenerated ones
             triangle->lines[i]->triangles.erase(Othertriangle->Nr);
-            triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
-            for (int k=0;k<3;k++)
+            triangle->lines[i]->triangles.insert(TrianglePair(partnerTriangle->Nr, partnerTriangle));
+            for (int k = 0; k < 3; k++)
               if (triangle->lines[i] == Othertriangle->lines[k]) {
                 Othertriangle->lines[k] = partnerTriangle->lines[j];
@@ -4411,6 +4665,6 @@
               }
             // the line of partnerTriangle receives the non-degenerated ones
-            partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
-            partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
+            partnerTriangle->lines[j]->triangles.erase(partnerTriangle->Nr);
+            partnerTriangle->lines[j]->triangles.insert(TrianglePair(Othertriangle->Nr, Othertriangle));
             partnerTriangle->lines[j] = triangle->lines[i];
           }
@@ -4418,20 +4672,18 @@
       // erase the pair
       count += (int) DegeneratedTriangles->erase(triangle->Nr);
-      Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl);
       RemoveTesselationTriangle(triangle);
       count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
-      Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl);
       RemoveTesselationTriangle(partnerTriangle);
     } else {
-      Log() << Verbose(0) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
-        << " and its partner " << *partnerTriangle << " because it is essential for at"
-        << " least one of the endpoints to be kept in the tesselation structure." << endl;
-    }
-  }
-  delete(DegeneratedTriangles);
+      DoLog(0) && (Log() << Verbose(0) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle << " and its partner " << *partnerTriangle << " because it is essential for at" << " least one of the endpoints to be kept in the tesselation structure." << endl);
+    }
+  }
+  delete (DegeneratedTriangles);
   if (count > 0)
     LastTriangle = NULL;
 
-  Log() << Verbose(0) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl);
 }
 
@@ -4446,5 +4698,5 @@
 void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell *LC)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   // find nearest boundary point
   class TesselPoint *BackupPoint = NULL;
@@ -4459,8 +4711,8 @@
     NearestBoundaryPoint = PointRunner->second;
   } else {
-    eLog() << Verbose(1) << "I cannot find the boundary point." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "I cannot find the boundary point." << endl);
     return;
   }
-  Log() << Verbose(0) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl);
 
   // go through its lines and find the best one to split
@@ -4470,11 +4722,10 @@
   class BoundaryLineSet *BestLine = NULL;
   for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
-    BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
-    BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
-    CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
-    CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
-    CenterToPoint.Scale(0.5);
-    CenterToPoint.SubtractVector(point->node);
-    angle = CenterToPoint.Angle(&BaseLine);
+    BaseLine = (*Runner->second->endpoints[0]->node->node) -
+               (*Runner->second->endpoints[1]->node->node);
+    CenterToPoint = 0.5 * ((*Runner->second->endpoints[0]->node->node) +
+                           (*Runner->second->endpoints[1]->node->node));
+    CenterToPoint -= (*point->node);
+    angle = CenterToPoint.Angle(BaseLine);
     if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
       BestAngle = angle;
@@ -4487,5 +4738,5 @@
   BestLine->triangles.erase(TempTriangle->Nr);
   int nr = -1;
-  for (int i=0;i<3; i++) {
+  for (int i = 0; i < 3; i++) {
     if (TempTriangle->lines[i] == BestLine) {
       nr = i;
@@ -4495,45 +4746,46 @@
 
   // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
-  Log() << Verbose(2) << "Adding new triangle points."<< endl;
+  DoLog(2) && (Log() << Verbose(2) << "Adding new triangle points." << endl);
   AddTesselationPoint((BestLine->endpoints[0]->node), 0);
   AddTesselationPoint((BestLine->endpoints[1]->node), 1);
   AddTesselationPoint(point, 2);
-  Log() << Verbose(2) << "Adding new triangle lines."<< endl;
-  AddTesselationLine(TPS[0], TPS[1], 0);
-  AddTesselationLine(TPS[0], TPS[2], 1);
-  AddTesselationLine(TPS[1], TPS[2], 2);
+  DoLog(2) && (Log() << Verbose(2) << "Adding new triangle lines." << endl);
+  AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
+  AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
+  AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
   BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
   BTS->GetNormalVector(TempTriangle->NormalVector);
   BTS->NormalVector.Scale(-1.);
-  Log() << Verbose(1) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl);
   AddTesselationTriangle();
 
   // create other side of this triangle and close both new sides of the first created triangle
-  Log() << Verbose(2) << "Adding new triangle points."<< endl;
+  DoLog(2) && (Log() << Verbose(2) << "Adding new triangle points." << endl);
   AddTesselationPoint((BestLine->endpoints[0]->node), 0);
   AddTesselationPoint((BestLine->endpoints[1]->node), 1);
   AddTesselationPoint(point, 2);
-  Log() << Verbose(2) << "Adding new triangle lines."<< endl;
-  AddTesselationLine(TPS[0], TPS[1], 0);
-  AddTesselationLine(TPS[0], TPS[2], 1);
-  AddTesselationLine(TPS[1], TPS[2], 2);
+  DoLog(2) && (Log() << Verbose(2) << "Adding new triangle lines." << endl);
+  AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
+  AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
+  AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
   BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
   BTS->GetNormalVector(TempTriangle->NormalVector);
-  Log() << Verbose(1) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl);
   AddTesselationTriangle();
 
   // add removed triangle to the last open line of the second triangle
-  for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
+  for (int i = 0; i < 3; i++) { // look for the same line as BestLine (only it's its degenerated companion)
     if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
-      if (BestLine == BTS->lines[i]){
-        eLog() << Verbose(0) << "BestLine is same as found line, something's wrong here!" << endl;
+      if (BestLine == BTS->lines[i]) {
+        DoeLog(0) && (eLog() << Verbose(0) << "BestLine is same as found line, something's wrong here!" << endl);
         performCriticalExit();
       }
-      BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
+      BTS->lines[i]->triangles.insert(pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle));
       TempTriangle->lines[nr] = BTS->lines[i];
       break;
     }
   }
-};
+}
+;
 
 /** Writes the envelope to file.
@@ -4544,5 +4796,5 @@
 void Tesselation::Output(const char *filename, const PointCloud * const cloud)
 {
-	Info FunctionInfo(__func__);
+  Info FunctionInfo(__func__);
   ofstream *tempstream = NULL;
   string NameofTempFile;
@@ -4550,17 +4802,17 @@
 
   if (LastTriangle != NULL) {
-    sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
+    sprintf(NumberName, "-%04d-%s_%s_%s", (int) TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
     if (DoTecplotOutput) {
       string NameofTempFile(filename);
       NameofTempFile.append(NumberName);
-      for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
-      NameofTempFile.erase(npos, 1);
+      for (size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
+        NameofTempFile.erase(npos, 1);
       NameofTempFile.append(TecplotSuffix);
-      Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
+      DoLog(0) && (Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n");
       tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
       WriteTecplotFile(tempstream, this, cloud, TriangleFilesWritten);
       tempstream->close();
       tempstream->flush();
-      delete(tempstream);
+      delete (tempstream);
     }
 
@@ -4568,8 +4820,8 @@
       string NameofTempFile(filename);
       NameofTempFile.append(NumberName);
-      for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
-      NameofTempFile.erase(npos, 1);
+      for (size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
+        NameofTempFile.erase(npos, 1);
       NameofTempFile.append(Raster3DSuffix);
-      Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
+      DoLog(0) && (Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n");
       tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
       WriteRaster3dFile(tempstream, this, cloud);
@@ -4577,13 +4829,16 @@
       tempstream->close();
       tempstream->flush();
-      delete(tempstream);
+      delete (tempstream);
     }
   }
   if (DoTecplotOutput || DoRaster3DOutput)
     TriangleFilesWritten++;
-};
-
-struct BoundaryPolygonSetCompare {
-  bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const {
+}
+;
+
+struct BoundaryPolygonSetCompare
+{
+  bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const
+  {
     if (s1->endpoints.size() < s2->endpoints.size())
       return true;
@@ -4614,36 +4869,35 @@
 {
   Info FunctionInfo(__func__);
-
   /// 2. Go through all BoundaryPointSet's, check their triangles' NormalVector
   IndexToIndex *DegeneratedTriangles = FindAllDegeneratedTriangles();
-  set < BoundaryPointSet *> EndpointCandidateList;
-  pair < set < BoundaryPointSet *>::iterator, bool > InsertionTester;
-  pair < map < int, Vector *>::iterator, bool > TriangleInsertionTester;
+  set<BoundaryPointSet *> EndpointCandidateList;
+  pair<set<BoundaryPointSet *>::iterator, bool> InsertionTester;
+  pair<map<int, Vector *>::iterator, bool> TriangleInsertionTester;
   for (PointMap::const_iterator Runner = PointsOnBoundary.begin(); Runner != PointsOnBoundary.end(); Runner++) {
-    Log() << Verbose(0) << "Current point is " << *Runner->second << "." << endl;
-    map < int, Vector *> TriangleVectors;
+    DoLog(0) && (Log() << Verbose(0) << "Current point is " << *Runner->second << "." << endl);
+    map<int, Vector *> TriangleVectors;
     // gather all NormalVectors
-    Log() << Verbose(1) << "Gathering triangles ..." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Gathering triangles ..." << endl);
     for (LineMap::const_iterator LineRunner = (Runner->second)->lines.begin(); LineRunner != (Runner->second)->lines.end(); LineRunner++)
       for (TriangleMap::const_iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
         if (DegeneratedTriangles->find(TriangleRunner->second->Nr) == DegeneratedTriangles->end()) {
-          TriangleInsertionTester = TriangleVectors.insert( pair< int, Vector *> ((TriangleRunner->second)->Nr, &((TriangleRunner->second)->NormalVector)) );
+          TriangleInsertionTester = TriangleVectors.insert(pair<int, Vector *> ((TriangleRunner->second)->Nr, &((TriangleRunner->second)->NormalVector)));
           if (TriangleInsertionTester.second)
-            Log() << Verbose(1) << " Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list." << endl;
+            DoLog(1) && (Log() << Verbose(1) << " Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list." << endl);
         } else {
-          Log() << Verbose(1) << " NOT adding triangle " << *(TriangleRunner->second) << " as it's a simply degenerated one." << endl;
+          DoLog(1) && (Log() << Verbose(1) << " NOT adding triangle " << *(TriangleRunner->second) << " as it's a simply degenerated one." << endl);
         }
       }
     // check whether there are two that are parallel
-    Log() << Verbose(1) << "Finding two parallel triangles ..." << endl;
-    for (map < int, Vector *>::iterator VectorWalker = TriangleVectors.begin(); VectorWalker != TriangleVectors.end(); VectorWalker++)
-      for (map < int, Vector *>::iterator VectorRunner = VectorWalker; VectorRunner != TriangleVectors.end(); VectorRunner++)
+    DoLog(1) && (Log() << Verbose(1) << "Finding two parallel triangles ..." << endl);
+    for (map<int, Vector *>::iterator VectorWalker = TriangleVectors.begin(); VectorWalker != TriangleVectors.end(); VectorWalker++)
+      for (map<int, Vector *>::iterator VectorRunner = VectorWalker; VectorRunner != TriangleVectors.end(); VectorRunner++)
         if (VectorWalker != VectorRunner) { // skip equals
-          const double SCP = VectorWalker->second->ScalarProduct(VectorRunner->second);  // ScalarProduct should result in -1. for degenerated triangles
-          Log() << Verbose(1) << "Checking " << *VectorWalker->second<< " against " << *VectorRunner->second << ": " << SCP << endl;
+          const double SCP = VectorWalker->second->ScalarProduct(*VectorRunner->second); // ScalarProduct should result in -1. for degenerated triangles
+          DoLog(1) && (Log() << Verbose(1) << "Checking " << *VectorWalker->second << " against " << *VectorRunner->second << ": " << SCP << endl);
           if (fabs(SCP + 1.) < ParallelEpsilon) {
             InsertionTester = EndpointCandidateList.insert((Runner->second));
             if (InsertionTester.second)
-              Log() << Verbose(0) << " Adding " << *Runner->second << " to endpoint candidate list." << endl;
+              DoLog(0) && (Log() << Verbose(0) << " Adding " << *Runner->second << " to endpoint candidate list." << endl);
             // and break out of both loops
             VectorWalker = TriangleVectors.end();
@@ -4653,4 +4907,5 @@
         }
   }
+  delete DegeneratedTriangles;
 
   /// 3. Find connected endpoint candidates and put them into a polygon
@@ -4659,9 +4914,9 @@
   BoundaryPointSet *OtherWalker = NULL;
   BoundaryPolygonSet *Current = NULL;
-  stack <BoundaryPointSet*> ToCheckConnecteds;
+  stack<BoundaryPointSet*> ToCheckConnecteds;
   while (!EndpointCandidateList.empty()) {
     Walker = *(EndpointCandidateList.begin());
-    if (Current == NULL) {  // create a new polygon with current candidate
-      Log() << Verbose(0) << "Starting new polygon set at point " << *Walker << endl;
+    if (Current == NULL) { // create a new polygon with current candidate
+      DoLog(0) && (Log() << Verbose(0) << "Starting new polygon set at point " << *Walker << endl);
       Current = new BoundaryPolygonSet;
       Current->endpoints.insert(Walker);
@@ -4676,18 +4931,18 @@
       for (LineMap::const_iterator LineWalker = Walker->lines.begin(); LineWalker != Walker->lines.end(); LineWalker++) {
         OtherWalker = (LineWalker->second)->GetOtherEndpoint(Walker);
-        Log() << Verbose(1) << "Checking " << *OtherWalker << endl;
-        set < BoundaryPointSet *>::iterator Finder = EndpointCandidateList.find(OtherWalker);
-        if (Finder != EndpointCandidateList.end()) {  // found a connected partner
-          Log() << Verbose(1) << " Adding to polygon." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Checking " << *OtherWalker << endl);
+        set<BoundaryPointSet *>::iterator Finder = EndpointCandidateList.find(OtherWalker);
+        if (Finder != EndpointCandidateList.end()) { // found a connected partner
+          DoLog(1) && (Log() << Verbose(1) << " Adding to polygon." << endl);
           Current->endpoints.insert(OtherWalker);
-          EndpointCandidateList.erase(Finder);  // remove from candidates
-          ToCheckConnecteds.push(OtherWalker);  // but check its partners too
+          EndpointCandidateList.erase(Finder); // remove from candidates
+          ToCheckConnecteds.push(OtherWalker); // but check its partners too
         } else {
-          Log() << Verbose(1) << " is not connected to " << *Walker << endl;
+          DoLog(1) && (Log() << Verbose(1) << " is not connected to " << *Walker << endl);
         }
       }
     }
 
-    Log() << Verbose(0) << "Final polygon is " << *Current << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Final polygon is " << *Current << endl);
     ListofDegeneratedPolygons.insert(Current);
     Current = NULL;
@@ -4696,11 +4951,11 @@
   const int counter = ListofDegeneratedPolygons.size();
 
-  Log() << Verbose(0) << "The following " << counter << " degenerated polygons have been found: " << endl;
+  DoLog(0) && (Log() << Verbose(0) << "The following " << counter << " degenerated polygons have been found: " << endl);
   for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++)
-    Log() << Verbose(0) << " " << **PolygonRunner << endl;
+    DoLog(0) && (Log() << Verbose(0) << " " << **PolygonRunner << endl);
 
   /// 4. Go through all these degenerated polygons
   for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++) {
-    stack <int> TriangleNrs;
+    stack<int> TriangleNrs;
     Vector NormalVector;
     /// 4a. Gather all triangles of this polygon
@@ -4709,6 +4964,6 @@
     // check whether number is bigger than 2, otherwise it's just a simply degenerated one and nothing to do.
     if (T->size() == 2) {
-      Log() << Verbose(1) << " Skipping degenerated polygon, is just a (already simply degenerated) triangle." << endl;
-      delete(T);
+      DoLog(1) && (Log() << Verbose(1) << " Skipping degenerated polygon, is just a (already simply degenerated) triangle." << endl);
+      delete (T);
       continue;
     }
@@ -4719,12 +4974,11 @@
     // connections to either polygon ...
     if (T->size() % 2 != 0) {
-      eLog() << Verbose(0) << " degenerated polygon contains an odd number of triangles, probably contains bridging non-degenerated ones, too!" << endl;
+      DoeLog(0) && (eLog() << Verbose(0) << " degenerated polygon contains an odd number of triangles, probably contains bridging non-degenerated ones, too!" << endl);
       performCriticalExit();
     }
-
-    TriangleSet::iterator TriangleWalker = T->begin();  // is the inner iterator
+    TriangleSet::iterator TriangleWalker = T->begin(); // is the inner iterator
     /// 4a. Get NormalVector for one side (this is "front")
-    NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
-    Log() << Verbose(1) << "\"front\" defining triangle is " << **TriangleWalker << " and Normal vector of \"front\" side is " << NormalVector << endl;
+    NormalVector = (*TriangleWalker)->NormalVector;
+    DoLog(1) && (Log() << Verbose(1) << "\"front\" defining triangle is " << **TriangleWalker << " and Normal vector of \"front\" side is " << NormalVector << endl);
     TriangleWalker++;
     TriangleSet::iterator TriangleSprinter = TriangleWalker; // is the inner advanced iterator
@@ -4735,52 +4989,50 @@
       triangle = *TriangleWalker;
       TriangleSprinter++;
-      Log() << Verbose(1) << "Current triangle to test for removal: " << *triangle << endl;
-      if (triangle->NormalVector.ScalarProduct(&NormalVector) < 0) { // if from other side, then delete and remove from list
-        Log() << Verbose(1) << " Removing ... " << endl;
+      DoLog(1) && (Log() << Verbose(1) << "Current triangle to test for removal: " << *triangle << endl);
+      if (triangle->NormalVector.ScalarProduct(NormalVector) < 0) { // if from other side, then delete and remove from list
+        DoLog(1) && (Log() << Verbose(1) << " Removing ... " << endl);
         TriangleNrs.push(triangle->Nr);
         T->erase(TriangleWalker);
         RemoveTesselationTriangle(triangle);
       } else
-        Log() << Verbose(1) << " Keeping ... " << endl;
+        DoLog(1) && (Log() << Verbose(1) << " Keeping ... " << endl);
     }
     /// 4c. Copy all "front" triangles but with inverse NormalVector
     TriangleWalker = T->begin();
-    while (TriangleWalker != T->end()) {  // go through all front triangles
-      Log() << Verbose(1) << " Re-creating triangle " << **TriangleWalker << " with NormalVector " << (*TriangleWalker)->NormalVector << endl;
+    while (TriangleWalker != T->end()) { // go through all front triangles
+      DoLog(1) && (Log() << Verbose(1) << " Re-creating triangle " << **TriangleWalker << " with NormalVector " << (*TriangleWalker)->NormalVector << endl);
       for (int i = 0; i < 3; i++)
         AddTesselationPoint((*TriangleWalker)->endpoints[i]->node, i);
-      AddTesselationLine(TPS[0], TPS[1], 0);
-      AddTesselationLine(TPS[0], TPS[2], 1);
-      AddTesselationLine(TPS[1], TPS[2], 2);
+      AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
+      AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
+      AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
       if (TriangleNrs.empty())
-        eLog() << Verbose(0) << "No more free triangle numbers!" << endl;
+        DoeLog(0) && (eLog() << Verbose(0) << "No more free triangle numbers!" << endl);
       BTS = new BoundaryTriangleSet(BLS, TriangleNrs.top()); // copy triangle ...
       AddTesselationTriangle(); // ... and add
       TriangleNrs.pop();
-      BTS->NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
-      BTS->NormalVector.Scale(-1.);
+      BTS->NormalVector = -1 * (*TriangleWalker)->NormalVector;
       TriangleWalker++;
     }
     if (!TriangleNrs.empty()) {
-      eLog() << Verbose(0) << "There have been less triangles created than removed!" << endl;
-    }
-    delete(T);  // remove the triangleset
-  }
-
+      DoeLog(0) && (eLog() << Verbose(0) << "There have been less triangles created than removed!" << endl);
+    }
+    delete (T); // remove the triangleset
+  }
   IndexToIndex * SimplyDegeneratedTriangles = FindAllDegeneratedTriangles();
-  Log() << Verbose(0) << "Final list of simply degenerated triangles found, containing " << SimplyDegeneratedTriangles->size() << " triangles:" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Final list of simply degenerated triangles found, containing " << SimplyDegeneratedTriangles->size() << " triangles:" << endl);
   IndexToIndex::iterator it;
   for (it = SimplyDegeneratedTriangles->begin(); it != SimplyDegeneratedTriangles->end(); it++)
-      Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
-  delete(SimplyDegeneratedTriangles);
-
+    DoLog(0) && (Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl);
+  delete (SimplyDegeneratedTriangles);
   /// 5. exit
   UniquePolygonSet::iterator PolygonRunner;
   while (!ListofDegeneratedPolygons.empty()) {
     PolygonRunner = ListofDegeneratedPolygons.begin();
-    delete(*PolygonRunner);
+    delete (*PolygonRunner);
     ListofDegeneratedPolygons.erase(PolygonRunner);
   }
 
   return counter;
-};
+}
+;
Index: src/tesselation.hpp
===================================================================
--- src/tesselation.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/tesselation.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -43,5 +43,5 @@
 #define DoTecplotOutput 1
 #define DoRaster3DOutput 1
-#define DoVRMLOutput 1
+#define DoVRMLOutput 0
 #define TecplotSuffix ".dat"
 #define Raster3DSuffix ".r3d"
@@ -89,4 +89,6 @@
 
 #define ListOfTesselPointList list<list <TesselPoint *> *>
+
+enum centers {Opt, OtherOpt};
 
 /********************************************** declarations *******************************/
@@ -249,9 +251,14 @@
   public :
   CandidateForTesselation(BoundaryLineSet* currentBaseLine);
-  CandidateForTesselation(TesselPoint* candidate, BoundaryLineSet* currentBaseLine, Vector OptCandidateCenter, Vector OtherOptCandidateCenter);
+  CandidateForTesselation(TesselPoint* candidate, BoundaryLineSet* currentBaseLine, BoundaryPointSet *point, Vector OptCandidateCenter, Vector OtherOptCandidateCenter);
   ~CandidateForTesselation();
 
+  bool CheckValidity(const double RADIUS, const LinkedCell *LC) const;
+
   TesselPointList pointlist;
-  BoundaryLineSet *BaseLine;
+  const BoundaryLineSet * BaseLine;
+  const BoundaryPointSet * ThirdPoint;
+  const BoundaryTriangleSet *T;
+  Vector OldCenter;
   Vector OptCenter;
   Vector OtherOptCenter;
@@ -274,19 +281,24 @@
     void AddTesselationPoint(TesselPoint* Candidate, const int n);
     void SetTesselationPoint(TesselPoint* Candidate, const int n) const;
-    void AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n);
-    void AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n);
+    void AddTesselationLine(const Vector * const OptCenter, const BoundaryPointSet * const candidate, class BoundaryPointSet *a, class BoundaryPointSet *b, const int n);
+    void AddNewTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n);
+    void AddExistingTesselationTriangleLine(class BoundaryLineSet *FindLine, int n);
     void AddTesselationTriangle();
     void AddTesselationTriangle(const int nr);
-    void AddCandidateTriangle(CandidateForTesselation CandidateLine);
+    void AddCandidateTriangle(CandidateForTesselation &CandidateLine, enum centers type);
+    void AddDegeneratedTriangle(CandidateForTesselation &CandidateLine, const double RADIUS, const LinkedCell *LC);
+    void AddCandidatePolygon(CandidateForTesselation CandidateLine, const double RADIUS, const LinkedCell *LC);
     void RemoveTesselationTriangle(class BoundaryTriangleSet *triangle);
     void RemoveTesselationLine(class BoundaryLineSet *line);
     void RemoveTesselationPoint(class BoundaryPointSet *point);
+    bool CheckDegeneracy(CandidateForTesselation &CandidateLine, const double RADIUS, const LinkedCell *LC) const;
 
 
     // concave envelope
-    void FindStartingTriangle(const double RADIUS, const LinkedCell *LC);
+    bool FindStartingTriangle(const double RADIUS, const LinkedCell *LC);
     void FindSecondPointForTesselation(class TesselPoint* a, Vector Oben, class TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell *LC);
-    void FindThirdPointForTesselation(Vector &NormalVector, Vector &SearchDirection, Vector &OldSphereCenter, CandidateForTesselation &CandidateLine, const class TesselPoint  * const ThirdNode, const double RADIUS, const LinkedCell *LC) const;
-    bool FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC);
+    void FindThirdPointForTesselation(const Vector &NormalVector, const Vector &SearchDirection, const Vector &OldSphereCenter, CandidateForTesselation &CandidateLine, const class BoundaryPointSet  * const ThirdNode, const double RADIUS, const LinkedCell *LC) const;
+    bool FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, const BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC);
+    bool FindCandidatesforOpenLines(const double RADIUS, const LinkedCell *&LCList);
     int CheckPresenceOfTriangle(class TesselPoint *Candidates[3]) const;
     class BoundaryTriangleSet * GetPresentTriangle(TesselPoint *Candidates[3]);
@@ -318,5 +330,6 @@
     bool IsInnerPoint(const Vector &Point, const LinkedCell* const LC) const;
     double GetDistanceSquaredToTriangle(const Vector &Point, const BoundaryTriangleSet* const triangle) const;
-    double GetDistanceSquaredToSurface(const Vector &Point, const LinkedCell* const LC) const;
+    double GetDistanceToSurface(const Vector &Point, const LinkedCell* const LC) const;
+    BoundaryTriangleSet * GetClosestTriangleOnSurface(const Vector &Point, const LinkedCell* const LC) const;
     bool AddBoundaryPoint(TesselPoint * Walker, const int n);
     DistanceToPointMap * FindClosestBoundaryPointsToVector(const Vector *x, const LinkedCell* LC) const;
@@ -362,4 +375,5 @@
 
     //bool HasOtherBaselineBetterCandidate(const BoundaryLineSet * const BaseRay, const TesselPoint * const OptCandidate, double ShortestAngle, double RADIUS, const LinkedCell * const LC) const;
+    void FindDegeneratedCandidatesforOpenLines(TesselPoint * const Sprinter, const Vector * const OptCenter);
 };
 
Index: src/tesselationhelpers.cpp
===================================================================
--- src/tesselationhelpers.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/tesselationhelpers.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -14,4 +14,5 @@
 #include "tesselationhelpers.hpp"
 #include "vector.hpp"
+#include "vector_ops.hpp"
 #include "verbose.hpp"
 
@@ -27,5 +28,5 @@
   int signum;
   gsl_permutation *p = gsl_permutation_alloc(A->size1);
-  gsl_matrix *tmpA;
+  gsl_matrix *tmpA=0;
 
   if (inPlace)
@@ -53,40 +54,40 @@
 
   for(int i=0;i<3;i++) {
-    gsl_matrix_set(A, i, 0, a.x[i]);
-    gsl_matrix_set(A, i, 1, b.x[i]);
-    gsl_matrix_set(A, i, 2, c.x[i]);
+    gsl_matrix_set(A, i, 0, a[i]);
+    gsl_matrix_set(A, i, 1, b[i]);
+    gsl_matrix_set(A, i, 2, c[i]);
   }
   m11 = DetGet(A, 1);
 
   for(int i=0;i<3;i++) {
-    gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
-    gsl_matrix_set(A, i, 1, b.x[i]);
-    gsl_matrix_set(A, i, 2, c.x[i]);
+    gsl_matrix_set(A, i, 0, a[i]*a[i] + b[i]*b[i] + c[i]*c[i]);
+    gsl_matrix_set(A, i, 1, b[i]);
+    gsl_matrix_set(A, i, 2, c[i]);
   }
   m12 = DetGet(A, 1);
 
   for(int i=0;i<3;i++) {
-    gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
-    gsl_matrix_set(A, i, 1, a.x[i]);
-    gsl_matrix_set(A, i, 2, c.x[i]);
+    gsl_matrix_set(A, i, 0, a[i]*a[i] + b[i]*b[i] + c[i]*c[i]);
+    gsl_matrix_set(A, i, 1, a[i]);
+    gsl_matrix_set(A, i, 2, c[i]);
   }
   m13 = DetGet(A, 1);
 
   for(int i=0;i<3;i++) {
-    gsl_matrix_set(A, i, 0, a.x[i]*a.x[i] + b.x[i]*b.x[i] + c.x[i]*c.x[i]);
-    gsl_matrix_set(A, i, 1, a.x[i]);
-    gsl_matrix_set(A, i, 2, b.x[i]);
+    gsl_matrix_set(A, i, 0, a[i]*a[i] + b[i]*b[i] + c[i]*c[i]);
+    gsl_matrix_set(A, i, 1, a[i]);
+    gsl_matrix_set(A, i, 2, b[i]);
   }
   m14 = DetGet(A, 1);
 
   if (fabs(m11) < MYEPSILON)
-    eLog() << Verbose(1) << "three points are colinear." << endl;
-
-  center->x[0] =  0.5 * m12/ m11;
-  center->x[1] = -0.5 * m13/ m11;
-  center->x[2] =  0.5 * m14/ m11;
-
-  if (fabs(a.Distance(center) - RADIUS) > MYEPSILON)
-    eLog() << Verbose(1) << "The given center is further way by " << fabs(a.Distance(center) - RADIUS) << " from a than RADIUS." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "three points are colinear." << endl);
+
+  center->at(0) =  0.5 * m12/ m11;
+  center->at(1) = -0.5 * m13/ m11;
+  center->at(2) =  0.5 * m14/ m11;
+
+  if (fabs(a.distance(*center) - RADIUS) > MYEPSILON)
+    DoeLog(1) && (eLog()<< Verbose(1) << "The given center is further way by " << fabs(a.distance(*center) - RADIUS) << " from a than RADIUS." << endl);
 
   gsl_matrix_free(A);
@@ -120,37 +121,32 @@
   Vector OtherCenter;
   Center->Zero();
-  helper.CopyVector(&a);
-  helper.Scale(sin(2.*alpha));
-  Center->AddVector(&helper);
-  helper.CopyVector(&b);
-  helper.Scale(sin(2.*beta));
-  Center->AddVector(&helper);
-  helper.CopyVector(&c);
-  helper.Scale(sin(2.*gamma));
-  Center->AddVector(&helper);
+  helper = sin(2.*alpha) * a;
+  (*Center) += helper;
+  helper = sin(2.*beta) * b;
+  (*Center) += helper;
+  helper = sin(2.*gamma) * c;
+  (*Center) += helper;
   //*Center = a * sin(2.*alpha) + b * sin(2.*beta) + c * sin(2.*gamma) ;
   Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
-  NewUmkreismittelpunkt->CopyVector(Center);
-  Log() << Verbose(1) << "Center of new circumference is " << *NewUmkreismittelpunkt << ".\n";
+  (*NewUmkreismittelpunkt) = (*Center);
+  DoLog(1) && (Log() << Verbose(1) << "Center of new circumference is " << *NewUmkreismittelpunkt << ".\n");
   // Here we calculated center of circumscribing circle, using barycentric coordinates
-  Log() << Verbose(1) << "Center of circumference is " << *Center << " in direction " << *Direction << ".\n";
-
-  TempNormal.CopyVector(&a);
-  TempNormal.SubtractVector(&b);
-  helper.CopyVector(&a);
-  helper.SubtractVector(&c);
-  TempNormal.VectorProduct(&helper);
+  DoLog(1) && (Log() << Verbose(1) << "Center of circumference is " << *Center << " in direction " << *Direction << ".\n");
+
+  TempNormal = a - b;
+  helper = a - c;
+  TempNormal.VectorProduct(helper);
   if (fabs(HalfplaneIndicator) < MYEPSILON)
     {
-      if ((TempNormal.ScalarProduct(AlternativeDirection) <0 && AlternativeIndicator >0) || (TempNormal.ScalarProduct(AlternativeDirection) >0 && AlternativeIndicator <0))
+      if ((TempNormal.ScalarProduct(*AlternativeDirection) <0 && AlternativeIndicator >0) || (TempNormal.ScalarProduct(*AlternativeDirection) >0 && AlternativeIndicator <0))
         {
-          TempNormal.Scale(-1);
+          TempNormal *= -1;
         }
     }
   else
     {
-      if (((TempNormal.ScalarProduct(Direction)<0) && (HalfplaneIndicator >0)) || ((TempNormal.ScalarProduct(Direction)>0) && (HalfplaneIndicator<0)))
+      if (((TempNormal.ScalarProduct(*Direction)<0) && (HalfplaneIndicator >0)) || ((TempNormal.ScalarProduct(*Direction)>0) && (HalfplaneIndicator<0)))
         {
-          TempNormal.Scale(-1);
+          TempNormal *= -1;
         }
     }
@@ -158,12 +154,11 @@
   TempNormal.Normalize();
   Restradius = sqrt(RADIUS*RADIUS - Umkreisradius*Umkreisradius);
-  Log() << Verbose(1) << "Height of center of circumference to center of sphere is " << Restradius << ".\n";
+  DoLog(1) && (Log() << Verbose(1) << "Height of center of circumference to center of sphere is " << Restradius << ".\n");
   TempNormal.Scale(Restradius);
-  Log() << Verbose(1) << "Shift vector to sphere of circumference is " << TempNormal << ".\n";
-
-  Center->AddVector(&TempNormal);
-  Log() << Verbose(1) << "Center of sphere of circumference is " << *Center << ".\n";
+  DoLog(1) && (Log() << Verbose(1) << "Shift vector to sphere of circumference is " << TempNormal << ".\n");
+  (*Center) += TempNormal;
+  DoLog(1) && (Log() << Verbose(1) << "Center of sphere of circumference is " << *Center << ".\n");
   GetSphere(&OtherCenter, a, b, c, RADIUS);
-  Log() << Verbose(1) << "OtherCenter of sphere of circumference is " << OtherCenter << ".\n";
+  DoLog(1) && (Log() << Verbose(1) << "OtherCenter of sphere of circumference is " << OtherCenter << ".\n");
 };
 
@@ -180,29 +175,22 @@
   Vector helper;
   double alpha, beta, gamma;
-  Vector SideA, SideB, SideC;
-  SideA.CopyVector(b);
-  SideA.SubtractVector(&c);
-  SideB.CopyVector(c);
-  SideB.SubtractVector(&a);
-  SideC.CopyVector(a);
-  SideC.SubtractVector(&b);
-  alpha = M_PI - SideB.Angle(&SideC);
-  beta = M_PI - SideC.Angle(&SideA);
-  gamma = M_PI - SideA.Angle(&SideB);
+  Vector SideA = b - c;
+  Vector SideB = c - a;
+  Vector SideC = a - b;
+  alpha = M_PI - SideB.Angle(SideC);
+  beta = M_PI - SideC.Angle(SideA);
+  gamma = M_PI - SideA.Angle(SideB);
   //Log() << Verbose(1) << "INFO: alpha = " << alpha/M_PI*180. << ", beta = " << beta/M_PI*180. << ", gamma = " << gamma/M_PI*180. << "." << endl;
   if (fabs(M_PI - alpha - beta - gamma) > HULLEPSILON) {
-    eLog() << Verbose(1) << "GetCenterofCircumcircle: Sum of angles " << (alpha+beta+gamma)/M_PI*180. << " > 180 degrees by " << fabs(M_PI - alpha - beta - gamma)/M_PI*180. << "!" << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "GetCenterofCircumcircle: Sum of angles " << (alpha+beta+gamma)/M_PI*180. << " > 180 degrees by " << fabs(M_PI - alpha - beta - gamma)/M_PI*180. << "!" << endl);
   }
 
   Center->Zero();
-  helper.CopyVector(a);
-  helper.Scale(sin(2.*alpha));
-  Center->AddVector(&helper);
-  helper.CopyVector(b);
-  helper.Scale(sin(2.*beta));
-  Center->AddVector(&helper);
-  helper.CopyVector(c);
-  helper.Scale(sin(2.*gamma));
-  Center->AddVector(&helper);
+  helper = sin(2.*alpha) * a;
+  (*Center) += helper;
+  helper = sin(2.*beta) * b;
+  (*Center) += helper;
+  helper = sin(2.*gamma) * c;
+  (*Center) += helper;
   Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
 };
@@ -226,34 +214,30 @@
   Vector helper;
   double radius, alpha;
-  Vector RelativeOldSphereCenter;
-  Vector RelativeNewSphereCenter;
-
-  RelativeOldSphereCenter.CopyVector(&OldSphereCenter);
-  RelativeOldSphereCenter.SubtractVector(&CircleCenter);
-  RelativeNewSphereCenter.CopyVector(&NewSphereCenter);
-  RelativeNewSphereCenter.SubtractVector(&CircleCenter);
-  helper.CopyVector(&RelativeNewSphereCenter);
+
+  Vector RelativeOldSphereCenter = OldSphereCenter - CircleCenter;
+  Vector RelativeNewSphereCenter = NewSphereCenter - CircleCenter;
+  helper = RelativeNewSphereCenter;
   // test whether new center is on the parameter circle's plane
-  if (fabs(helper.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
-    eLog() << Verbose(1) << "Something's very wrong here: NewSphereCenter is not on the band's plane as desired by " <<fabs(helper.ScalarProduct(&CirclePlaneNormal))  << "!" << endl;
-    helper.ProjectOntoPlane(&CirclePlaneNormal);
+  if (fabs(helper.ScalarProduct(CirclePlaneNormal)) > HULLEPSILON) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Something's very wrong here: NewSphereCenter is not on the band's plane as desired by " <<fabs(helper.ScalarProduct(CirclePlaneNormal))  << "!" << endl);
+    helper.ProjectOntoPlane(CirclePlaneNormal);
   }
   radius = helper.NormSquared();
   // test whether the new center vector has length of CircleRadius
   if (fabs(radius - CircleRadius) > HULLEPSILON)
-    eLog() << Verbose(1) << "The projected center of the new sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
-  alpha = helper.Angle(&RelativeOldSphereCenter);
+    DoeLog(1) && (eLog()<< Verbose(1) << "The projected center of the new sphere has radius " << radius << " instead of " << CircleRadius << "." << endl);
+  alpha = helper.Angle(RelativeOldSphereCenter);
   // make the angle unique by checking the halfplanes/search direction
-  if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)  // acos is not unique on [0, 2.*M_PI), hence extra check to decide between two half intervals
+  if (helper.ScalarProduct(SearchDirection) < -HULLEPSILON)  // acos is not unique on [0, 2.*M_PI), hence extra check to decide between two half intervals
     alpha = 2.*M_PI - alpha;
-  Log() << Verbose(1) << "INFO: RelativeNewSphereCenter is " << helper << ", RelativeOldSphereCenter is " << RelativeOldSphereCenter << " and resulting angle is " << alpha << "." << endl;
-  radius = helper.Distance(&RelativeOldSphereCenter);
-  helper.ProjectOntoPlane(&NormalVector);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: RelativeNewSphereCenter is " << helper << ", RelativeOldSphereCenter is " << RelativeOldSphereCenter << " and resulting angle is " << alpha << "." << endl);
+  radius = helper.distance(RelativeOldSphereCenter);
+  helper.ProjectOntoPlane(NormalVector);
   // check whether new center is somewhat away or at least right over the current baseline to prevent intersecting triangles
   if ((radius > HULLEPSILON) || (helper.Norm() < HULLEPSILON)) {
-    Log() << Verbose(1) << "INFO: Distance between old and new center is " << radius << " and between new center and baseline center is " << helper.Norm() << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Distance between old and new center is " << radius << " and between new center and baseline center is " << helper.Norm() << "." << endl);
     return alpha;
   } else {
-    Log() << Verbose(1) << "INFO: NewSphereCenter " << RelativeNewSphereCenter << " is too close to RelativeOldSphereCenter" << RelativeOldSphereCenter << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: NewSphereCenter " << RelativeNewSphereCenter << " is too close to RelativeOldSphereCenter" << RelativeOldSphereCenter << "." << endl);
     return 2.*M_PI;
   }
@@ -279,21 +263,16 @@
   struct Intersection *I = (struct Intersection *)params;
   Vector intersection;
-  Vector SideA,SideB,HeightA, HeightB;
   for (int i=0;i<NDIM;i++)
-    intersection.x[i] = gsl_vector_get(x, i);
-
-  SideA.CopyVector(&(I->x1));
-  SideA.SubtractVector(&I->x2);
-  HeightA.CopyVector(&intersection);
-  HeightA.SubtractVector(&I->x1);
-  HeightA.ProjectOntoPlane(&SideA);
-
-  SideB.CopyVector(&I->x3);
-  SideB.SubtractVector(&I->x4);
-  HeightB.CopyVector(&intersection);
-  HeightB.SubtractVector(&I->x3);
-  HeightB.ProjectOntoPlane(&SideB);
-
-  retval = HeightA.ScalarProduct(&HeightA) + HeightB.ScalarProduct(&HeightB);
+    intersection[i] = gsl_vector_get(x, i);
+
+  Vector SideA = I->x1 -I->x2 ;
+  Vector HeightA = intersection - I->x1;
+  HeightA.ProjectOntoPlane(SideA);
+
+  Vector SideB = I->x3 - I->x4;
+  Vector HeightB = intersection - I->x3;
+  HeightB.ProjectOntoPlane(SideB);
+
+  retval = HeightA.ScalarProduct(HeightA) + HeightB.ScalarProduct(HeightB);
   //Log() << Verbose(1) << "MinIntersectDistance called, result: " << retval << endl;
 
@@ -320,8 +299,8 @@
 
   struct Intersection par;
-    par.x1.CopyVector(&point1);
-    par.x2.CopyVector(&point2);
-    par.x3.CopyVector(&point3);
-    par.x4.CopyVector(&point4);
+    par.x1 = point1;
+    par.x2 = point2;
+    par.x3 = point3;
+    par.x4 = point4;
 
     const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
@@ -336,7 +315,7 @@
     /* Starting point */
     x = gsl_vector_alloc(NDIM);
-    gsl_vector_set(x, 0, point1.x[0]);
-    gsl_vector_set(x, 1, point1.x[1]);
-    gsl_vector_set(x, 2, point1.x[2]);
+    gsl_vector_set(x, 0, point1[0]);
+    gsl_vector_set(x, 1, point1[1]);
+    gsl_vector_set(x, 2, point1[2]);
 
     /* Set initial step sizes to 1 */
@@ -364,28 +343,24 @@
 
         if (status == GSL_SUCCESS) {
-          Log() << Verbose(1) << "converged to minimum" <<  endl;
+          DoLog(1) && (Log() << Verbose(1) << "converged to minimum" <<  endl);
         }
     } while (status == GSL_CONTINUE && iter < 100);
 
     // check whether intersection is in between or not
-  Vector intersection, SideA, SideB, HeightA, HeightB;
+  Vector intersection;
   double t1, t2;
   for (int i = 0; i < NDIM; i++) {
-    intersection.x[i] = gsl_vector_get(s->x, i);
-  }
-
-  SideA.CopyVector(&par.x2);
-  SideA.SubtractVector(&par.x1);
-  HeightA.CopyVector(&intersection);
-  HeightA.SubtractVector(&par.x1);
-
-  t1 = HeightA.ScalarProduct(&SideA)/SideA.ScalarProduct(&SideA);
-
-  SideB.CopyVector(&par.x4);
-  SideB.SubtractVector(&par.x3);
-  HeightB.CopyVector(&intersection);
-  HeightB.SubtractVector(&par.x3);
-
-  t2 = HeightB.ScalarProduct(&SideB)/SideB.ScalarProduct(&SideB);
+    intersection[i] = gsl_vector_get(s->x, i);
+  }
+
+  Vector SideA = par.x2 - par.x1;
+  Vector HeightA = intersection - par.x1;
+
+  t1 = HeightA.ScalarProduct(SideA)/SideA.ScalarProduct(SideA);
+
+  Vector SideB = par.x4 - par.x3;
+  Vector HeightB = intersection - par.x3;
+
+  t2 = HeightB.ScalarProduct(SideB)/SideB.ScalarProduct(SideB);
 
   Log() << Verbose(1) << "Intersection " << intersection << " is at "
@@ -394,8 +369,8 @@
 
   if (((t1 >= 0) && (t1 <= 1)) && ((t2 >= 0) && (t2 <= 1))) {
-    Log() << Verbose(1) << "true intersection." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "true intersection." << endl);
     result = true;
   } else {
-    Log() << Verbose(1) << "intersection out of region of interest." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "intersection out of region of interest." << endl);
     result = false;
   }
@@ -427,10 +402,10 @@
   if (point.IsZero())
     return M_PI;
-  double phi = point.Angle(&reference);
-  if (OrthogonalVector.ScalarProduct(&point) > 0) {
+  double phi = point.Angle(reference);
+  if (OrthogonalVector.ScalarProduct(point) > 0) {
     phi = 2.*M_PI - phi;
   }
 
-  Log() << Verbose(1) << "INFO: " << point << " has angle " << phi << " with respect to reference " << reference << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: " << point << " has angle " << phi << " with respect to reference " << reference << "." << endl);
 
   return phi;
@@ -451,12 +426,12 @@
   double volume;
 
-  TetraederVector[0].CopyVector(a);
-  TetraederVector[1].CopyVector(b);
-  TetraederVector[2].CopyVector(c);
+  TetraederVector[0] = a;
+  TetraederVector[1] = b;
+  TetraederVector[2] = c;
   for (int j=0;j<3;j++)
-    TetraederVector[j].SubtractVector(&d);
-  Point.CopyVector(&TetraederVector[0]);
-  Point.VectorProduct(&TetraederVector[1]);
-  volume = 1./6. * fabs(Point.ScalarProduct(&TetraederVector[2]));
+    TetraederVector[j].SubtractVector(d);
+  Point = TetraederVector[0];
+  Point.VectorProduct(TetraederVector[1]);
+  volume = 1./6. * fabs(Point.ScalarProduct(TetraederVector[2]));
   return volume;
 };
@@ -479,5 +454,5 @@
     for (int j=i+1; j<3; j++) {
       if (nodes[i] == NULL) {
-        Log() << Verbose(1) << "Node nr. " << i << " is not yet present." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Node nr. " << i << " is not yet present." << endl);
         result = true;
       } else if (nodes[i]->lines.find(nodes[j]->node->nr) != nodes[i]->lines.end()) {  // there already is a line
@@ -493,10 +468,10 @@
         }
       } else { // no line
-        Log() << Verbose(1) << "The line between " << *nodes[i] << " and " << *nodes[j] << " is not yet present, hence no need for a degenerate triangle." << endl;
+        DoLog(1) && (Log() << Verbose(1) << "The line between " << *nodes[i] << " and " << *nodes[j] << " is not yet present, hence no need for a degenerate triangle." << endl);
         result = true;
       }
     }
   if ((!result) && (counter > 1)) {
-    Log() << Verbose(1) << "INFO: Degenerate triangle is ok, at least two, here " << counter << ", existing lines are used." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Degenerate triangle is ok, at least two, here " << counter << ", existing lines are used." << endl);
     result = true;
   }
@@ -512,5 +487,5 @@
 //  Vector BaseLineVector, OrthogonalVector, helper;
 //  if (candidate1->BaseLine != candidate2->BaseLine) {  // sanity check
-//    eLog() << Verbose(1) << "sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl;
+//    DoeLog(1) && (eLog()<< Verbose(1) << "sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl);
 //    //return false;
 //    exit(1);
@@ -571,5 +546,5 @@
   for(int i=0;i<NDIM;i++) // store indices of this cell
     N[i] = LC->n[i];
-  Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl);
 
   LC->GetNeighbourBounds(Nlower, Nupper);
@@ -578,10 +553,9 @@
     for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
       for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-        const LinkedNodes *List = LC->GetCurrentCell();
+        const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
         //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
         if (List != NULL) {
-          for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
-            helper.CopyVector(Point);
-            helper.SubtractVector((*Runner)->node);
+          for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+            helper = (*Point) - (*(*Runner)->node);
             double currentNorm = helper. Norm();
             if (currentNorm < distance) {
@@ -626,5 +600,5 @@
   for(int i=0;i<NDIM;i++) // store indices of this cell
     N[i] = LC->n[i];
-  Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl);
 
   LC->GetNeighbourBounds(Nlower, Nupper);
@@ -633,10 +607,9 @@
     for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
       for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-        const LinkedNodes *List = LC->GetCurrentCell();
+        const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
         //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
         if (List != NULL) {
-          for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
-            helper.CopyVector(Point);
-            helper.SubtractVector((*Runner)->node);
+          for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+            helper = (*Point) - (*(*Runner)->node);
             double currentNorm = helper.NormSquared();
             if (currentNorm < distance) {
@@ -659,8 +632,8 @@
   // output
   if (closestPoint != NULL) {
-    Log() << Verbose(1) << "Closest point is " << *closestPoint;
+    DoLog(1) && (Log() << Verbose(1) << "Closest point is " << *closestPoint);
     if (SecondPoint != NULL)
-      Log() << Verbose(0) << " and second closest is " << *SecondPoint;
-    Log() << Verbose(0) << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << " and second closest is " << *SecondPoint);
+    DoLog(0) && (Log() << Verbose(0) << "." << endl);
   }
   return closestPoint;
@@ -677,31 +650,24 @@
 	Info FunctionInfo(__func__);
   // construct the plane of the two baselines (i.e. take both their directional vectors)
-  Vector Normal;
-  Vector Baseline, OtherBaseline;
-  Baseline.CopyVector(Base->endpoints[1]->node->node);
-  Baseline.SubtractVector(Base->endpoints[0]->node->node);
-  OtherBaseline.CopyVector(OtherBase->endpoints[1]->node->node);
-  OtherBaseline.SubtractVector(OtherBase->endpoints[0]->node->node);
-  Normal.CopyVector(&Baseline);
-  Normal.VectorProduct(&OtherBaseline);
+  Vector Baseline = (*Base->endpoints[1]->node->node) - (*Base->endpoints[0]->node->node);
+  Vector OtherBaseline = (*OtherBase->endpoints[1]->node->node) - (*OtherBase->endpoints[0]->node->node);
+  Vector Normal = Baseline;
+  Normal.VectorProduct(OtherBaseline);
   Normal.Normalize();
-  Log() << Verbose(1) << "First direction is " << Baseline << ", second direction is " << OtherBaseline << ", normal of intersection plane is " << Normal << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "First direction is " << Baseline << ", second direction is " << OtherBaseline << ", normal of intersection plane is " << Normal << "." << endl);
 
   // project one offset point of OtherBase onto this plane (and add plane offset vector)
-  Vector NewOffset;
-  NewOffset.CopyVector(OtherBase->endpoints[0]->node->node);
-  NewOffset.SubtractVector(Base->endpoints[0]->node->node);
-  NewOffset.ProjectOntoPlane(&Normal);
-  NewOffset.AddVector(Base->endpoints[0]->node->node);
-  Vector NewDirection;
-  NewDirection.CopyVector(&NewOffset);
-  NewDirection.AddVector(&OtherBaseline);
+  Vector NewOffset = (*OtherBase->endpoints[0]->node->node) - (*Base->endpoints[0]->node->node);
+  NewOffset.ProjectOntoPlane(Normal);
+  NewOffset += (*Base->endpoints[0]->node->node);
+  Vector NewDirection = NewOffset + OtherBaseline;
 
   // calculate the intersection between this projected baseline and Base
   Vector *Intersection = new Vector;
-  Intersection->GetIntersectionOfTwoLinesOnPlane(Base->endpoints[0]->node->node, Base->endpoints[1]->node->node, &NewOffset, &NewDirection, &Normal);
-  Normal.CopyVector(Intersection);
-  Normal.SubtractVector(Base->endpoints[0]->node->node);
-  Log() << Verbose(1) << "Found closest point on " << *Base << " at " << *Intersection << ", factor in line is " << fabs(Normal.ScalarProduct(&Baseline)/Baseline.NormSquared()) << "." << endl;
+  *Intersection = GetIntersectionOfTwoLinesOnPlane(*(Base->endpoints[0]->node->node),
+                                                   *(Base->endpoints[1]->node->node),
+                                                     NewOffset, NewDirection);
+  Normal = (*Intersection) - (*Base->endpoints[0]->node->node);
+  DoLog(1) && (Log() << Verbose(1) << "Found closest point on " << *Base << " at " << *Intersection << ", factor in line is " << fabs(Normal.ScalarProduct(Baseline)/Baseline.NormSquared()) << "." << endl);
 
   return Intersection;
@@ -721,5 +687,5 @@
     return -1;
   }
-  distance = x->DistanceToPlane(&triangle->NormalVector, triangle->endpoints[0]->node->node);
+  distance = x->DistanceToPlane(triangle->NormalVector, *triangle->endpoints[0]->node->node);
   return distance;
 };
@@ -747,5 +713,5 @@
       *vrmlfile << "Sphere {" << endl << "  "; // 2 is sphere type
       for (i=0;i<NDIM;i++)
-        *vrmlfile << Walker->node->x[i]-center->x[i] << " ";
+        *vrmlfile << Walker->node->at(i)-center->at(i) << " ";
       *vrmlfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
       cloud->GoToNext();
@@ -757,5 +723,5 @@
       for (i=0;i<3;i++) { // print each node
         for (int j=0;j<NDIM;j++)  // and for each node all NDIM coordinates
-          *vrmlfile << TriangleRunner->second->endpoints[i]->node->node->x[j]-center->x[j] << " ";
+          *vrmlfile << TriangleRunner->second->endpoints[i]->node->node->at(j)-center->at(j) << " ";
         *vrmlfile << "\t";
       }
@@ -764,5 +730,5 @@
     }
   } else {
-    eLog() << Verbose(1) << "Given vrmlfile is " << vrmlfile << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Given vrmlfile is " << vrmlfile << "." << endl);
   }
   delete(center);
@@ -784,13 +750,12 @@
     Vector *center = cloud->GetCenter();
     // make the circumsphere's center absolute again
-    helper.CopyVector(Tess->LastTriangle->endpoints[0]->node->node);
-    helper.AddVector(Tess->LastTriangle->endpoints[1]->node->node);
-    helper.AddVector(Tess->LastTriangle->endpoints[2]->node->node);
-    helper.Scale(1./3.);
-    helper.SubtractVector(center);
+    Vector helper = (1./3.) * ((*Tess->LastTriangle->endpoints[0]->node->node) +
+                               (*Tess->LastTriangle->endpoints[1]->node->node) +
+                               (*Tess->LastTriangle->endpoints[2]->node->node));
+    helper -= (*center);
     // and add to file plus translucency object
     *rasterfile << "# current virtual sphere\n";
     *rasterfile << "8\n  25.0    0.6     -1.0 -1.0 -1.0     0.2        0 0 0 0\n";
-    *rasterfile << "2\n  " << helper.x[0] << " " << helper.x[1] << " " << helper.x[2] << "\t" << 5. << "\t1 0 0\n";
+    *rasterfile << "2\n  " << helper[0] << " " << helper[1] << " " << helper[2] << "\t" << 5. << "\t1 0 0\n";
     *rasterfile << "9\n  terminating special property\n";
     delete(center);
@@ -820,5 +785,5 @@
       *rasterfile << "2" << endl << "  ";  // 2 is sphere type
       for (i=0;i<NDIM;i++)
-        *rasterfile << Walker->node->x[i]-center->x[i] << " ";
+        *rasterfile << Walker->node->at(i)-center->at(i) << " ";
       *rasterfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
       cloud->GoToNext();
@@ -831,5 +796,5 @@
       for (i=0;i<3;i++) {  // print each node
         for (int j=0;j<NDIM;j++)  // and for each node all NDIM coordinates
-          *rasterfile << TriangleRunner->second->endpoints[i]->node->node->x[j]-center->x[j] << " ";
+          *rasterfile << TriangleRunner->second->endpoints[i]->node->node->at(j)-center->at(j) << " ";
         *rasterfile << "\t";
       }
@@ -839,5 +804,5 @@
     *rasterfile << "9\n#  terminating special property\n";
   } else {
-    eLog() << Verbose(1) << "Given rasterfile is " << rasterfile << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Given rasterfile is " << rasterfile << "." << endl);
   }
   IncludeSphereinRaster3D(rasterfile, Tess, cloud);
@@ -862,6 +827,10 @@
     } else {
       *tecplot << N << "-";
-      for (int i=0;i<3;i++)
-        *tecplot << (i==0 ? "" : "_") << TesselStruct->LastTriangle->endpoints[i]->node->Name;
+      if (TesselStruct->LastTriangle != NULL) {
+        for (int i=0;i<3;i++)
+          *tecplot << (i==0 ? "" : "_") << TesselStruct->LastTriangle->endpoints[i]->node->Name;
+      } else {
+        *tecplot << "none";
+      }
     }
     *tecplot << "\", N=" << TesselStruct->PointsOnBoundary.size() << ", E=" << TesselStruct->TrianglesOnBoundary.size() << ", DATAPACKING=POINT, ZONETYPE=FETRIANGLE" << endl;
@@ -877,11 +846,11 @@
       Walker = target->second->node;
       LookupList[Walker->nr] = Counter++;
-      *tecplot << Walker->node->x[0] << " " << Walker->node->x[1] << " " << Walker->node->x[2] << " " << target->second->value << endl;
+      *tecplot << Walker->node->at(0) << " " << Walker->node->at(1) << " " << Walker->node->at(2) << " " << target->second->value << endl;
     }
     *tecplot << endl;
     // print connectivity
-    Log() << Verbose(1) << "The following triangles were created:" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "The following triangles were created:" << endl);
     for (TriangleMap::const_iterator runner = TesselStruct->TrianglesOnBoundary.begin(); runner != TesselStruct->TrianglesOnBoundary.end(); runner++) {
-      Log() << Verbose(1) << " " << runner->second->endpoints[0]->node->Name << "<->" << runner->second->endpoints[1]->node->Name << "<->" << runner->second->endpoints[2]->node->Name << endl;
+      DoLog(1) && (Log() << Verbose(1) << " " << runner->second->endpoints[0]->node->Name << "<->" << runner->second->endpoints[1]->node->Name << "<->" << runner->second->endpoints[2]->node->Name << endl);
       *tecplot << LookupList[runner->second->endpoints[0]->node->nr] << " " << LookupList[runner->second->endpoints[1]->node->nr] << " " << LookupList[runner->second->endpoints[2]->node->nr] << endl;
     }
@@ -904,5 +873,5 @@
   for (PointMap::const_iterator PointRunner = TesselStruct->PointsOnBoundary.begin(); PointRunner != TesselStruct->PointsOnBoundary.end(); PointRunner++) {
     point = PointRunner->second;
-    Log() << Verbose(1) << "INFO: Current point is " << *point << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Current point is " << *point << "." << endl);
     point->value = 0;
     for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
@@ -928,13 +897,13 @@
   int counter = 0;
 
-  Log() << Verbose(1) << "Check: List of Baselines with not two connected triangles:" << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Check: List of Baselines with not two connected triangles:" << endl);
   for (testline = TesselStruct->LinesOnBoundary.begin(); testline != TesselStruct->LinesOnBoundary.end(); testline++) {
     if (testline->second->triangles.size() != 2) {
-      Log() << Verbose(2) << *testline->second << "\t" << testline->second->triangles.size() << endl;
+      DoLog(2) && (Log() << Verbose(2) << *testline->second << "\t" << testline->second->triangles.size() << endl);
       counter++;
     }
   }
   if (counter == 0) {
-    Log() << Verbose(1) << "None." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "None." << endl);
     result = true;
   }
@@ -951,5 +920,5 @@
   // check number of endpoints in *P
   if (P->endpoints.size() != 4) {
-    eLog() << Verbose(1) << "CountTrianglePairContainingPolygon works only on polygons with 4 nodes!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "CountTrianglePairContainingPolygon works only on polygons with 4 nodes!" << endl);
     return 0;
   }
@@ -957,9 +926,9 @@
   // check number of triangles in *T
   if (T->size() < 2) {
-    eLog() << Verbose(1) << "Not enough triangles to have pairs!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Not enough triangles to have pairs!" << endl);
     return 0;
   }
 
-  Log() << Verbose(0) << "Polygon is " << *P << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Polygon is " << *P << endl);
   // create each pair, get the endpoints and check whether *P is contained.
   int counter = 0;
@@ -977,14 +946,14 @@
         const int size = PairTrianglenodes.endpoints.size();
         if (size == 4) {
-          Log() << Verbose(0) << " Current pair of triangles: " << **Walker << "," << **PairWalker << " with " << size << " distinct endpoints:" << PairTrianglenodes << endl;
+          DoLog(0) && (Log() << Verbose(0) << " Current pair of triangles: " << **Walker << "," << **PairWalker << " with " << size << " distinct endpoints:" << PairTrianglenodes << endl);
           // now check
           if (PairTrianglenodes.ContainsPresentTupel(P)) {
             counter++;
-            Log() << Verbose(0) << "  ACCEPT: Matches with " << *P << endl;
+            DoLog(0) && (Log() << Verbose(0) << "  ACCEPT: Matches with " << *P << endl);
           } else {
-            Log() << Verbose(0) << "  REJECT: No match with " << *P << endl;
+            DoLog(0) && (Log() << Verbose(0) << "  REJECT: No match with " << *P << endl);
           }
         } else {
-          Log() << Verbose(0) << "  REJECT: Less than four endpoints." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "  REJECT: Less than four endpoints." << endl);
         }
       }
@@ -1007,5 +976,5 @@
     if (P2->ContainsBoundaryPoint((*Runner))) {
       counter++;
-      Log() << Verbose(1) << *(*Runner) << " of second polygon is found in the first one." << endl;
+      DoLog(1) && (Log() << Verbose(1) << *(*Runner) << " of second polygon is found in the first one." << endl);
       return true;
     }
@@ -1025,5 +994,5 @@
     Tester = P1->endpoints.insert((*Runner));
     if (Tester.second)
-      Log() << Verbose(0) << "Inserting endpoint " << *(*Runner) << " into first polygon." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Inserting endpoint " << *(*Runner) << " into first polygon." << endl);
   }
   P2->endpoints.clear();
Index: src/test/ActOnAlltest.hpp
===================================================================
--- src/test/ActOnAlltest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/test/ActOnAlltest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -27,4 +27,5 @@
 
   template <typename klasse, typename res, typename T> void ActOnAll( res (klasse::*f)(T), T t );
+  template <typename klasse, typename res, typename T> void ActOnAll( res (klasse::*f)(T&), T &t );
   template <typename klasse, typename res, typename T, typename U> void ActOnAll( res (klasse::*f)(T, U), T t, U u );
   template <typename klasse, typename res, typename T, typename U, typename V> void ActOnAll( res (klasse::*f)(T, U, V), T t, U u, V v);
@@ -76,4 +77,10 @@
 };
 
+template <typename klasse, typename res, typename T> void VectorList::ActOnAll( res (klasse::*f)(T&), T &t )
+{
+  for (ListOfVectors::iterator Runner = Vectors.begin(); Runner != Vectors.end(); Runner++)
+    ((*Runner)->*f)(t);
+};
+
 template <typename klasse, typename res, typename T, typename U> void VectorList::ActOnAll( res (klasse::*f)(T, U), T t, U u )
 {
Index: src/triangleintersectionlist.cpp
===================================================================
--- src/triangleintersectionlist.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/triangleintersectionlist.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,172 @@
+/*
+ * triangleintersectionlist.cpp
+ *
+ * This files encapsulates the TriangleIntersectionList class where all matters related to points in space being how close to
+ * a tesselated surface are answered, i.e. distance, is inside, ...
+ *
+ *  Created on: Mar 1, 2010
+ *      Author: heber
+ */
+
+#include "triangleintersectionlist.hpp"
+
+#include "info.hpp"
+#include "tesselation.hpp"
+#include "vector.hpp"
+
+/** Constructor for class TriangleIntersectionList.
+ *
+ */
+TriangleIntersectionList::TriangleIntersectionList(const Vector *x, const Tesselation *surface, const LinkedCell* LC) :
+  Point(x),
+  Tess(surface),
+  Vicinity(LC)
+{
+  Info FunctionInfo(__func__);
+  GatherIntersectionsWithTriangles();
+};
+
+/** Destructor for class TriangleIntersectionList.
+ * Free's all allocated intersection vectors
+ */
+TriangleIntersectionList::~TriangleIntersectionList()
+{
+  Info FunctionInfo(__func__);
+  for (TriangleVectorMap::iterator Runner = IntersectionList.begin(); Runner != IntersectionList.end(); Runner++)
+    delete((*Runner).second);
+};
+
+/** Returns the smallest distance between TriangleIntersectionList::Point and the surface given by
+ * TriangleIntersectionList::Tess.
+ * \return distance >=0, -1 if no specific distance could be found
+ */
+double TriangleIntersectionList::GetSmallestDistance() const
+{
+  Info FunctionInfo(__func__);
+  FillDistanceList();
+  if (!DistanceList.empty())
+    return DistanceList.begin()->first;
+  else
+    // return reference, if none can be found
+    return -1.;
+};
+
+/** Returns the vector of closest intersection between TriangleIntersectionList::Point and the surface
+ * TriangleIntersectionList::Tess.
+ * \return Intersection vector or TriangleIntersectionList::Point if none could be found
+ */
+Vector TriangleIntersectionList::GetClosestIntersection() const
+{
+  Info FunctionInfo(__func__);
+  TriangleVectorMap::const_iterator runner;
+  runner = GetIteratortoSmallestDistance();
+  if (runner != IntersectionList.end()) {
+    return *((*runner).second);
+  }
+  // return reference, if none can be found
+  return *Point;
+};
+
+/** Returns the triangle closest to TriangleIntersectionList::Point and the surface
+ * TriangleIntersectionList::Tess.
+ * \return pointer to triangle or NULL if none could be found
+ */
+BoundaryTriangleSet * TriangleIntersectionList::GetClosestTriangle() const
+{
+  Info FunctionInfo(__func__);
+  TriangleVectorMap::const_iterator runner;
+  runner = GetIteratortoSmallestDistance();
+  if (runner != IntersectionList.end()) {
+    return ((*runner).first);
+  }
+  // return reference, if none can be found
+  return NULL;
+};
+
+/** Checks whether reference TriangleIntersectionList::Point of this class is inside or outside.
+ * \return true - TriangleIntersectionList::Point is inside, false - is outside
+ */
+bool TriangleIntersectionList::IsInside() const
+{
+  Info FunctionInfo(__func__);
+  TriangleVectorMap::const_iterator runner;
+  runner = GetIteratortoSmallestDistance();
+  if (runner != IntersectionList.end()) {
+    // if we have found one, check Scalarproduct between the vector
+    Vector TestVector = (*Point) - (*(*runner).second);
+    if (fabs(TestVector.NormSquared()) < MYEPSILON) //
+      return true;
+    const double sign = (*runner).first->NormalVector.ScalarProduct(TestVector);
+    if (sign < 0) {
+      return true;
+    } else {
+      return false;
+    }
+  }
+  // so far away from surface that there are no triangles in list
+  return false;
+};
+
+/** Puts all triangles in vicinity (by \a *LC) into a hash map with Intersection vectors.
+ * Private function for constructor of TriangleIntersectionList.
+ */
+void TriangleIntersectionList::GatherIntersectionsWithTriangles()
+{
+  Info FunctionInfo(__func__);
+
+  // get closest points
+  DistanceToPointMap * points = Tess->FindClosestBoundaryPointsToVector(Point,Vicinity);
+  if (points == NULL) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "There is no nearest point: too far away from the surface." << endl);
+    return;
+  }
+
+  // gather all triangles in *LC-neighbourhood
+  TriangleSet triangles;
+  for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++)
+    for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++)
+      for (TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
+        triangles.insert(TriangleRunner->second);
+
+  Vector *Intersection = NULL;
+  for (TriangleSet::const_iterator TriangleRunner = triangles.begin(); TriangleRunner != triangles.end(); TriangleRunner++) {
+    // get intersection with triangle plane
+    Intersection = new Vector;
+    (*TriangleRunner)->GetClosestPointInsideTriangle(Point, Intersection);
+    //Log() << Verbose(1) << "Intersection between " << *Point << " and " << **TriangleRunner << " is at " << *Intersection << "." << endl;
+    IntersectionList.insert( pair<BoundaryTriangleSet *, Vector * > (*TriangleRunner, Intersection) );
+  }
+};
+
+/** Fills the private distance list
+ */
+void TriangleIntersectionList::FillDistanceList() const
+{
+  Info FunctionInfo(__func__);
+  if (DistanceList.empty())
+    for (TriangleVectorMap::const_iterator runner = IntersectionList.begin(); runner != IntersectionList.end(); runner++)
+      DistanceList.insert( pair<double, BoundaryTriangleSet *> (Point->distance(*(*runner).second), (*runner).first) );
+
+  //for (DistanceTriangleMap::const_iterator runner = DistanceList.begin(); runner != DistanceList.end(); runner++)
+  //  Log() << Verbose(1) << (*runner).first << " away from " << *(*runner).second << endl;
+};
+
+
+/** Returns the iterator in VectorTriangleMap to the smallest distance.
+ * This is a private helper function as the iterator is then evaluated in some other functions.
+ * \return iterator or TriangleIntersectionList::IntersectionList.end() if none could be found
+ */
+TriangleVectorMap::const_iterator TriangleIntersectionList::GetIteratortoSmallestDistance() const
+{
+  Info FunctionInfo(__func__);
+  FillDistanceList();
+
+  // do we have any intersections?
+  TriangleVectorMap::const_iterator runner;
+  if (!DistanceList.empty()) {
+    // get closest triangle
+    runner = IntersectionList.find(DistanceList.begin()->second);
+  }
+  return runner;
+};
+
Index: src/triangleintersectionlist.hpp
===================================================================
--- src/triangleintersectionlist.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/triangleintersectionlist.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,61 @@
+/*
+ * TriangleIntersectionList.hpp
+ *
+ *  Created on: Mar 1, 2010
+ *      Author: heber
+ */
+
+#ifndef TRIANGLEINTERSECTIONLIST_HPP_
+#define TRIANGLEINTERSECTIONLIST_HPP_
+
+using namespace std;
+
+/*********************************************** includes ***********************************/
+
+// include config.h
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <map>
+
+/****************************************** forward declarations *****************************/
+
+class BoundaryTriangleSet;
+class LinkedCell;
+class Tesselation;
+class Vector;
+
+/********************************************** definitions *********************************/
+
+#define TriangleVectorMap map < class BoundaryTriangleSet *, Vector *>
+#define DistanceTriangleMap map < double, class BoundaryTriangleSet *>
+
+// ======================================================== class TriangleIntersectionList =======================================
+
+/** Stores all intersection vectors to a list of triangles.
+ */
+class TriangleIntersectionList
+{
+public:
+  TriangleIntersectionList(const Vector *x, const Tesselation *surface, const LinkedCell* LC);
+  ~TriangleIntersectionList();
+
+  double GetSmallestDistance() const;
+  Vector GetClosestIntersection() const;
+  BoundaryTriangleSet * GetClosestTriangle() const;
+  bool IsInside() const;
+
+private:
+  void GatherIntersectionsWithTriangles();
+  TriangleVectorMap::const_iterator GetIteratortoSmallestDistance() const;
+  void FillDistanceList() const;
+
+  const Vector *Point;
+  const Tesselation *Tess;
+  const LinkedCell *Vicinity;
+  TriangleVectorMap IntersectionList;
+  mutable DistanceTriangleMap DistanceList;
+};
+
+#endif /* TRIANGLEINTERSECTIONLIST_HPP_ */
Index: src/types.hpp
===================================================================
--- src/types.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/types.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,21 @@
+/*
+ * types.hpp
+ *
+ *  Created on: Mar 12, 2010
+ *      Author: crueger
+ */
+
+#ifndef TYPES_HPP_
+#define TYPES_HPP_
+
+
+/**
+ *  This file defines some globally used types for later use
+ */
+
+
+typedef unsigned int atomId_t;        //!< The type of atomIds
+typedef unsigned int moleculeId_t;    //!< The type of moleculeIds
+typedef unsigned int atomicNumber_t;  //!< The type of atomicNumbers
+
+#endif /* TYPES_HPP_ */
Index: src/unittests/ActOnAllUnitTest.cpp
===================================================================
--- src/unittests/ActOnAllUnitTest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/ActOnAllUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -44,4 +44,7 @@
 {
   VL.EmptyList();
+  // Ref was copy constructed, hence has to be cleaned, too!
+  Ref.EmptyList();
+  MemoryUsageObserver::purgeInstance();
 };
 
@@ -53,7 +56,7 @@
 
   // adding, subtracting
-  VL.ActOnAll( &Vector::AddVector, &test );
+  VL.ActOnAll( &Vector::AddVector, test );
   CPPUNIT_ASSERT_EQUAL( VL == Ref , false );
-  VL.ActOnAll( &Vector::SubtractVector, &test );
+  VL.ActOnAll( &Vector::SubtractVector, test );
   CPPUNIT_ASSERT_EQUAL( VL == Ref , true );
 };
@@ -67,15 +70,8 @@
 
   // scaling by value
-  VL.ActOnAll( (void (Vector::*)(const double)) &Vector::Scale, 2. );
+  VL.ActOnAll( (void (Vector::*)(const double)) &Vector::Scale, factor );
   CPPUNIT_ASSERT_EQUAL( VL == Ref , false );
 
-  VL.ActOnAll( (void (Vector::*)(const double)) &Vector::Scale, 0.5 );
-  CPPUNIT_ASSERT_EQUAL( VL == Ref , true );
-
-  // scaling by ref
-  VL.ActOnAll( (void (Vector::*)(const double * const)) &Vector::Scale, (const double * const)&factor );
-  CPPUNIT_ASSERT_EQUAL( VL == Ref , false );
-
-  VL.ActOnAll( (void (Vector::*)(const double * const)) &Vector::Scale, (const double * const)&inverse );
+  VL.ActOnAll( (void (Vector::*)(const double)) &Vector::Scale, inverse );
   CPPUNIT_ASSERT_EQUAL( VL == Ref , true );
 
@@ -87,10 +83,23 @@
     inverses[i] = 1./factors[i];
   }
-  VL.ActOnAll( (void (Vector::*)(const double ** const)) &Vector::Scale, (const double ** const)&factors );
+  VL.ActOnAll<Vector,void,const double*>(&Vector::ScaleAll, factors );
   CPPUNIT_ASSERT_EQUAL( VL == Ref , false );
 
-  VL.ActOnAll( (void (Vector::*)(const double ** const)) &Vector::Scale, (const double ** const)&inverses );
+  VL.ActOnAll<Vector,void,const double*>(&Vector::ScaleAll, inverses );
   CPPUNIT_ASSERT_EQUAL( VL == Ref , true );
+  Free(factors);
+  Free(inverses);
 };
+
+#if 0
+
+// Unitttest deactivated for now...
+// Reasons:
+//    Vector::MakeNormalVector has been removed and is now part of Plane class
+//    VectorList::ActOnAll is in the test directory and seems to be used only for unittests
+//    MakeNormal never depended on the input Vector except in the case of linear dependence (i.e. failure)
+//
+// TODO: Rethink what exactely is being tested at this point and introduce a new unittest for the
+//       tested behaviour. Most likely this should result in a thourough unittest of the plane class
 
 /** UnitTest for VectorList::ActOnAll() and Vector::MakeNormalVector()
@@ -108,6 +117,8 @@
   // check that x and y components are zero
   for (ListOfVectors::iterator Runner = VL.Vectors.begin(); Runner != VL.Vectors.end(); Runner++) {
-    CPPUNIT_ASSERT_EQUAL( (*Runner)->x[0] , 0. );
-    CPPUNIT_ASSERT_EQUAL( (*Runner)->x[1] , 0. );
+    CPPUNIT_ASSERT_EQUAL( (*Runner)->at(0) , 0. );
+    CPPUNIT_ASSERT_EQUAL( (*Runner)->at(1) , 0. );
   }
 };
+
+#endif
Index: src/unittests/ActOnAllUnitTest.hpp
===================================================================
--- src/unittests/ActOnAllUnitTest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/ActOnAllUnitTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -20,5 +20,8 @@
     CPPUNIT_TEST ( AddSubtractTest );
     CPPUNIT_TEST ( ScaleTest );
+#if 0
+    // test deactivated. See .cpp for reasons and workarounds
     CPPUNIT_TEST ( NormalizeTest );
+#endif
     CPPUNIT_TEST_SUITE_END();
 
Index: src/unittests/ActionSequenceTest.cpp
===================================================================
--- src/unittests/ActionSequenceTest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/ActionSequenceTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -13,4 +13,7 @@
 #include "Actions/Action.hpp"
 #include "Actions/ActionSequence.hpp"
+#include "Actions/MakroAction.hpp"
+#include "Actions/ActionHistory.hpp"
+#include "Actions/ActionRegistry.hpp"
 
 #ifdef HAVE_TESTRUNNER
@@ -22,9 +25,4 @@
 // Registers the fixture into the 'registry'
 CPPUNIT_TEST_SUITE_REGISTRATION( ActionSequenceTest );
-
-void setUp();
-void tearDown();
-
-void canUndoTest();
 
 /* some neccessary stubs for tests */
@@ -35,7 +33,17 @@
   virtual ~canUndoActionStub(){}
 
-  virtual void call(){}
-  virtual void undo(){}
+  virtual Action::state_ptr performCall(){
+    return Action::success;
+  }
+  virtual Action::state_ptr performUndo(Action::state_ptr){
+    return Action::success;
+  }
+  virtual Action::state_ptr performRedo(Action::state_ptr){
+    return Action::success;
+  }
   virtual bool canUndo(){
+    return true;
+  }
+  virtual bool shouldUndo(){
     return true;
   }
@@ -48,8 +56,18 @@
   virtual ~cannotUndoActionStub(){}
 
-  virtual void call(){}
-  virtual void undo(){}
+  virtual Action::state_ptr performCall(){
+    return Action::success;
+  }
+  virtual Action::state_ptr performUndo(Action::state_ptr){
+    return Action::success;
+  }
+  virtual Action::state_ptr performRedo(Action::state_ptr){
+    return Action::success;
+  }
   virtual bool canUndo(){
     return false;
+  }
+  virtual bool shouldUndo(){
+   return true;
   }
 };
@@ -64,11 +82,20 @@
   virtual ~wasCalledActionStub(){}
 
-  virtual void call(){
+  virtual Action::state_ptr performCall(){
     called = true;
-  }
-  virtual void undo(){
+    return Action::success;
+  }
+  virtual Action::state_ptr performUndo(Action::state_ptr){
     called = false;
+    return Action::success;
+  }
+  virtual Action::state_ptr performRedo(Action::state_ptr){
+    called = true;
+    return Action::success;
   }
   virtual bool canUndo(){
+    return true;
+  }
+  virtual bool shouldUndo(){
     return true;
   }
@@ -81,4 +108,5 @@
 
 void ActionSequenceTest::setUp(){
+  ActionHistory::init();
   // create some necessary stubs used in this test
   positive1 = new canUndoActionStub();
@@ -105,4 +133,6 @@
   delete shouldNotCall2;
 
+  ActionHistory::purgeInstance();
+  ActionRegistry::purgeInstance();
 }
 
@@ -175,26 +205,27 @@
   CPPUNIT_ASSERT_EQUAL(false,shouldNotCall2->wasCalled());
 
+  delete sequence;
 }
 
 void ActionSequenceTest::doesUndoTest(){
   ActionSequence *sequence = new ActionSequence();
-  sequence->addAction(shouldNotCall1);
-  sequence->addAction(shouldNotCall2);
-  sequence->addAction(shouldCall1);
-  sequence->addAction(shouldCall2);
-
-  sequence->callAll();
-
-  sequence->removeLastAction();
-  sequence->removeLastAction();
-
-  sequence->undoAll();
-
-  CPPUNIT_ASSERT_EQUAL(true,shouldCall1->wasCalled());
-  CPPUNIT_ASSERT_EQUAL(true,shouldCall2->wasCalled());
-  CPPUNIT_ASSERT_EQUAL(false,shouldNotCall1->wasCalled());
-  CPPUNIT_ASSERT_EQUAL(false,shouldNotCall2->wasCalled());
-
-}
-
-
+  wasCalledActionStub *wasCalled1 = new wasCalledActionStub();
+  wasCalledActionStub *wasCalled2 = new wasCalledActionStub();
+  sequence->addAction(wasCalled1);
+  sequence->addAction(wasCalled2);
+
+  MakroAction act("Test MakroAction",sequence,false);
+
+  act.call();
+
+  CPPUNIT_ASSERT_EQUAL(true,wasCalled1->wasCalled());
+  CPPUNIT_ASSERT_EQUAL(true,wasCalled1->wasCalled());
+
+  ActionHistory::getInstance().undoLast();
+
+  CPPUNIT_ASSERT_EQUAL(false,wasCalled1->wasCalled());
+  CPPUNIT_ASSERT_EQUAL(false,wasCalled1->wasCalled());
+
+}
+
+
Index: src/unittests/AnalysisCorrelationToPointUnitTest.cpp
===================================================================
--- src/unittests/AnalysisCorrelationToPointUnitTest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/AnalysisCorrelationToPointUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -17,4 +17,5 @@
 #include "AnalysisCorrelationToPointUnitTest.hpp"
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "boundary.hpp"
@@ -24,4 +25,5 @@
 #include "periodentafel.hpp"
 #include "tesselation.hpp"
+#include "World.hpp"
 
 #ifdef HAVE_TESTRUNNER
@@ -55,24 +57,24 @@
 
   // construct periodentafel
-  tafel = new periodentafel;
+  tafel = World::getInstance().getPeriode();
   tafel->AddElement(hydrogen);
 
   // construct molecule (tetraeder of hydrogens)
-  TestMolecule = new molecule(tafel);
-  Walker = new atom();
+  TestMolecule = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(1., 0., 1. );
+  *Walker->node = Vector(1., 0., 1. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(0., 1., 1. );
+  *Walker->node = Vector(0., 1., 1. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(1., 1., 0. );
+  *Walker->node = Vector(1., 1., 0. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(0., 0., 0. );
+  *Walker->node = Vector(0., 0., 0. );
   TestMolecule->AddAtom(Walker);
 
@@ -80,7 +82,7 @@
   CPPUNIT_ASSERT_EQUAL( TestMolecule->AtomCount, 4 );
 
-  TestList = new MoleculeListClass;
+  TestList = World::getInstance().getMolecules();
+  TestList->insert(TestMolecule);
   TestMolecule->ActiveFlag = true;
-  TestList->insert(TestMolecule);
 
   // init point
@@ -101,10 +103,8 @@
     delete(binmap);
 
-  // remove
-  delete(TestList);
-  // note that all the atoms are cleaned by TestMolecule
   delete(point);
-  delete(tafel);
-  // note that element is cleaned by periodentafel
+  World::purgeInstance();
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
 };
 
@@ -122,6 +122,6 @@
   // put pair correlation into bins and check with no range
   binmap = BinData( pointmap, 0.5, 0., 0. );
-  CPPUNIT_ASSERT_EQUAL( (size_t)2, binmap->size() );
-  //OutputCorrelation ( binmap );
+  OutputCorrelation ( (ofstream *)&cout, binmap );
+  CPPUNIT_ASSERT_EQUAL( (size_t)3, binmap->size() );
   tester = binmap->begin();
   CPPUNIT_ASSERT_EQUAL( 1., tester->first );
@@ -135,6 +135,6 @@
   // ... and check with [0., 2.] range
   binmap = BinData( pointmap, 0.5, 0., 2. );
+  OutputCorrelation ( (ofstream *)&cout, binmap );
   CPPUNIT_ASSERT_EQUAL( (size_t)5, binmap->size() );
-  //OutputCorrelation ( binmap );
   tester = binmap->begin();
   CPPUNIT_ASSERT_EQUAL( 0., tester->first );
Index: src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp
===================================================================
--- src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -17,4 +17,5 @@
 #include "AnalysisCorrelationToSurfaceUnitTest.hpp"
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "boundary.hpp"
@@ -24,4 +25,7 @@
 #include "periodentafel.hpp"
 #include "tesselation.hpp"
+#include "World.hpp"
+
+#include "Helpers/Assert.hpp"
 
 #ifdef HAVE_TESTRUNNER
@@ -36,9 +40,11 @@
 void AnalysisCorrelationToSurfaceUnitTest::setUp()
 {
+  //ASSERT_DO(Assert::Throw);
+
   atom *Walker = NULL;
 
   // init private all pointers to zero
   TestList = NULL;
-  TestMolecule = NULL;
+  TestSurfaceMolecule = NULL;
   hydrogen = NULL;
   tafel = NULL;
@@ -59,60 +65,61 @@
 
   // construct periodentafel
-  tafel = new periodentafel;
+  tafel = World::getInstance().getPeriode();
   tafel->AddElement(hydrogen);
   tafel->AddElement(carbon);
 
   // construct molecule (tetraeder of hydrogens) base
-  TestMolecule = new molecule(tafel);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(1., 0., 1. );
-  TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(0., 1., 1. );
-  TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(1., 1., 0. );
-  TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(0., 0., 0. );
-  TestMolecule->AddAtom(Walker);
+  TestSurfaceMolecule = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(1., 0., 1. );
+
+  TestSurfaceMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(0., 1., 1. );
+  TestSurfaceMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(1., 1., 0. );
+  TestSurfaceMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(0., 0., 0. );
+  TestSurfaceMolecule->AddAtom(Walker);
 
   // check that TestMolecule was correctly constructed
-  CPPUNIT_ASSERT_EQUAL( TestMolecule->AtomCount, 4 );
-
-  TestList = new MoleculeListClass;
-  TestMolecule->ActiveFlag = true;
-  TestList->insert(TestMolecule);
+  CPPUNIT_ASSERT_EQUAL( TestSurfaceMolecule->AtomCount, 4 );
+
+  TestList = World::getInstance().getMolecules();
+  TestSurfaceMolecule->ActiveFlag = true;
+  TestList->insert(TestSurfaceMolecule);
 
   // init tesselation and linked cell
   Surface = new Tesselation;
-  FindNonConvexBorder(TestMolecule, Surface, (const LinkedCell *&)LC, 2.5, NULL);
-  LC = new LinkedCell(TestMolecule, 5.);
-  CPPUNIT_ASSERT_EQUAL( (size_t)4, Surface->PointsOnBoundary.size() );
-  CPPUNIT_ASSERT_EQUAL( (size_t)6, Surface->LinesOnBoundary.size() );
-  CPPUNIT_ASSERT_EQUAL( (size_t)4, Surface->TrianglesOnBoundary.size() );
+  LC = new LinkedCell(TestSurfaceMolecule, 5.);
+  FindNonConvexBorder(TestSurfaceMolecule, Surface, (const LinkedCell *&)LC, 2.5, NULL);
 
   // add outer atoms
-  Walker = new atom();
-  Walker->type = carbon;
-  Walker->node->Init(4., 0., 4. );
-  TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = carbon;
-  Walker->node->Init(0., 4., 4. );
-  TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = carbon;
-  Walker->node->Init(4., 4., 0. );
-  TestMolecule->AddAtom(Walker);
+  TestSurfaceMolecule = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
+  Walker->type = carbon;
+  *Walker->node = Vector(4., 0., 4. );
+  TestSurfaceMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = carbon;
+  *Walker->node = Vector(0., 4., 4. );
+  TestSurfaceMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = carbon;
+  *Walker->node = Vector(4., 4., 0. );
+  TestSurfaceMolecule->AddAtom(Walker);
   // add inner atoms
-  Walker = new atom();
-  Walker->type = carbon;
-  Walker->node->Init(0.5, 0.5, 0.5 );
-  TestMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = carbon;
+  *Walker->node = Vector(0.5, 0.5, 0.5 );
+  TestSurfaceMolecule->AddAtom(Walker);
+  TestSurfaceMolecule->ActiveFlag = true;
+  TestList->insert(TestSurfaceMolecule);
 
   // init maps
@@ -130,13 +137,23 @@
     delete(binmap);
 
-  // remove
-  delete(TestList);
   delete(Surface);
   // note that all the atoms are cleaned by TestMolecule
   delete(LC);
-  delete(tafel);
-  // note that element is cleaned by periodentafel
-};
-
+  World::purgeInstance();
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
+};
+
+
+/** Checks whether setup() does the right thing.
+ */
+void AnalysisCorrelationToSurfaceUnitTest::SurfaceTest()
+{
+  CPPUNIT_ASSERT_EQUAL( 4, TestSurfaceMolecule->AtomCount );
+  CPPUNIT_ASSERT_EQUAL( (size_t)2, TestList->ListOfMolecules.size() );
+  CPPUNIT_ASSERT_EQUAL( (size_t)4, Surface->PointsOnBoundary.size() );
+  CPPUNIT_ASSERT_EQUAL( (size_t)6, Surface->LinesOnBoundary.size() );
+  CPPUNIT_ASSERT_EQUAL( (size_t)4, Surface->TrianglesOnBoundary.size() );
+};
 
 void AnalysisCorrelationToSurfaceUnitTest::CorrelationToSurfaceTest()
@@ -144,4 +161,5 @@
   // do the pair correlation
   surfacemap = CorrelationToSurface( TestList, hydrogen, Surface, LC );
+//  OutputCorrelationToSurface ( (ofstream *)&cout, surfacemap );
   CPPUNIT_ASSERT( surfacemap != NULL );
   CPPUNIT_ASSERT_EQUAL( (size_t)4, surfacemap->size() );
@@ -153,7 +171,8 @@
   surfacemap = CorrelationToSurface( TestList, hydrogen, Surface, LC );
   // put pair correlation into bins and check with no range
+//  OutputCorrelationToSurface ( (ofstream *)&cout, surfacemap );
   binmap = BinData( surfacemap, 0.5, 0., 0. );
   CPPUNIT_ASSERT_EQUAL( (size_t)1, binmap->size() );
-  //OutputCorrelation ( binmap );
+  OutputCorrelation ( (ofstream *)&cout, binmap );
   tester = binmap->begin();
   CPPUNIT_ASSERT_EQUAL( 0., tester->first );
@@ -166,8 +185,9 @@
   BinPairMap::iterator tester;
   surfacemap = CorrelationToSurface( TestList, hydrogen, Surface, LC );
+//  OutputCorrelationToSurface ( (ofstream *)&cout, surfacemap );
   // ... and check with [0., 2.] range
   binmap = BinData( surfacemap, 0.5, 0., 2. );
   CPPUNIT_ASSERT_EQUAL( (size_t)5, binmap->size() );
-  //OutputCorrelation ( binmap );
+//  OutputCorrelation ( (ofstream *)&cout, binmap );
   tester = binmap->begin();
   CPPUNIT_ASSERT_EQUAL( 0., tester->first );
@@ -183,14 +203,15 @@
   BinPairMap::iterator tester;
   surfacemap = CorrelationToSurface( TestList, carbon, Surface, LC );
+//  OutputCorrelationToSurface ( (ofstream *)&cout, surfacemap );
   // put pair correlation into bins and check with no range
   binmap = BinData( surfacemap, 0.5, 0., 0. );
-  CPPUNIT_ASSERT_EQUAL( (size_t)2, binmap->size() );
-  OutputCorrelation ( (ofstream *)&cout, binmap );
+  //OutputCorrelation ( (ofstream *)&cout, binmap );
+  CPPUNIT_ASSERT_EQUAL( (size_t)9, binmap->size() );
   // inside point is first and must have negative value
-  tester = binmap->lower_bound(2.95); // start depends on the min value and
+  tester = binmap->lower_bound(4.25-0.5); // start depends on the min value and
   CPPUNIT_ASSERT( tester != binmap->end() );
   CPPUNIT_ASSERT_EQUAL( 3, tester->second );
   // inner point
-  tester = binmap->lower_bound(-0.5);
+  tester = binmap->lower_bound(0.);
   CPPUNIT_ASSERT( tester != binmap->end() );
   CPPUNIT_ASSERT_EQUAL( 1, tester->second );
@@ -201,16 +222,16 @@
   BinPairMap::iterator tester;
   surfacemap = CorrelationToSurface( TestList, carbon, Surface, LC );
+//  OutputCorrelationToSurface ( (ofstream *)&cout, surfacemap );
   // ... and check with [0., 2.] range
   binmap = BinData( surfacemap, 0.5, -2., 4. );
+  //OutputCorrelation ( (ofstream *)&cout, binmap );
   CPPUNIT_ASSERT_EQUAL( (size_t)13, binmap->size() );
-  OutputCorrelation ( (ofstream *)&cout, binmap );
   // three outside points
-  tester = binmap->lower_bound(3.);
+  tester = binmap->lower_bound(4.25-0.5);
   CPPUNIT_ASSERT( tester != binmap->end() );
   CPPUNIT_ASSERT_EQUAL( 3, tester->second );
   // inner point
-  tester = binmap->lower_bound(-0.5);
+  tester = binmap->lower_bound(0.);
   CPPUNIT_ASSERT( tester != binmap->end() );
   CPPUNIT_ASSERT_EQUAL( 1, tester->second );
-
-};
+};
Index: src/unittests/AnalysisCorrelationToSurfaceUnitTest.hpp
===================================================================
--- src/unittests/AnalysisCorrelationToSurfaceUnitTest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/AnalysisCorrelationToSurfaceUnitTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -23,4 +23,5 @@
 {
     CPPUNIT_TEST_SUITE( AnalysisCorrelationToSurfaceUnitTest ) ;
+    CPPUNIT_TEST ( SurfaceTest );
     CPPUNIT_TEST ( CorrelationToSurfaceTest );
     CPPUNIT_TEST ( CorrelationToSurfaceHydrogenBinNoRangeTest );
@@ -33,4 +34,5 @@
       void setUp();
       void tearDown();
+      void SurfaceTest();
       void CorrelationToSurfaceTest();
       void CorrelationToSurfaceHydrogenBinNoRangeTest();
@@ -42,5 +44,5 @@
 
       MoleculeListClass *TestList;
-      molecule *TestMolecule;
+      molecule *TestSurfaceMolecule;
       element *hydrogen;
       element *carbon;
Index: src/unittests/AnalysisPairCorrelationUnitTest.cpp
===================================================================
--- src/unittests/AnalysisPairCorrelationUnitTest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/AnalysisPairCorrelationUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -17,4 +17,5 @@
 #include "AnalysisPairCorrelationUnitTest.hpp"
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "boundary.hpp"
@@ -24,4 +25,5 @@
 #include "periodentafel.hpp"
 #include "tesselation.hpp"
+#include "World.hpp"
 
 #ifdef HAVE_TESTRUNNER
@@ -54,24 +56,24 @@
 
   // construct periodentafel
-  tafel = new periodentafel;
+  tafel = World::getInstance().getPeriode();
   tafel->AddElement(hydrogen);
 
   // construct molecule (tetraeder of hydrogens)
-  TestMolecule = new molecule(tafel);
-  Walker = new atom();
+  TestMolecule = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(1., 0., 1. );
+  *Walker->node = Vector(1., 0., 1. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(0., 1., 1. );
+  *Walker->node = Vector(0., 1., 1. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(1., 1., 0. );
+  *Walker->node = Vector(1., 1., 0. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(0., 0., 0. );
+  *Walker->node = Vector(0., 0., 0. );
   TestMolecule->AddAtom(Walker);
 
@@ -79,5 +81,5 @@
   CPPUNIT_ASSERT_EQUAL( TestMolecule->AtomCount, 4 );
 
-  TestList = new MoleculeListClass;
+  TestList = World::getInstance().getMolecules();
   TestMolecule->ActiveFlag = true;
   TestList->insert(TestMolecule);
@@ -97,9 +99,9 @@
     delete(binmap);
 
-  // remove
-  delete(TestList);
   // note that all the atoms are cleaned by TestMolecule
-  delete(tafel);
-  // note that element is cleaned by periodentafel
+  World::purgeInstance();
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
+  errorLogger::purgeInstance();
 };
 
Index: src/unittests/AtomDescriptorTest.cpp
===================================================================
--- src/unittests/AtomDescriptorTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/AtomDescriptorTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,157 @@
+/*
+ * DescriptorUnittest.cpp
+ *
+ *  Created on: Feb 9, 2010
+ *      Author: crueger
+ */
+
+#include "AtomDescriptorTest.hpp"
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+#include <iostream>
+
+#include <Descriptors/AtomDescriptor.hpp>
+#include <Descriptors/AtomIdDescriptor.hpp>
+
+#include "World.hpp"
+#include "atom.hpp"
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+/********************************************** Test classes **************************************/
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( AtomDescriptorTest );
+
+// set up and tear down
+void AtomDescriptorTest::setUp(){
+  World::getInstance();
+  for(int i=0;i<ATOM_COUNT;++i){
+    atoms[i]= World::getInstance().createAtom();
+    atomIds[i]= atoms[i]->getId();
+  }
+}
+
+void AtomDescriptorTest::tearDown(){
+  World::purgeInstance();
+}
+
+// some helper functions
+static bool hasAllAtoms(std::vector<atom*> atoms,atomId_t ids[ATOM_COUNT], std::set<atomId_t> excluded = std::set<atomId_t>()){
+  for(int i=0;i<ATOM_COUNT;++i){
+    atomId_t id = ids[i];
+    if(!excluded.count(id)){
+      std::vector<atom*>::iterator iter;
+      bool res=false;
+      for(iter=atoms.begin();iter!=atoms.end();++iter){
+        res |= (*iter)->getId() == id;
+      }
+      if(!res) {
+        cout << "Atom " << id << " missing in returned list" << endl;
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+static bool hasNoDuplicateAtoms(std::vector<atom*> atoms){
+  std::set<atomId_t> found;
+  std::vector<atom*>::iterator iter;
+  for(iter=atoms.begin();iter!=atoms.end();++iter){
+    int id = (*iter)->getId();
+    if(found.count(id))
+      return false;
+    found.insert(id);
+  }
+  return true;
+}
+
+
+void AtomDescriptorTest::AtomBaseSetsTest(){
+  std::vector<atom*> allAtoms = World::getInstance().getAllAtoms(AllAtoms());
+  CPPUNIT_ASSERT_EQUAL( true , hasAllAtoms(allAtoms,atomIds));
+  CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateAtoms(allAtoms));
+
+  std::vector<atom*> noAtoms = World::getInstance().getAllAtoms(NoAtoms());
+  CPPUNIT_ASSERT_EQUAL( true , noAtoms.empty());
+}
+void AtomDescriptorTest::AtomIdTest(){
+  // test Atoms from boundaries and middle of the set
+  atom* testAtom;
+  testAtom = World::getInstance().getAtom(AtomById(atomIds[0]));
+  CPPUNIT_ASSERT(testAtom);
+  CPPUNIT_ASSERT_EQUAL( atomIds[0], testAtom->getId());
+  testAtom = World::getInstance().getAtom(AtomById(atomIds[ATOM_COUNT/2]));
+  CPPUNIT_ASSERT(testAtom);
+  CPPUNIT_ASSERT_EQUAL( atomIds[ATOM_COUNT/2], testAtom->getId());
+  testAtom = World::getInstance().getAtom(AtomById(atomIds[ATOM_COUNT-1]));
+  CPPUNIT_ASSERT(testAtom);
+  CPPUNIT_ASSERT_EQUAL( atomIds[ATOM_COUNT-1], testAtom->getId());
+
+  // find some ID that has not been created
+  atomId_t outsideId=0;
+  bool res = false;
+  for(outsideId=0;!res;++outsideId) {
+    res = true;
+    for(int i = 0; i < ATOM_COUNT; ++i){
+      res &= atomIds[i]!=outsideId;
+    }
+  }
+  // test from outside of set
+  testAtom = World::getInstance().getAtom(AtomById(outsideId));
+  CPPUNIT_ASSERT(!testAtom);
+}
+void AtomDescriptorTest::AtomCalcTest(){
+  // test some elementary set operations
+  {
+    std::vector<atom*> testAtoms = World::getInstance().getAllAtoms(AllAtoms()||NoAtoms());
+    CPPUNIT_ASSERT_EQUAL( true , hasAllAtoms(testAtoms,atomIds));
+    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateAtoms(testAtoms));
+  }
+
+  {
+    std::vector<atom*> testAtoms = World::getInstance().getAllAtoms(NoAtoms()||AllAtoms());
+    CPPUNIT_ASSERT_EQUAL( true , hasAllAtoms(testAtoms,atomIds));
+    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateAtoms(testAtoms));
+  }
+
+  {
+    std::vector<atom*> testAtoms = World::getInstance().getAllAtoms(NoAtoms()&&AllAtoms());
+    CPPUNIT_ASSERT_EQUAL( true , testAtoms.empty());
+  }
+
+  {
+    std::vector<atom*> testAtoms = World::getInstance().getAllAtoms(AllAtoms()&&NoAtoms());
+    CPPUNIT_ASSERT_EQUAL( true , testAtoms.empty());
+  }
+
+  {
+    std::vector<atom*> testAtoms = World::getInstance().getAllAtoms(!AllAtoms());
+    CPPUNIT_ASSERT_EQUAL( true , testAtoms.empty());
+  }
+
+  {
+    std::vector<atom*> testAtoms = World::getInstance().getAllAtoms(!NoAtoms());
+    CPPUNIT_ASSERT_EQUAL( true , hasAllAtoms(testAtoms,atomIds));
+    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateAtoms(testAtoms));
+  }
+  // exclude and include some atoms
+  {
+    std::vector<atom*> testAtoms = World::getInstance().getAllAtoms(AllAtoms()&&(!AtomById(atomIds[ATOM_COUNT/2])));
+    std::set<atomId_t> excluded;
+    excluded.insert(atomIds[ATOM_COUNT/2]);
+    CPPUNIT_ASSERT_EQUAL( true , hasAllAtoms(testAtoms,atomIds,excluded));
+    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateAtoms(testAtoms));
+    CPPUNIT_ASSERT_EQUAL( (size_t)(ATOM_COUNT-1), testAtoms.size());
+  }
+
+  {
+    std::vector<atom*> testAtoms = World::getInstance().getAllAtoms(NoAtoms()||(AtomById(atomIds[ATOM_COUNT/2])));
+    CPPUNIT_ASSERT_EQUAL( (size_t)1, testAtoms.size());
+    CPPUNIT_ASSERT_EQUAL( atomIds[ATOM_COUNT/2], testAtoms[0]->getId());
+  }
+}
Index: src/unittests/AtomDescriptorTest.hpp
===================================================================
--- src/unittests/AtomDescriptorTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/AtomDescriptorTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,40 @@
+/*
+ * AtomDescriptorTest.hpp
+ *
+ *  Created on: Feb 9, 2010
+ *      Author: crueger
+ */
+
+#ifndef ATOMDESCRIPTORTEST_HPP_
+#define ATOMDESCRIPTORTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "types.hpp"
+
+#define ATOM_COUNT (10)
+
+class atom;
+
+class AtomDescriptorTest : public CppUnit::TestFixture
+{
+  CPPUNIT_TEST_SUITE( AtomDescriptorTest );
+  CPPUNIT_TEST ( AtomBaseSetsTest );
+  CPPUNIT_TEST ( AtomIdTest );
+  CPPUNIT_TEST ( AtomCalcTest );
+  CPPUNIT_TEST_SUITE_END();
+
+public:
+  void setUp();
+  void tearDown();
+
+  void AtomBaseSetsTest();
+  void AtomIdTest();
+  void AtomCalcTest();
+
+private:
+  atom *atoms [ATOM_COUNT];
+  atomId_t atomIds [ATOM_COUNT];
+};
+
+#endif /* ATOMDESCRIPTORTEST_HPP_ */
Index: src/unittests/CacheableTest.cpp
===================================================================
--- src/unittests/CacheableTest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/CacheableTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -27,8 +27,9 @@
 class threeNumbers : public Observable {
 public:
-  bool hasRecalced;
   int x;
   int y;
   int z;
+  Cacheable<int> sum;
+  bool hasRecalced;
 
   void setX(int _x){
@@ -54,10 +55,8 @@
 
   threeNumbers(int _x,int _y, int _z) :
+    x(_x),y(_y),z(_z),
     sum(this,boost::bind(&threeNumbers::calcSum,this)),
-    x(_x),y(_y),z(_z),
     hasRecalced(false)
   {}
-
-  Cacheable<int> sum;
 };
 
Index: src/unittests/CountBondsUnitTest.cpp
===================================================================
--- src/unittests/CountBondsUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/CountBondsUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,240 @@
+/*
+ * CountBondsUnitTest.cpp
+ *
+ *  Created on: Mar 30, 2010
+ *      Author: heber
+ */
+
+
+using namespace std;
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include <iostream>
+#include <stdio.h>
+#include <cstring>
+
+#include "analysis_bonds.hpp"
+#include "atom.hpp"
+#include "bond.hpp"
+#include "bondgraph.hpp"
+#include "element.hpp"
+#include "molecule.hpp"
+#include "periodentafel.hpp"
+#include "World.hpp"
+#include "CountBondsUnitTest.hpp"
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( CountBondsTest );
+
+
+void CountBondsTest::setUp()
+{
+  atom *Walker = NULL;
+  BG = NULL;
+  filename = NULL;
+
+  // init private all pointers to zero
+  molecules = NULL;
+  TestMolecule1 = NULL;
+  TestMolecule2 = NULL;
+  hydrogen = NULL;
+  oxygen = NULL;
+  tafel = NULL;
+
+  // construct element
+  hydrogen = new element;
+  hydrogen->Z = 1;
+  hydrogen->CovalentRadius = 0.23;
+  strcpy(hydrogen->name, "hydrogen");
+  strcpy(hydrogen->symbol, "H");
+  oxygen = new element;
+  oxygen->Z = 8;
+  oxygen->CovalentRadius = 0.68;
+  strcpy(oxygen->name, "oxygen");
+  strcpy(oxygen->symbol, "O");
+
+  // construct periodentafel
+  tafel = World::getInstance().getPeriode();
+  tafel->AddElement(hydrogen);
+  tafel->AddElement(oxygen);
+
+  // construct molecule (water molecule)
+  TestMolecule1 = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(-0.2418, 0.9350, 0. );
+  TestMolecule1->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(0.9658, 0., 0. );
+  TestMolecule1->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = oxygen;
+  *Walker->node = Vector(0., 0., 0. );
+  TestMolecule1->AddAtom(Walker);
+
+  TestMolecule2 = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(-0.2418, 0.9350, 0. );
+  TestMolecule2->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(0.9658, 0., 0. );
+  TestMolecule2->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = oxygen;
+  *Walker->node = Vector(0., 0., 0. );
+  TestMolecule2->AddAtom(Walker);
+
+  molecules = World::getInstance().getMolecules();
+  molecules->insert(TestMolecule1);
+  molecules->insert(TestMolecule2);
+
+  // check that TestMolecule was correctly constructed
+  CPPUNIT_ASSERT_EQUAL( TestMolecule1->AtomCount, 3 );
+  Walker = TestMolecule1->start->next;
+  CPPUNIT_ASSERT( TestMolecule1->end != Walker );
+  CPPUNIT_ASSERT_EQUAL( TestMolecule2->AtomCount, 3 );
+  Walker = TestMolecule2->start->next;
+  CPPUNIT_ASSERT( TestMolecule2->end != Walker );
+
+  // create a small file with table
+  BG = new BondGraph(true);
+
+  // construct bond graphs
+  CPPUNIT_ASSERT_EQUAL( true , BG->ConstructBondGraph(TestMolecule1) );
+  CPPUNIT_ASSERT_EQUAL( true , BG->ConstructBondGraph(TestMolecule2) );
+//  TestMolecule1->Output((ofstream *)&cout);
+//  TestMolecule1->OutputBondsList();
+};
+
+
+void CountBondsTest::tearDown()
+{
+  // remove the file
+  delete(BG);
+
+  World::purgeInstance();
+  MemoryUsageObserver::purgeInstance();
+};
+
+/** UnitTest for CountBondsTest::BondsOfTwoTest().
+ */
+void CountBondsTest::BondsOfTwoTest()
+{
+  CPPUNIT_ASSERT_EQUAL( 4 , CountBondsOfTwo(molecules, hydrogen, oxygen) );
+  CPPUNIT_ASSERT_EQUAL( 0 , CountBondsOfTwo(molecules, hydrogen, hydrogen) );
+  CPPUNIT_ASSERT_EQUAL( 0 , CountBondsOfTwo(molecules, oxygen, oxygen) );
+};
+
+/** UnitTest for CountBondsTest::BondsOfThreeTest().
+ */
+void CountBondsTest::BondsOfThreeTest()
+{
+  CPPUNIT_ASSERT_EQUAL( 2 , CountBondsOfThree(molecules, hydrogen, oxygen, hydrogen) );
+  CPPUNIT_ASSERT_EQUAL( 0 , CountBondsOfThree(molecules, oxygen, hydrogen, oxygen) );
+};
+
+void OutputTestMolecule(molecule *mol, const char *name)
+{
+  ofstream output(name);
+  mol->OutputXYZ(&output);
+  output.close();
+}
+
+/** UnitTest for CountBondsTest::HydrogenBridgeBondsTest().
+ */
+void CountBondsTest::HydrogenBridgeBondsTest()
+{
+  double *mirror = new double[3];
+  for (int i=0;i<3;i++)
+    mirror[i] = -1.;
+  Vector Translator;
+
+  //OutputTestMolecule(TestMolecule1, "testmolecule1.xyz");
+
+  cout << "Case 1: offset of (3,0,0), hence angles are (104.5, 0, 75.5, 180) < 30." << endl;
+  Translator  = Vector(3,0,0);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 1 , CountHydrogenBridgeBonds(molecules, NULL) );
+  CPPUNIT_ASSERT_EQUAL( 0 , CountHydrogenBridgeBonds(molecules, oxygen) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-1.xyz");
+  Translator = Vector(-3,0,0);
+  TestMolecule2->Translate(&Translator);
+
+  cout << "Case 2: offset of (0,3,0), hence angle are (14.5, 165.5, 90) < 30 (only three, because other 90 is missing due to first H01 only fulfilling H-bond criteria)." << endl;
+  Translator = Vector(0,3,0);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 1 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-2.xyz");
+  Translator = Vector(0,-3,0);
+  TestMolecule2->Translate(&Translator);
+
+  cout << "Case 3: offset of (0,-3,0) and mirror, hence angle are (165.5, 90, 165.5, 90) > 30." << endl;
+  Translator = Vector(0,-3,0);
+  TestMolecule2->Scale((const double ** const)&mirror);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 0 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-3.xyz");
+  Translator = Vector(0,3,0);
+  TestMolecule2->Translate(&Translator);
+  TestMolecule2->Scale((const double ** const)&mirror);
+
+  cout << "Case 4: offset of (2,1,0), hence angle are (78, 26.6, 102, 153.4) < 30." << endl;
+  Translator = Vector(2,1,0);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 1 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-4.xyz");
+  Translator = Vector(-2,-1,0);
+  TestMolecule2->Translate(&Translator);
+
+  cout << "Case 5: offset of (0,0,3), hence angle are (90, 90, 90, 90) > 30." << endl;
+  Translator = Vector(0,0,3);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 0 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-5.xyz");
+  Translator = Vector(0,0,-3);
+  TestMolecule2->Translate(&Translator);
+
+  cout << "Case 6: offset of (-3,0,0) and mirror, hence angle are (75.5, 180, 104.5, 180) > 30." << endl;
+  Translator = Vector(-3,0,0);
+  TestMolecule2->Scale((const double ** const)&mirror);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 0 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-6.xyz");
+  Translator = Vector(3,0,0);
+  TestMolecule2->Translate(&Translator);
+  TestMolecule2->Scale((const double ** const)&mirror);
+
+  cout << "Case 7: offset of (3,0,0) and mirror, hence angles are (104.5, 0, 104.5, 0) < 30, but interfering hydrogens." << endl;
+  Translator = Vector(3,0,0);
+  TestMolecule2->Scale((const double ** const)&mirror);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 0 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-7.xyz");
+  Translator = Vector(-3,0,0);
+  TestMolecule2->Translate(&Translator);
+  TestMolecule2->Scale((const double ** const)&mirror);
+
+  cout << "Case 8: offset of (0,3,0), hence angle are (14.5, 90, 14.5, 90) < 30, but interfering hydrogens." << endl;
+  Translator = Vector(0,3,0);
+  TestMolecule2->Scale((const double ** const)&mirror);
+  TestMolecule2->Translate(&Translator);
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-8.xyz");
+  CPPUNIT_ASSERT_EQUAL( 0 , CountHydrogenBridgeBonds(molecules, NULL) );
+  Translator = Vector(0,-3,0);
+  TestMolecule2->Translate(&Translator);
+  TestMolecule2->Scale((const double ** const)&mirror);
+
+  delete[](mirror);
+};
Index: src/unittests/CountBondsUnitTest.hpp
===================================================================
--- src/unittests/CountBondsUnitTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/CountBondsUnitTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,50 @@
+/*
+ * CountBondsUnitTest.hpp
+ *
+ *  Created on: Mar 30, 2010
+ *      Author: heber
+ */
+
+#ifndef COUNTBONDSUNITTEST_HPP_
+#define COUNTBONDSUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+
+class BondGraph;
+class element;
+class molecule;
+class periodentafel;
+
+/********************************************** Test classes **************************************/
+
+class CountBondsTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( CountBondsTest) ;
+    CPPUNIT_TEST ( BondsOfTwoTest );
+    CPPUNIT_TEST ( BondsOfThreeTest );
+    CPPUNIT_TEST ( HydrogenBridgeBondsTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+      void setUp();
+      void tearDown();
+      void BondsOfTwoTest();
+      void BondsOfThreeTest();
+      void HydrogenBridgeBondsTest();
+
+private:
+
+      MoleculeListClass *molecules;
+      molecule *TestMolecule1;
+      molecule *TestMolecule2;
+      element *hydrogen;
+      element *oxygen;
+      periodentafel *tafel;
+
+      BondGraph *BG;
+      string *filename;
+};
+
+
+#endif /* COUNTBONDSUNITTEST_HPP_ */
Index: src/unittests/DescriptorUnittest.cpp
===================================================================
--- src/unittests/DescriptorUnittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ 	(revision )
@@ -1,163 +1,0 @@
-/*
- * DescriptorUnittest.cpp
- *
- *  Created on: Feb 9, 2010
- *      Author: crueger
- */
-
-#include "DescriptorUnittest.hpp"
-
-#include <cppunit/CompilerOutputter.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <cppunit/ui/text/TestRunner.h>
-#include <iostream>
-
-#include <Descriptors/AtomDescriptor.hpp>
-#include <Descriptors/AtomIdDescriptor.hpp>
-
-#include "World.hpp"
-#include "atom.hpp"
-
-#ifdef HAVE_TESTRUNNER
-#include "UnitTestMain.hpp"
-#endif /*HAVE_TESTRUNNER*/
-
-/********************************************** Test classes **************************************/
-// Registers the fixture into the 'registry'
-CPPUNIT_TEST_SUITE_REGISTRATION( DescriptorUnittest );
-
-// some stubs
-class AtomStub : public atom {
-public:
-  AtomStub(int _id) :
-  atom(),
-  id(_id)
-  {}
-
-  virtual int getId(){
-    return id;
-  }
-
-private:
-  int id;
-};
-
-
-// set up and tear down
-void DescriptorUnittest::setUp(){
-  World::get();
-  for(int i=0;i<ATOM_COUNT;++i){
-    atoms[i]= new AtomStub(i);
-  }
-}
-void DescriptorUnittest::tearDown(){
-  World::destroy();
-  for(int i=0;i<ATOM_COUNT;++i){
-    delete atoms[i];
-  }
-}
-
-// some helper functions
-bool hasAll(std::vector<atom*> atoms,int min, int max, std::set<int> excluded = std::set<int>()){
-  for(int i=min;i<max;++i){
-    if(!excluded.count(i)){
-      std::vector<atom*>::iterator iter;
-      bool res=false;
-      for(iter=atoms.begin();iter!=atoms.end();++iter){
-        res |= (*iter)->getId() == i;
-      }
-      if(!res) {
-        cout << "Atom " << i << " missing in returned list" << endl;
-        return false;
-      }
-    }
-  }
-  return true;
-}
-
-bool hasNoDuplicates(std::vector<atom*> atoms){
-  std::set<int> found;
-  std::vector<atom*>::iterator iter;
-  for(iter=atoms.begin();iter!=atoms.end();++iter){
-    int id = (*iter)->getId();
-    if(found.count(id))
-      return false;
-    found.insert(id);
-  }
-  return true;
-}
-
-
-void DescriptorUnittest::AtomBaseSetsTest(){
-  std::vector<atom*> allAtoms = World::get()->getAllAtoms(AllAtoms());
-  CPPUNIT_ASSERT_EQUAL( true , hasAll(allAtoms,0,ATOM_COUNT));
-  CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicates(allAtoms));
-
-  std::vector<atom*> noAtoms = World::get()->getAllAtoms(NoAtoms());
-  CPPUNIT_ASSERT_EQUAL( true , noAtoms.empty());
-}
-void DescriptorUnittest::AtomIdTest(){
-  // test Atoms from boundaries and middle of the set
-  atom* testAtom;
-  testAtom = World::get()->getAtom(AtomById(0));
-  CPPUNIT_ASSERT_EQUAL( 0, testAtom->getId());
-  testAtom = World::get()->getAtom(AtomById(ATOM_COUNT/2));
-  CPPUNIT_ASSERT_EQUAL( ATOM_COUNT/2, testAtom->getId());
-  testAtom = World::get()->getAtom(AtomById(ATOM_COUNT-1));
-  CPPUNIT_ASSERT_EQUAL( ATOM_COUNT-1, testAtom->getId());
-
-  // test from outside of set
-  testAtom = World::get()->getAtom(AtomById(ATOM_COUNT));
-  CPPUNIT_ASSERT(!testAtom);
-}
-void DescriptorUnittest::AtomCalcTest(){
-  // test some elementary set operations
-  {
-    std::vector<atom*> testAtoms = World::get()->getAllAtoms(AllAtoms()||NoAtoms());
-    CPPUNIT_ASSERT_EQUAL( true , hasAll(testAtoms,0,ATOM_COUNT));
-    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicates(testAtoms));
-  }
-
-  {
-    std::vector<atom*> testAtoms = World::get()->getAllAtoms(NoAtoms()||AllAtoms());
-    CPPUNIT_ASSERT_EQUAL( true , hasAll(testAtoms,0,ATOM_COUNT));
-    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicates(testAtoms));
-  }
-
-  {
-    std::vector<atom*> testAtoms = World::get()->getAllAtoms(NoAtoms()&&AllAtoms());
-    CPPUNIT_ASSERT_EQUAL( true , testAtoms.empty());
-  }
-
-  {
-    std::vector<atom*> testAtoms = World::get()->getAllAtoms(AllAtoms()&&NoAtoms());
-    CPPUNIT_ASSERT_EQUAL( true , testAtoms.empty());
-  }
-
-  {
-    std::vector<atom*> testAtoms = World::get()->getAllAtoms(!AllAtoms());
-    CPPUNIT_ASSERT_EQUAL( true , testAtoms.empty());
-  }
-
-  {
-    std::vector<atom*> testAtoms = World::get()->getAllAtoms(!NoAtoms());
-    CPPUNIT_ASSERT_EQUAL( true , hasAll(testAtoms,0,ATOM_COUNT));
-    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicates(testAtoms));
-  }
-
-  // exclude and include some atoms
-  {
-    std::vector<atom*> testAtoms = World::get()->getAllAtoms(AllAtoms()&&(!AtomById(ATOM_COUNT/2)));
-    std::set<int> excluded;
-    excluded.insert(ATOM_COUNT/2);
-    CPPUNIT_ASSERT_EQUAL( true , hasAll(testAtoms,0,ATOM_COUNT,excluded));
-    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicates(testAtoms));
-    CPPUNIT_ASSERT_EQUAL( (size_t)(ATOM_COUNT-1), testAtoms.size());
-  }
-
-  {
-    std::vector<atom*> testAtoms = World::get()->getAllAtoms(NoAtoms()||(AtomById(ATOM_COUNT/2)));
-    CPPUNIT_ASSERT_EQUAL( (size_t)1, testAtoms.size());
-    CPPUNIT_ASSERT_EQUAL( ATOM_COUNT/2, testAtoms[0]->getId());
-  }
-}
Index: src/unittests/DescriptorUnittest.hpp
===================================================================
--- src/unittests/DescriptorUnittest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ 	(revision )
@@ -1,37 +1,0 @@
-/*
- * DescriptorUnittest.hpp
- *
- *  Created on: Feb 9, 2010
- *      Author: crueger
- */
-
-#ifndef DESCRIPTORUNITTEST_HPP_
-#define DESCRIPTORUNITTEST_HPP_
-
-#include <cppunit/extensions/HelperMacros.h>
-
-#define ATOM_COUNT (10)
-
-class atom;
-
-class DescriptorUnittest : public CppUnit::TestFixture
-{
-  CPPUNIT_TEST_SUITE( DescriptorUnittest );
-  CPPUNIT_TEST ( AtomBaseSetsTest );
-  CPPUNIT_TEST ( AtomIdTest );
-  CPPUNIT_TEST ( AtomCalcTest );
-  CPPUNIT_TEST_SUITE_END();
-
-public:
-  void setUp();
-  void tearDown();
-
-  void AtomBaseSetsTest();
-  void AtomIdTest();
-  void AtomCalcTest();
-
-private:
-  atom *atoms [ATOM_COUNT];
-};
-
-#endif /* DESCRIPTORUNITTEST_HPP_ */
Index: src/unittests/LinkedCellUnitTest.cpp
===================================================================
--- src/unittests/LinkedCellUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/LinkedCellUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,372 @@
+/*
+ * LinkedCellUnitTest.cpp
+ *
+ *  Created on: Apr 9, 2010
+ *      Author: heber
+ */
+
+using namespace std;
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include <iostream>
+#include <stdio.h>
+#include <cstring>
+
+#include "atom.hpp"
+#include "element.hpp"
+#include "linkedcell.hpp"
+#include "molecule.hpp"
+#include "periodentafel.hpp"
+#include "LinkedCellUnitTest.hpp"
+#include "World.hpp"
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( LinkedCellTest );
+
+
+void LinkedCellTest::setUp()
+{
+  atom *Walker = NULL;
+
+  // init private all pointers to zero
+  TestMolecule = NULL;
+  hydrogen = NULL;
+  tafel = NULL;
+
+  // construct element
+  hydrogen = new element;
+  hydrogen->Z = 1;
+  hydrogen->CovalentRadius = 0.23;
+  strcpy(hydrogen->name, "hydrogen");
+  strcpy(hydrogen->symbol, "H");
+
+  // construct periodentafel
+  tafel = World::getInstance().getPeriode();
+  tafel->AddElement(hydrogen);
+
+  // construct molecule (water molecule)
+  TestMolecule = World::getInstance().createMolecule();
+  for (double x=0.5;x<3;x+=1.)
+    for (double y=0.5;y<3;y+=1.)
+      for (double z=0.5;z<3;z+=1.) {
+        Walker = World::getInstance().createAtom();
+        Walker->type = hydrogen;
+        *Walker->node = Vector(x, y, z );
+        TestMolecule->AddAtom(Walker);
+      }
+
+  // construct linked cell
+  LC = new LinkedCell (TestMolecule, 1.);
+
+  // check that TestMolecule was correctly constructed
+  CPPUNIT_ASSERT_EQUAL( TestMolecule->AtomCount, 3*3*3 );
+  Walker = TestMolecule->start->next;
+  CPPUNIT_ASSERT( TestMolecule->end != Walker );
+};
+
+
+void LinkedCellTest::tearDown()
+{
+  delete(LC);
+  World::purgeInstance();
+  MemoryUsageObserver::purgeInstance();
+};
+
+
+/** UnitTest for LinkedCell::CheckBounds().
+ */
+void LinkedCellTest::CheckBoundsTest()
+{
+  // check for within bounds
+  LC->n[0] = LC->n[1] = LC->n[2] = 0;
+  CPPUNIT_ASSERT_EQUAL( true, LC->CheckBounds() );
+  LC->n[0] = LC->n[1] = LC->n[2] = 1;
+  CPPUNIT_ASSERT_EQUAL( true, LC->CheckBounds() );
+  LC->n[0] = LC->n[1] = LC->n[2] = 2;
+  CPPUNIT_ASSERT_EQUAL( true, LC->CheckBounds() );
+
+  // check for out of bounds
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  LC->n[0] = 404040;
+  CPPUNIT_ASSERT_EQUAL( false, LC->CheckBounds() );
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  LC->n[0] = 0;
+  LC->n[1] = 5000;
+  CPPUNIT_ASSERT_EQUAL( false, LC->CheckBounds() );
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  LC->n[1] = 0;
+  LC->n[2] = -70;
+  CPPUNIT_ASSERT_EQUAL( false, LC->CheckBounds() );
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  LC->n[0] = LC->n[1] = LC->n[2] = 3;
+  CPPUNIT_ASSERT_EQUAL( false, LC->CheckBounds() );
+};
+
+
+/** UnitTest for LinkedCell::GetCurrentCell().
+ * Note that CheckBounds() is used and has to be tested already.
+ */
+void LinkedCellTest::GetCurrentCellTest()
+{
+  // within bounds
+  LC->n[0] = LC->n[1] = LC->n[2] = 0;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)&LC->LC[0 * 3*3 + 0 * 3 + 0], LC->GetCurrentCell() );
+  LC->n[0] = LC->n[1] = LC->n[2] = 1;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)&LC->LC[1 * 3*3 + 1 * 3 + 1], LC->GetCurrentCell() );
+  LC->n[0] = LC->n[1] = LC->n[2] = 2;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)&LC->LC[2 * 3*3 + 2 * 3 + 2], LC->GetCurrentCell() );
+
+  // out of bounds
+  LC->n[0] = LC->n[1] = LC->n[2] = 3;
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)NULL, LC->GetCurrentCell() );
+  LC->n[0] = LC->n[1] = LC->n[2] = -1;
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)NULL, LC->GetCurrentCell() );
+};
+
+/** UnitTest for LinkedCell::GetRelativeToCurrentCell().
+ */
+void LinkedCellTest::GetRelativeToCurrentCellTest()
+{
+  int offset[3];
+
+  // offset to (0,0,0) always
+  offset[0] = offset[1] = offset[2] = 0;
+  LC->n[0] = LC->n[1] = LC->n[2] = 0;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)&LC->LC[0], LC->GetRelativeToCurrentCell(offset) );
+  offset[0] = offset[1] = offset[2] = -1;
+  LC->n[0] = LC->n[1] = LC->n[2] = 1;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)&LC->LC[0], LC->GetRelativeToCurrentCell(offset) );
+  offset[0] = offset[1] = offset[2] = -2;
+  LC->n[0] = LC->n[1] = LC->n[2] = 2;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)&LC->LC[0], LC->GetRelativeToCurrentCell(offset) );
+
+  // offset to (0,0,0) - 1.*(x/y/z) out of bounds
+  offset[0] = offset[1] = offset[2] = 0;
+  offset[0] = -1;
+  LC->n[0] = LC->n[1] = LC->n[2] = 0;
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)NULL, LC->GetRelativeToCurrentCell(offset) );
+  offset[0] = offset[1] = offset[2] = 0;
+  offset[1] = -1;
+  LC->n[0] = LC->n[1] = LC->n[2] = 0;
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)NULL, LC->GetRelativeToCurrentCell(offset) );
+  offset[0] = offset[1] = offset[2] = 0;
+  offset[2] = -1;
+  LC->n[0] = LC->n[1] = LC->n[2] = 0;
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)NULL, LC->GetRelativeToCurrentCell(offset) );
+
+  // out of bounds
+  offset[0] = offset[1] = offset[2] = -5054932;
+  LC->n[0] = LC->n[1] = LC->n[2] = 1;
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)NULL, LC->GetRelativeToCurrentCell(offset) );
+  offset[0] = offset[1] = offset[2] = 192345;
+  LC->n[0] = LC->n[1] = LC->n[2] = 1;
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)NULL, LC->GetRelativeToCurrentCell(offset) );
+
+  // index is out of bounds, offset points within
+  offset[0] = offset[1] = offset[2] = -2;
+  LC->n[0] = LC->n[1] = LC->n[2] = 4;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)&LC->LC[2 * 3*3 + 2 * 3 + 2], LC->GetRelativeToCurrentCell(offset) );
+
+  // index is within bounds, offset points out
+  offset[0] = offset[1] = offset[2] = 2;
+  LC->n[0] = LC->n[1] = LC->n[2] = 2;
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( (const LinkedCell::LinkedNodes*)NULL, LC->GetRelativeToCurrentCell(offset) );
+};
+
+
+/** UnitTest for LinkedCell::SetIndexToNode().
+ */
+void LinkedCellTest::SetIndexToNodeTest()
+{
+  // check all atoms
+  atom *Walker = TestMolecule->start;
+  while (Walker->next != TestMolecule->end) {
+    Walker = Walker->next;
+    CPPUNIT_ASSERT_EQUAL( true, LC->SetIndexToNode(Walker) );
+  }
+
+  // check internal vectors, returns false, because this atom is not in LC-list!
+  Walker = World::getInstance().createAtom();
+  Walker->Name = Malloc<char>(6, "LinkedCellTest::SetIndexToNodeTest - Walker");
+  strcpy(Walker->Name, "test");
+  Walker->x= Vector(1,1,1);
+  CPPUNIT_ASSERT_EQUAL( false, LC->SetIndexToNode(Walker) );
+  World::getInstance().destroyAtom(Walker);
+
+  // check out of bounds vectors
+  Walker = World::getInstance().createAtom();
+  Walker->Name = Malloc<char>(6, "LinkedCellTest::SetIndexToNodeTest - Walker");
+  strcpy(Walker->Name, "test");
+  Walker->x = Vector(0,-1,0);
+  CPPUNIT_ASSERT_EQUAL( false, LC->SetIndexToNode(Walker) );
+  World::getInstance().destroyAtom(Walker);
+};
+
+
+/** UnitTest for LinkedCell::SetIndexToVector().
+ */
+void LinkedCellTest::SetIndexToVectorTest()
+{
+  Vector tester;
+
+  // check center of each cell
+  for (double x=0.5;x<3;x+=1.)
+    for (double y=0.5;y<3;y+=1.)
+      for (double z=0.5;z<3;z+=1.) {
+        tester = Vector(x,y,z);
+        CPPUNIT_ASSERT_EQUAL( true, LC->SetIndexToVector(&tester) );
+      }
+  // check corners of each cell
+  for (double x=1.;x<4;x+=1.)
+    for (double y=1.;y<4;y+=1.)
+      for (double z=1.;z<4;z+=1.) {
+        tester= Vector(x,y,z);
+        cout << "Tester is at " << tester << "." << endl;
+        CPPUNIT_ASSERT_EQUAL( true, LC->SetIndexToVector(&tester) );
+      }
+  // check out of bounds
+  for (double x=0.5-1e-10;x<5;x+=3.1)
+    for (double y=0.5-1e-10;y<5;y+=3.1)
+      for (double z=0.5-1e-10;z<5;z+=3.1) {
+        tester = Vector(x,y,z);
+        cout << "The following test is supposed to fail and produce an ERROR." << endl;
+        CPPUNIT_ASSERT_EQUAL( false, LC->SetIndexToVector(&tester) );
+      }
+  // check nonsense vectors
+  tester= Vector(-423598,3245978,29349);
+  cout << "The following test is supposed to fail and produce an ERROR." << endl;
+  CPPUNIT_ASSERT_EQUAL( false, LC->SetIndexToVector(&tester) );
+};
+
+
+/** UnitTest for LinkedCell::GetNeighbourBounds().
+ */
+void LinkedCellTest::GetNeighbourBoundsTest()
+{
+  Vector tester;
+  int lower[NDIM], upper[NDIM];
+
+  tester= Vector(0.5,0.5,0.5);
+  LC->SetIndexToVector(&tester);
+  LC->GetNeighbourBounds(lower, upper);
+  for (int i=0;i<NDIM;i++)
+    CPPUNIT_ASSERT_EQUAL( 0, lower[i]);
+  for (int i=0;i<NDIM;i++)
+    CPPUNIT_ASSERT_EQUAL( 1, upper[i]);
+};
+
+
+/** UnitTest for LinkedCell::GetallNeighbours().
+ */
+void LinkedCellTest::GetallNeighboursTest()
+{
+  Vector tester;
+  LinkedCell::LinkedNodes *ListOfPoints = NULL;
+  atom *Walker = NULL;
+  size_t size = 0;
+
+  // get all atoms
+  tester= Vector(1.5,1.5,1.5);
+  CPPUNIT_ASSERT_EQUAL ( true, LC->SetIndexToVector(&tester) );
+  ListOfPoints = LC->GetallNeighbours();
+  size = ListOfPoints->size();
+  CPPUNIT_ASSERT_EQUAL( (size_t)27, size );
+  Walker = TestMolecule->start;
+  Walker = TestMolecule->start;
+  while (Walker->next != TestMolecule->end) {
+    Walker = Walker->next;
+    ListOfPoints->remove(Walker);
+    size--;
+    CPPUNIT_ASSERT_EQUAL( size, ListOfPoints->size() );
+  }
+  CPPUNIT_ASSERT_EQUAL( (size_t)0, size );
+  CPPUNIT_ASSERT_EQUAL( (size_t)0, ListOfPoints->size() );
+  CPPUNIT_ASSERT_EQUAL( true, ListOfPoints->empty() );
+  delete(ListOfPoints);
+
+  // get all atoms in one corner
+  tester= Vector(0.5, 0.5, 0.5);
+  CPPUNIT_ASSERT_EQUAL ( true, LC->SetIndexToVector(&tester) );
+  ListOfPoints = LC->GetallNeighbours();
+  size=ListOfPoints->size();
+  CPPUNIT_ASSERT_EQUAL( (size_t)8, size );
+  Walker = TestMolecule->start;
+  while (Walker->next != TestMolecule->end) {
+    Walker = Walker->next;
+    if ((Walker->x[0] <2) && (Walker->x[1] <2) && (Walker->x[2] <2)) {
+      ListOfPoints->remove(Walker);
+      size--;
+      CPPUNIT_ASSERT_EQUAL( size, ListOfPoints->size() );
+    }
+  }
+  CPPUNIT_ASSERT_EQUAL( (size_t)0, size );
+  CPPUNIT_ASSERT_EQUAL( (size_t)0, ListOfPoints->size() );
+  CPPUNIT_ASSERT_EQUAL( true, ListOfPoints->empty() );
+  delete(ListOfPoints);
+
+  // get all atoms from one corner
+  tester = Vector(0.5, 0.5, 0.5);
+  CPPUNIT_ASSERT_EQUAL ( true, LC->SetIndexToVector(&tester) );
+  ListOfPoints = LC->GetallNeighbours(3);
+  size=ListOfPoints->size();
+  CPPUNIT_ASSERT_EQUAL( (size_t)27, size );
+  Walker = TestMolecule->start;
+  while (Walker->next != TestMolecule->end) {
+    Walker = Walker->next;
+    ListOfPoints->remove(Walker);
+    size--;
+    CPPUNIT_ASSERT_EQUAL( size, ListOfPoints->size() );
+  }
+  CPPUNIT_ASSERT_EQUAL( (size_t)0, size );
+  CPPUNIT_ASSERT_EQUAL( (size_t)0, ListOfPoints->size() );
+  CPPUNIT_ASSERT_EQUAL( true, ListOfPoints->empty() );
+  delete(ListOfPoints);
+};
+
+
+/** UnitTest for LinkedCell::GetPointsInsideSphere().
+ */
+void LinkedCellTest::GetPointsInsideSphereTest()
+{
+  Vector tester;
+  LinkedCell::LinkedNodes *ListOfPoints = NULL;
+  atom *Walker = NULL;
+  size_t size = 0;
+
+  // get all points around central arom with radius 1.
+  tester= Vector(1.5,1.5,1.5);
+  CPPUNIT_ASSERT_EQUAL ( true, LC->SetIndexToVector(&tester) );
+  ListOfPoints = LC->GetPointsInsideSphere(1., &tester);
+  size = ListOfPoints->size();
+  CPPUNIT_ASSERT_EQUAL( (size_t)7, size );
+  Walker = TestMolecule->start;
+  while (Walker->next != TestMolecule->end) {
+    Walker = Walker->next;
+    if ((Walker->x.DistanceSquared(tester) - 1.) < MYEPSILON ) {
+      ListOfPoints->remove(Walker);
+      size--;
+      CPPUNIT_ASSERT_EQUAL( size, ListOfPoints->size() );
+    }
+  }
+  CPPUNIT_ASSERT_EQUAL( (size_t)0, size );
+  CPPUNIT_ASSERT_EQUAL( (size_t)0, ListOfPoints->size() );
+  CPPUNIT_ASSERT_EQUAL( true, ListOfPoints->empty() );
+  delete(ListOfPoints);
+};
Index: src/unittests/LinkedCellUnitTest.hpp
===================================================================
--- src/unittests/LinkedCellUnitTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/LinkedCellUnitTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,56 @@
+/*
+ * LinkedCellUnitTest.hpp
+ *
+ *  Created on: Apr 9, 2010
+ *      Author: heber
+ */
+
+#ifndef LINKEDCELLUNITTEST_HPP_
+#define LINKEDCELLUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+
+class element;
+class LinkedCell;
+class molecule;
+class periodentafel;
+
+/********************************************** Test classes **************************************/
+
+class LinkedCellTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( LinkedCellTest) ;
+    CPPUNIT_TEST ( CheckBoundsTest );
+    CPPUNIT_TEST ( GetCurrentCellTest );
+    CPPUNIT_TEST ( GetRelativeToCurrentCellTest );
+    CPPUNIT_TEST ( SetIndexToNodeTest );
+    CPPUNIT_TEST ( SetIndexToVectorTest );
+    CPPUNIT_TEST ( GetNeighbourBoundsTest );
+    CPPUNIT_TEST ( GetallNeighboursTest );
+    CPPUNIT_TEST ( GetPointsInsideSphereTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+      void setUp();
+      void tearDown();
+
+      void GetCurrentCellTest();
+      void GetRelativeToCurrentCellTest();
+      void SetIndexToNodeTest();
+      void SetIndexToVectorTest();
+      void CheckBoundsTest();
+      void GetNeighbourBoundsTest();
+      void GetallNeighboursTest();
+      void GetPointsInsideSphereTest();
+
+private:
+
+      molecule *TestMolecule;
+      element *hydrogen;
+      periodentafel *tafel;
+      LinkedCell *LC;
+};
+
+
+#endif /* LINKEDCELLUNITTEST_HPP_ */
Index: src/unittests/Makefile.am
===================================================================
--- src/unittests/Makefile.am	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/Makefile.am	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -1,2 +1,5 @@
+# PLEASE adhere to the alphabetical ordering in this Makefile!
+# Also indentation by a single tab
+
 INCLUDES = -I$(top_srcdir)/src
 
@@ -4,5 +7,6 @@
 AM_CXXFLAGS = $(CPPUNIT_CFLAGS)
 
-MENUTESTS = ActionSequenceTest
+MENUTESTS = \
+  ActionSequenceTest
 
 TESTS = \
@@ -12,5 +16,9 @@
   AnalysisCorrelationToSurfaceUnitTest \
   AnalysisPairCorrelationUnitTest \
+  atomsCalculationTest \
+  AtomDescriptorTest \
   BondGraphUnitTest \
+  CacheableTest \
+  CountBondsUnitTest \
   GSLMatrixSymmetricUnitTest \
   GSLMatrixUnitTest \
@@ -18,8 +26,15 @@
   InfoUnitTest \
   LinearSystemOfEquationsUnitTest \
+  LinkedCellUnitTest \
   ListOfBondsUnitTest \
   LogUnitTest \
+  manipulateAtomsTest \
   MemoryUsageObserverUnitTest \
   MemoryAllocatorUnitTest \
+  MoleculeDescriptorTest \
+  PlaneUnittest \
+  ObserverTest \
+  ParserUnitTest \
+  SingletonTest \
   StackClassUnitTest \
   TesselationUnitTest \
@@ -27,9 +42,6 @@
   Tesselation_InOutsideUnitTest \
   VectorUnitTest \
-  ObserverTest \
-  CacheableTest \
-  DescriptorUnittest \
-  ${MENUTESTS}  
-    
+  ${MENUTESTS}
+  
   
 check_PROGRAMS = $(TESTS) 
@@ -41,9 +53,14 @@
 TESTSOURCES = \
   ActOnAllUnitTest.cpp \
+  ActionSequenceTest.cpp \
   analysisbondsunittest.cpp \
   AnalysisCorrelationToPointUnitTest.cpp \
   AnalysisCorrelationToSurfaceUnitTest.cpp  \
   AnalysisPairCorrelationUnitTest.cpp \
+  AtomDescriptorTest.cpp \
+  atomsCalculationTest.cpp \
   bondgraphunittest.cpp \
+  CacheableTest.cpp \
+  CountBondsUnitTest.cpp \
   gslmatrixsymmetricunittest.cpp \
   gslmatrixunittest.cpp \
@@ -51,20 +68,57 @@
   infounittest.cpp \
   linearsystemofequationsunittest.cpp \
+  LinkedCellUnitTest.cpp \
   listofbondsunittest.cpp \
   logunittest.cpp \
+  manipulateAtomsTest.cpp \
   memoryallocatorunittest.cpp  \
   memoryusageobserverunittest.cpp \
+  MoleculeDescriptorTest.cpp \
+  PlaneUnittest.cpp \
+  ObserverTest.cpp \
+  ParserUnitTest.cpp \
+  SingletonTest.cpp \
   stackclassunittest.cpp \
   tesselationunittest.cpp \
   tesselation_boundarytriangleunittest.cpp \
   tesselation_insideoutsideunittest.cpp \
-  vectorunittest.cpp \
-  ActionSequenceTest.cpp \
-  ObserverTest.cpp \
-  CacheableTest.cpp \
-  DescriptorUnittest.cpp
+  vectorunittest.cpp
 
 TESTHEADERS = \
-  analysis_correlation.hpp
+  ActOnAllUnitTest.hpp \
+  ActionSequenceTest.hpp \
+  analysisbondsunittest.hpp \
+  AnalysisCorrelationToPointUnitTest.hpp \
+  AnalysisCorrelationToSurfaceUnitTest.hpp  \
+  AnalysisPairCorrelationUnitTest.hpp \
+  AtomDescriptorTest.hpp \
+  atomsCalculationTest.hpp \
+  bondgraphunittest.hpp \
+  CacheableTest.hpp \
+  CountBondsUnitTest.hpp \
+  gslmatrixsymmetricunittest.hpp \
+  gslmatrixunittest.hpp \
+  gslvectorunittest.hpp \
+  infounittest.hpp \
+  linearsystemofequationsunittest.hpp \
+  LinkedCellUnitTest.hpp \
+  listofbondsunittest.hpp \
+  logunittest.hpp \
+  manipulateAtomsTest.hpp \
+  memoryallocatorunittest.hpp  \
+  memoryusageobserverunittest.hpp \
+  MoleculeDescriptorTest.hpp \
+  PlaneUnittest.hpp \
+  ObserverTest.hpp \
+  SingletonTest.hpp \
+  stackclassunittest.hpp \
+  tesselationunittest.hpp \
+  tesselation_boundarytriangleunittest.hpp \
+  tesselation_insideoutsideunittest.hpp \
+  vectorunittest.hpp
+  
+
+ActionSequenceTest_SOURCES = UnitTestMain.cpp ../../../TestRunnerClient.hpp ActionSequenceTest.cpp ActionSequenceTest.hpp
+ActionSequenceTest_LDADD = ${ALLLIBS}
 
 ActOnAllUnitTest_SOURCES = UnitTestMain.cpp ../test/ActOnAllTest.hpp ActOnAllUnitTest.cpp ActOnAllUnitTest.hpp
@@ -83,7 +137,19 @@
 AnalysisPairCorrelationUnitTest_LDADD = ${ALLLIBS}
 
+atomsCalculationTest_SOURCES = UnitTestMain.cpp atomsCalculationTest.cpp atomsCalculationTest.hpp
+atomsCalculationTest_LDADD = ${ALLLIBS}
+
+AtomDescriptorTest_SOURCES = UnitTestMain.cpp AtomDescriptorTest.cpp AtomDescriptorTest.hpp
+AtomDescriptorTest_LDADD = ${ALLLIBS}
+
 BondGraphUnitTest_SOURCES = UnitTestMain.cpp bondgraphunittest.cpp bondgraphunittest.hpp
 BondGraphUnitTest_LDADD = ${ALLLIBS}
 
+CacheableTest_SOURCES = UnitTestMain.cpp CacheableTest.cpp CacheableTest.hpp
+CacheableTest_LDADD = ${ALLLIBS}
+
+CountBondsUnitTest_SOURCES = UnitTestMain.cpp CountBondsUnitTest.cpp CountBondsUnitTest.hpp
+CountBondsUnitTest_LDADD = ${ALLLIBS}
+
 GSLMatrixSymmetricUnitTest_SOURCES = UnitTestMain.cpp gslmatrixsymmetricunittest.cpp gslmatrixsymmetricunittest.hpp
 GSLMatrixSymmetricUnitTest_LDADD = ${GSLLIBS}
@@ -101,4 +167,7 @@
 LinearSystemOfEquationsUnitTest_LDADD = ${ALLLIBS}
 
+LinkedCellUnitTest_SOURCES = UnitTestMain.cpp LinkedCellUnitTest.cpp LinkedCellUnitTest.hpp 
+LinkedCellUnitTest_LDADD = ${ALLLIBS}
+
 ListOfBondsUnitTest_SOURCES = UnitTestMain.cpp listofbondsunittest.cpp listofbondsunittest.hpp
 ListOfBondsUnitTest_LDADD = ${ALLLIBS}
@@ -107,4 +176,7 @@
 LogUnitTest_LDADD = ${ALLLIBS}
 
+manipulateAtomsTest_SOURCES = UnitTestMain.cpp manipulateAtomsTest.cpp manipulateAtomsTest.hpp
+manipulateAtomsTest_LDADD = ${ALLLIBS}
+
 MemoryAllocatorUnitTest_SOURCES = UnitTestMain.cpp memoryallocatorunittest.cpp memoryallocatorunittest.hpp 
 MemoryAllocatorUnitTest_LDADD = ${ALLLIBS}
@@ -113,4 +185,19 @@
 MemoryUsageObserverUnitTest_LDADD = ${ALLLIBS}
 
+MoleculeDescriptorTest_SOURCES = UnitTestMain.cpp MoleculeDescriptorTest.cpp MoleculeDescriptorTest.hpp
+MoleculeDescriptorTest_LDADD = ${ALLLIBS}
+
+ObserverTest_SOURCES = UnitTestMain.cpp ObserverTest.cpp ObserverTest.hpp
+ObserverTest_LDADD = ${ALLLIBS}
+
+ParserUnitTest_SOURCES = UnitTestMain.cpp ParserUnitTest.cpp ParserUnitTest.hpp
+ParserUnitTest_LDADD = ${ALLLIBS}
+
+PlaneUnittest_SOURCES = UnitTestMain.cpp PlaneUnittest.cpp PlaneUnittest.hpp
+PlaneUnittest_LDADD = ${ALLLIBS}
+
+SingletonTest_SOURCES = UnitTestMain.cpp SingletonTest.cpp SingletonTest.hpp
+SingletonTest_LDADD = $(BOOST_LIB) ${BOOST_THREAD_LIB}
+
 StackClassUnitTest_SOURCES = UnitTestMain.cpp stackclassunittest.cpp stackclassunittest.hpp
 StackClassUnitTest_LDADD = ${ALLLIBS}
@@ -125,22 +212,9 @@
 Tesselation_InOutsideUnitTest_LDADD = ${ALLLIBS}
 
+TestRunner_SOURCES = TestRunnerMain.cpp $(TESTSOURCES) $(TESTHEADERS)
+TestRunner_LDADD = ${ALLLIBS}
+
 VectorUnitTest_SOURCES = UnitTestMain.cpp vectorunittest.cpp vectorunittest.hpp 
 VectorUnitTest_LDADD = ${ALLLIBS}
 
-ActionSequenceTest_SOURCES = UnitTestMain.cpp ../../../TestRunnerClient.hpp ActionSequenceTest.cpp ActionSequenceTest.hpp
-ActionSequenceTest_LDADD = ${ALLLIBS}
-
-ObserverTest_SOURCES = UnitTestMain.cpp ObserverTest.cpp ObserverTest.hpp
-ObserverTest_LDADD = ${ALLLIBS}
-
-CacheableTest_SOURCES = UnitTestMain.cpp CacheableTest.cpp CacheableTest.hpp
-CacheableTest_LDADD = ${ALLLIBS}
-
-DescriptorUnittest_SOURCES = UnitTestMain.cpp DescriptorUnittest.cpp DescriptorUnittest.hpp
-DescriptorUnittest_LDADD = ${ALLLIBS}
-
-TestRunner_SOURCES = TestRunnerMain.cpp $(TESTSOURCES) $(TESTHEADERS)
-TestRunner_LDADD = ${ALLLIBS}
-
 #AUTOMAKE_OPTIONS = parallel-tests
-
Index: src/unittests/MoleculeDescriptorTest.cpp
===================================================================
--- src/unittests/MoleculeDescriptorTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/MoleculeDescriptorTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,158 @@
+/*
+ * MoleculeDescriptorTest.cpp
+ *
+ *  Created on: Mar 4, 2010
+ *      Author: crueger
+ */
+
+#include "MoleculeDescriptorTest.hpp"
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+#include <iostream>
+
+#include <Descriptors/MoleculeDescriptor.hpp>
+#include <Descriptors/MoleculeIdDescriptor.hpp>
+
+#include "World.hpp"
+#include "molecule.hpp"
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+/********************************************** Test classes **************************************/
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( MoleculeDescriptorTest );
+
+// set up and tear down
+void MoleculeDescriptorTest::setUp(){
+  World::getInstance();
+  for(int i=0;i<MOLECULE_COUNT;++i){
+    molecules[i]= World::getInstance().createMolecule();
+    moleculeIds[i]= molecules[i]->getId();
+  }
+}
+
+void MoleculeDescriptorTest::tearDown(){
+  World::purgeInstance();
+}
+
+// some helper functions
+static bool hasAllMolecules(std::vector<molecule*> molecules,moleculeId_t ids[MOLECULE_COUNT], std::set<moleculeId_t> excluded = std::set<moleculeId_t>()){
+  for(int i=0;i<MOLECULE_COUNT;++i){
+    moleculeId_t id = ids[i];
+    if(!excluded.count(id)){
+      std::vector<molecule*>::iterator iter;
+      bool res=false;
+      for(iter=molecules.begin();iter!=molecules.end();++iter){
+        res |= (*iter)->getId() == id;
+      }
+      if(!res) {
+        cout << "Molecule " << id << " missing in returned list" << endl;
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+static bool hasNoDuplicateMolecules(std::vector<molecule*> molecules){
+  std::set<moleculeId_t> found;
+  std::vector<molecule*>::iterator iter;
+  for(iter=molecules.begin();iter!=molecules.end();++iter){
+    int id = (*iter)->getId();
+    if(found.count(id))
+      return false;
+    found.insert(id);
+  }
+  return true;
+}
+
+
+void MoleculeDescriptorTest::MoleculeBaseSetsTest(){
+  std::vector<molecule*> allMolecules = World::getInstance().getAllMolecules(AllMolecules());
+  CPPUNIT_ASSERT_EQUAL( true , hasAllMolecules(allMolecules,moleculeIds));
+  CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateMolecules(allMolecules));
+
+  std::vector<molecule*> noMolecules = World::getInstance().getAllMolecules(NoMolecules());
+  CPPUNIT_ASSERT_EQUAL( true , noMolecules.empty());
+}
+void MoleculeDescriptorTest::MoleculeIdTest(){
+  // test Molecules from boundaries and middle of the set
+  molecule* testMolecule;
+  testMolecule = World::getInstance().getMolecule(MoleculeById(moleculeIds[0]));
+  CPPUNIT_ASSERT(testMolecule);
+  CPPUNIT_ASSERT_EQUAL( moleculeIds[0], testMolecule->getId());
+  testMolecule = World::getInstance().getMolecule(MoleculeById(moleculeIds[MOLECULE_COUNT/2]));
+  CPPUNIT_ASSERT(testMolecule);
+  CPPUNIT_ASSERT_EQUAL( moleculeIds[MOLECULE_COUNT/2], testMolecule->getId());
+  testMolecule = World::getInstance().getMolecule(MoleculeById(moleculeIds[MOLECULE_COUNT-1]));
+  CPPUNIT_ASSERT(testMolecule);
+  CPPUNIT_ASSERT_EQUAL( moleculeIds[MOLECULE_COUNT-1], testMolecule->getId());
+
+  // find some ID that has not been created
+  moleculeId_t outsideId=0;
+  bool res = false;
+  for(outsideId=0;!res;++outsideId) {
+    res = true;
+    for(int i = 0; i < MOLECULE_COUNT; ++i){
+      res &= moleculeIds[i]!=outsideId;
+    }
+  }
+  // test from outside of set
+  testMolecule = World::getInstance().getMolecule(MoleculeById(outsideId));
+  CPPUNIT_ASSERT(!testMolecule);
+}
+void MoleculeDescriptorTest::MoleculeCalcTest(){
+  // test some elementary set operations
+  {
+    std::vector<molecule*> testMolecules = World::getInstance().getAllMolecules(AllMolecules()||NoMolecules());
+    CPPUNIT_ASSERT_EQUAL( true , hasAllMolecules(testMolecules,moleculeIds));
+    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateMolecules(testMolecules));
+  }
+
+  {
+    std::vector<molecule*> testMolecules = World::getInstance().getAllMolecules(NoMolecules()||AllMolecules());
+    CPPUNIT_ASSERT_EQUAL( true , hasAllMolecules(testMolecules,moleculeIds));
+    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateMolecules(testMolecules));
+  }
+
+  {
+    std::vector<molecule*> testMolecules = World::getInstance().getAllMolecules(NoMolecules()&&AllMolecules());
+    CPPUNIT_ASSERT_EQUAL( true , testMolecules.empty());
+  }
+
+  {
+    std::vector<molecule*> testMolecules = World::getInstance().getAllMolecules(AllMolecules()&&NoMolecules());
+    CPPUNIT_ASSERT_EQUAL( true , testMolecules.empty());
+  }
+
+  {
+    std::vector<molecule*> testMolecules = World::getInstance().getAllMolecules(!AllMolecules());
+    CPPUNIT_ASSERT_EQUAL( true , testMolecules.empty());
+  }
+
+  {
+    std::vector<molecule*> testMolecules = World::getInstance().getAllMolecules(!NoMolecules());
+    CPPUNIT_ASSERT_EQUAL( true , hasAllMolecules(testMolecules,moleculeIds));
+    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateMolecules(testMolecules));
+  }
+
+  // exclude and include some molecules
+  {
+    std::vector<molecule*> testMolecules = World::getInstance().getAllMolecules(AllMolecules()&&(!MoleculeById(moleculeIds[MOLECULE_COUNT/2])));
+    std::set<moleculeId_t> excluded;
+    excluded.insert(moleculeIds[MOLECULE_COUNT/2]);
+    CPPUNIT_ASSERT_EQUAL( true , hasAllMolecules(testMolecules,moleculeIds,excluded));
+    CPPUNIT_ASSERT_EQUAL( true , hasNoDuplicateMolecules(testMolecules));
+    CPPUNIT_ASSERT_EQUAL( (size_t)(MOLECULE_COUNT-1), testMolecules.size());
+  }
+
+  {
+    std::vector<molecule*> testMolecules = World::getInstance().getAllMolecules(NoMolecules()||(MoleculeById(moleculeIds[MOLECULE_COUNT/2])));
+    CPPUNIT_ASSERT_EQUAL( (size_t)1, testMolecules.size());
+    CPPUNIT_ASSERT_EQUAL( moleculeIds[MOLECULE_COUNT/2], testMolecules[0]->getId());
+  }
+}
Index: src/unittests/MoleculeDescriptorTest.hpp
===================================================================
--- src/unittests/MoleculeDescriptorTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/MoleculeDescriptorTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,40 @@
+/*
+ * MoleculeDescriptorTest.hpp
+ *
+ *  Created on: Mar 4, 2010
+ *      Author: crueger
+ */
+
+#ifndef MOLECULEDESCRIPTORTEST_HPP_
+#define MOLECULEDESCRIPTORTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "types.hpp"
+
+#define MOLECULE_COUNT (10)
+
+class molecule;
+
+class MoleculeDescriptorTest : public CppUnit::TestFixture
+{
+  CPPUNIT_TEST_SUITE( MoleculeDescriptorTest );
+  CPPUNIT_TEST ( MoleculeBaseSetsTest );
+  CPPUNIT_TEST ( MoleculeIdTest );
+  CPPUNIT_TEST ( MoleculeCalcTest );
+  CPPUNIT_TEST_SUITE_END();
+
+public:
+  void setUp();
+  void tearDown();
+
+  void MoleculeBaseSetsTest();
+  void MoleculeIdTest();
+  void MoleculeCalcTest();
+
+private:
+  molecule *molecules [MOLECULE_COUNT];
+  moleculeId_t moleculeIds [MOLECULE_COUNT];
+};
+
+#endif /* MOLECULEDESCRIPTORTEST_HPP_ */
Index: src/unittests/ObserverTest.cpp
===================================================================
--- src/unittests/ObserverTest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/ObserverTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -13,4 +13,5 @@
 
 #include "Patterns/Observer.hpp"
+#include "Helpers/Assert.hpp"
 
 #include <iostream>
@@ -44,5 +45,5 @@
   void changeMethod() {
     OBSERVE;
-    int i;
+    int i = 0;
     i++;
   }
@@ -53,5 +54,5 @@
   void changeMethod1() {
     OBSERVE;
-    int i;
+    int i = 0;
     i++;
   }
@@ -59,7 +60,41 @@
   void changeMethod2() {
     OBSERVE;
-    int i;
+    int i = 0;
     i++;
     changeMethod1();
+  }
+};
+
+class BlockObservable : public Observable {
+public:
+  void changeMethod1(){
+    OBSERVE;
+    // test if we report correctly as blocked
+    CPPUNIT_ASSERT(isBlocked());
+  }
+
+  void changeMethod2(){
+    OBSERVE;
+    internalMethod1();
+    internalMethod2();
+  }
+
+  void internalMethod1(){
+    // we did not block, but our caller did...
+    // see if this is found
+    CPPUNIT_ASSERT(isBlocked());
+  }
+
+  void internalMethod2(){
+    OBSERVE;
+    // Both this method and the caller do block
+    // Does the reporting still work as expected?
+    CPPUNIT_ASSERT(isBlocked());
+  }
+
+  void noChangeMethod(){
+    // No Block introduced here
+    // reported correctely?
+    CPPUNIT_ASSERT(!isBlocked());
   }
 };
@@ -76,5 +111,5 @@
   void changeMethod() {
     OBSERVE;
-    int i;
+    int i = 0;
     i++;
     subObservable->changeMethod();
@@ -83,11 +118,59 @@
 };
 
+class NotificationObservable : public Observable {
+public:
+  NotificationObservable() :
+      notification1(new Notification(this)),
+      notification2(new Notification(this))
+  {}
+
+  ~NotificationObservable(){
+    delete notification1;
+    delete notification2;
+  }
+
+  void operation1(){
+    OBSERVE;
+    NOTIFY(notification1);
+  }
+
+  void operation2(){
+    OBSERVE;
+    NOTIFY(notification2);
+  }
+
+  Notification_ptr notification1;
+  Notification_ptr notification2;
+};
+
+class NotificationObserver : public Observer {
+public:
+  NotificationObserver(Notification_ptr notification) :
+    requestedNotification(notification),
+    wasNotified(false)
+  {}
+
+  void update(Observable*){}
+  void subjectKilled(Observable*){}
+  void recieveNotification(Observable *publisher, Notification_ptr notification){
+    ASSERT(requestedNotification==notification,"Notification received that was not requested");
+    wasNotified = true;
+  }
+
+  Notification_ptr requestedNotification;
+
+  bool wasNotified;
+};
+
 /******************* actuall tests ***************/
 
 void ObserverTest::setUp() {
+  ASSERT_DO(Assert::Throw);
   simpleObservable1 = new SimpleObservable();
   simpleObservable2 = new SimpleObservable();
   callObservable = new CallObservable();
   superObservable = new SuperObservable();
+  blockObservable = new BlockObservable();
+  notificationObservable = new NotificationObservable();
 
   observer1 = new UpdateCountObserver();
@@ -95,4 +178,8 @@
   observer3 = new UpdateCountObserver();
   observer4 = new UpdateCountObserver();
+
+  notificationObserver1 = new NotificationObserver(notificationObservable->notification1);
+  notificationObserver2 = new NotificationObserver(notificationObservable->notification2);
+
 }
 
@@ -102,4 +189,6 @@
   delete callObservable;
   delete superObservable;
+  delete blockObservable;
+  delete notificationObservable;
 
   delete observer1;
@@ -107,4 +196,6 @@
   delete observer3;
   delete observer4;
+  delete notificationObserver1;
+  delete notificationObserver2;
 }
 
@@ -163,4 +254,28 @@
 }
 
+void ObserverTest::doesNotifyTest(){
+  notificationObservable->signOn(notificationObserver1,
+                                 notificationObservable->notification1);
+  notificationObservable->signOn(notificationObserver2,
+                                 notificationObservable->notification2);
+
+  notificationObservable->operation1();
+  CPPUNIT_ASSERT(notificationObserver1->wasNotified);
+  CPPUNIT_ASSERT(!notificationObserver2->wasNotified);
+
+  notificationObserver1->wasNotified=false;
+
+  notificationObservable->operation2();
+  CPPUNIT_ASSERT(!notificationObserver1->wasNotified);
+  CPPUNIT_ASSERT(notificationObserver2->wasNotified);
+
+}
+
+void ObserverTest::doesReportTest(){
+  // Actual checks are in the Stub-methods for this
+  blockObservable->changeMethod1();
+  blockObservable->changeMethod2();
+  blockObservable->noChangeMethod();
+}
 
 void ObserverTest::CircleDetectionTest() {
@@ -174,5 +289,5 @@
   // make this Observable its own subject. NEVER DO THIS IN ACTUAL CODE
   simpleObservable1->signOn(simpleObservable1);
-  simpleObservable1->changeMethod();
+  CPPUNIT_ASSERT_THROW(simpleObservable1->changeMethod(),Assert::AssertionFailure);
 
   // more complex test
@@ -180,5 +295,5 @@
   simpleObservable1->signOn(simpleObservable2);
   simpleObservable2->signOn(simpleObservable1);
-  simpleObservable1->changeMethod();
+  CPPUNIT_ASSERT_THROW(simpleObservable1->changeMethod(),Assert::AssertionFailure);
   simpleObservable1->signOff(simpleObservable2);
   simpleObservable2->signOff(simpleObservable1);
Index: src/unittests/ObserverTest.hpp
===================================================================
--- src/unittests/ObserverTest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/ObserverTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -13,7 +13,10 @@
 // forward declaration for test stubs
 class UpdateCountObserver;
+class NotificationObserver;
 class SimpleObservable;
 class CallObservable;
 class SuperObservable;
+class BlockObservable;
+class NotificationObservable;
 
 
@@ -24,4 +27,6 @@
   CPPUNIT_TEST ( doesBlockUpdateTest );
   CPPUNIT_TEST ( doesSubObservableTest );
+  CPPUNIT_TEST ( doesNotifyTest );
+  CPPUNIT_TEST ( doesReportTest );
   CPPUNIT_TEST ( CircleDetectionTest );
   CPPUNIT_TEST_SUITE_END();
@@ -34,4 +39,6 @@
   void doesBlockUpdateTest();
   void doesSubObservableTest();
+  void doesNotifyTest();
+  void doesReportTest();
   void CircleDetectionTest();
 
@@ -42,8 +49,13 @@
   UpdateCountObserver *observer4;
 
+  NotificationObserver *notificationObserver1;
+  NotificationObserver *notificationObserver2;
+
   SimpleObservable *simpleObservable1;
   SimpleObservable *simpleObservable2;
   CallObservable *callObservable;
+  BlockObservable *blockObservable;
   SuperObservable *superObservable;
+  NotificationObservable *notificationObservable;
 };
 
Index: src/unittests/ParserUnitTest.cpp
===================================================================
--- src/unittests/ParserUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/ParserUnitTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,186 @@
+/*
+ * ParserUnitTest.cpp
+ *
+ *  Created on: Mar 3, 2010
+ *      Author: metzler
+ */
+
+#include "ParserUnitTest.hpp"
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include "Parser/XyzParser.hpp"
+#include "Parser/TremoloParser.hpp"
+#include "World.hpp"
+#include "atom.hpp"
+#include "element.hpp"
+#include "periodentafel.hpp"
+#include "Descriptors/AtomTypeDescriptor.hpp"
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+using namespace std;
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( ParserUnitTest );
+
+
+void ParserUnitTest::setUp() {
+  element* oxygen = new element();
+  oxygen->symbol[0] = 'O';
+  oxygen->Z = 8;
+  World::getInstance().getPeriode()->AddElement(oxygen);
+
+  element* hydrogen = new element();
+  hydrogen->symbol[0] = 'H';
+  hydrogen->Z = 1;
+  World::getInstance().getPeriode()->AddElement(hydrogen);
+}
+
+void ParserUnitTest::tearDown() {
+  World::purgeInstance();
+}
+
+/************************************ tests ***********************************/
+
+void ParserUnitTest::rewriteAnXyzTest() {
+  cout << "Testing the XYZ parser." << endl;
+  XyzParser* testParser = new XyzParser();
+  string waterXyz = "3\nH2O: water molecule\nO\t0.000000\t0.000000\t0.000000\nH\t0.758602\t0.000000\t0.504284\nH\t0.758602\t0.000000\t-0.504284\n";
+  stringstream input;
+  input << waterXyz;
+  testParser->load(&input);
+
+  CPPUNIT_ASSERT_EQUAL(3, World::getInstance().numAtoms());
+
+  string newWaterXyz = "";
+  stringstream output;
+  testParser->save(&output);
+  newWaterXyz = output.str();
+
+  CPPUNIT_ASSERT(waterXyz == newWaterXyz);
+}
+
+void ParserUnitTest::readTremoloPreliminaryCommentsTest() {
+  cout << "Testing the tremolo parser." << endl;
+  TremoloParser* testParser = new TremoloParser();
+  stringstream input, output;
+  string waterTremolo;
+
+  // Atomdata beginning with "# ATOMDATA"
+  waterTremolo = "# ATOMDATA\tId\tname\tType\tx=3\n";
+  input << waterTremolo;
+  testParser->load(&input);
+  testParser->save(&output);
+  CPPUNIT_ASSERT(waterTremolo == output.str());
+  input.clear();
+  output.clear();
+
+  // Atomdata beginning with "#ATOMDATA"
+  waterTremolo = "#\n#ATOMDATA Id name Type x=3\n1 hydrogen H 3.0 4.5 0.1\n\n";
+  input << waterTremolo;
+  testParser->load(&input);
+  testParser->save(&output);
+  CPPUNIT_ASSERT(output.str().find("hydrogen") != string::npos);
+  input.clear();
+  output.clear();
+
+  // Invalid key in Atomdata line
+  waterTremolo = "#\n#ATOMDATA Id name foo Type x=3\n\n\n";
+  input << waterTremolo;
+  testParser->load(&input);
+  //TODO: proove invalidity
+  input.clear();
+}
+
+void ParserUnitTest::readTremoloCoordinatesTest() {
+  TremoloParser* testParser = new TremoloParser();
+  stringstream input;
+  string waterTremolo;
+
+  // One simple data line
+  waterTremolo = "#\n#ATOMDATA Id name Type x=3\n1 hydrogen H 3.0 4.5 0.1\n\n";
+  input << waterTremolo;
+  testParser->load(&input);
+  CPPUNIT_ASSERT(World::getInstance().getAtom(AtomByType(1))->x[0] == 3.0);
+  input.clear();
+}
+
+void ParserUnitTest::readTremoloVelocityTest() {
+  TremoloParser* testParser = new TremoloParser();
+  stringstream input;
+  string waterTremolo;
+
+  // One simple data line
+  waterTremolo = "#\n#ATOMDATA Id name Type u=3\n1 hydrogen H 3.0 4.5 0.1\n\n";
+  input << waterTremolo;
+  testParser->load(&input);
+  CPPUNIT_ASSERT(World::getInstance().getAtom(AtomByType(1))->v[0] == 3.0);
+  input.clear();
+}
+
+void ParserUnitTest::readTremoloNeighborInformationTest() {
+  TremoloParser* testParser = new TremoloParser();
+  stringstream input;
+  string waterTremolo;
+
+  // Neighbor data
+  waterTremolo = "#\n#ATOMDATA Id Type neighbors=2\n1 H 3 0\n2 H 3 0\n3 O 1 2\n";
+  input << waterTremolo;
+  testParser->load(&input);
+
+  CPPUNIT_ASSERT_EQUAL(3, World::getInstance().numAtoms());
+  CPPUNIT_ASSERT(World::getInstance().getAtom(AtomByType(8))->
+      IsBondedTo(World::getInstance().getAtom(AtomByType(1))));
+  input.clear();
+}
+
+void ParserUnitTest::readAndWriteTremoloImprDataInformationTest() {
+  TremoloParser* testParser = new TremoloParser();
+  stringstream input, output;
+  string waterTremolo;
+
+  // Neighbor data
+  waterTremolo = "#\n#ATOMDATA Id Type imprData\n8 H 9-10\n9 H 10-8,8-10\n10 O -\n";
+  input << waterTremolo;
+  testParser->load(&input);
+  testParser->save(&output);
+  CPPUNIT_ASSERT_EQUAL(3, World::getInstance().numAtoms());
+  CPPUNIT_ASSERT(output.str().find("2-0,0-2") != string::npos);
+  input.clear();
+  output.clear();
+}
+
+void ParserUnitTest::readAndWriteTremoloTorsionInformationTest() {
+  TremoloParser* testParser = new TremoloParser();
+  stringstream input, output;
+  string waterTremolo;
+
+  // Neighbor data
+  waterTremolo = "#\n#ATOMDATA Id Type torsion\n8 H 9-10\n9 H 10-8,8-10\n10 O -\n";
+  input << waterTremolo;
+  testParser->load(&input);
+  testParser->save(&output);
+  CPPUNIT_ASSERT_EQUAL(3, World::getInstance().numAtoms());
+  CPPUNIT_ASSERT(output.str().find("2-0,0-2") != string::npos);
+  input.clear();
+  output.clear();
+}
+
+void ParserUnitTest::writeTremoloTest() {
+  TremoloParser* testParser = new TremoloParser();
+  stringstream output;
+
+  // with the maximum number of fields and minimal information, default values are printed
+  atom* newAtom = World::getInstance().createAtom();
+  newAtom->type = World::getInstance().getPeriode()->FindElement(1);
+  testParser->setFieldsForSave("x=3 u=3 F stress Id neighbors=5 imprData GroupMeasureTypeNo Type extType name resName chainID resSeq occupancy tempFactor segID Charge charge GrpTypeNo torsion");
+  testParser->save(&output);
+  CPPUNIT_ASSERT(output.str() == "# ATOMDATA\tx=3\tu=3\tF\tstress\tId\tneighbors=5\timprData\tGroupMeasureTypeNo\tType\textType\tname\tresName\tchainID\tresSeq\toccupancy\ttempFactor\tsegID\tCharge\tcharge\tGrpTypeNo\ttorsion\n0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t-\t0\tH\t-\t-\t-\t0\t0\t0\t0\t0\t0\t0\t0\t-\t\n");
+
+  cout << "testing the tremolo parser is done" << endl;
+}
Index: src/unittests/ParserUnitTest.hpp
===================================================================
--- src/unittests/ParserUnitTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/ParserUnitTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,40 @@
+/*
+ * ParserUnitTest.hpp
+ *
+ *  Created on: Mar 3, 2010
+ *      Author: metzler
+ */
+#ifndef PARSERUNITTEST_HPP_
+#define PARSERUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <string>
+
+class ParserUnitTest :  public CppUnit::TestFixture
+{
+  CPPUNIT_TEST_SUITE( ParserUnitTest ) ;
+  CPPUNIT_TEST ( rewriteAnXyzTest );
+  CPPUNIT_TEST ( readTremoloPreliminaryCommentsTest );
+  CPPUNIT_TEST ( readTremoloCoordinatesTest );
+  CPPUNIT_TEST ( readTremoloVelocityTest );
+  CPPUNIT_TEST ( readTremoloNeighborInformationTest );
+  CPPUNIT_TEST ( readAndWriteTremoloImprDataInformationTest );
+  CPPUNIT_TEST ( readAndWriteTremoloTorsionInformationTest );
+  CPPUNIT_TEST ( writeTremoloTest );
+  CPPUNIT_TEST_SUITE_END();
+
+public:
+  void setUp();
+  void tearDown();
+
+  void rewriteAnXyzTest();
+  void readTremoloPreliminaryCommentsTest();
+  void readTremoloCoordinatesTest();
+  void readTremoloVelocityTest();
+  void readTremoloNeighborInformationTest();
+  void readAndWriteTremoloImprDataInformationTest();
+  void readAndWriteTremoloTorsionInformationTest();
+  void writeTremoloTest();
+};
+
+#endif /* PARSERUNITTEST_HPP_ */
Index: src/unittests/PlaneUnittest.cpp
===================================================================
--- src/unittests/PlaneUnittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/PlaneUnittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,157 @@
+/*
+ * PlaneUnittest.cpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#include "PlaneUnittest.hpp"
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+#include "vector.hpp"
+
+CPPUNIT_TEST_SUITE_REGISTRATION( PlaneUnittest );
+
+void PlaneUnittest::setUp(){
+  p1 = new Plane(e1,e2,e3);
+  p2 = new Plane(e1,e2,zeroVec);
+  p3 = new Plane(e1,zeroVec,e3);
+  p4 = new Plane(zeroVec,e2,e3);
+}
+
+void PlaneUnittest::tearDown(){
+  delete p1;
+  delete p2;
+  delete p3;
+  delete p4;
+}
+
+void PlaneUnittest::constructionErrorTest(){
+  // try several method of construction..
+  // see if error checking works
+
+  // three points
+  CPPUNIT_ASSERT_NO_THROW(Plane(e1,e2,e3));
+  // when only two points are differnt this gives an error
+  CPPUNIT_ASSERT_THROW(Plane(e1,e2,e2),LinearDependenceException);
+  // same with only one point
+  CPPUNIT_ASSERT_THROW(Plane(e1,e1,e1),LinearDependenceException);
+
+  // use two vector giving two directions
+  CPPUNIT_ASSERT_NO_THROW(Plane(e1,e2,0));
+  // and again this is actually only one vector
+  CPPUNIT_ASSERT_THROW(Plane(e1,e1,0),LinearDependenceException);
+  // Zero vector does not give a good direction
+  CPPUNIT_ASSERT_THROW(Plane(e1,zeroVec,0),ZeroVectorException);
+
+  // use a normalvector and an scalar offset
+  CPPUNIT_ASSERT_NO_THROW(Plane(e1,0));
+  // The zero vector is no good as a normalvector
+  CPPUNIT_ASSERT_THROW(Plane(zeroVec,0),ZeroVectorException);
+
+  // use a normalvector and an offset vector
+  CPPUNIT_ASSERT_NO_THROW(Plane(e1,zeroVec));
+  // and the bad zeroVector again
+  CPPUNIT_ASSERT_THROW(Plane(zeroVec,zeroVec),ZeroVectorException);
+}
+
+
+// we need to test normals independent of the direction
+bool testNormal(const Vector &normal1, const Vector &normal2){
+  return (normal1==normal2) || (normal1==-1*normal2);
+}
+
+void PlaneUnittest::constructionResultTest(){
+  {
+    // construct with three points on plane
+    Plane p1(e1,e2,zeroVec);
+    CPPUNIT_ASSERT(testNormal(e3,p1.getNormal()));
+    CPPUNIT_ASSERT_EQUAL(0.,p1.getOffset());
+
+    Plane p2(e1,e3,zeroVec);
+    CPPUNIT_ASSERT(testNormal(e2,p2.getNormal()));
+    CPPUNIT_ASSERT_EQUAL(0.,p2.getOffset());
+
+    Plane p3(e2,e3,zeroVec);
+    CPPUNIT_ASSERT(testNormal(e1,p3.getNormal()));
+    CPPUNIT_ASSERT_EQUAL(0.,p3.getOffset());
+  }
+  {
+    // construct with two directions + offset
+    Plane p1(e1,e2,0);
+    CPPUNIT_ASSERT(testNormal(e3,p1.getNormal()));
+    CPPUNIT_ASSERT_EQUAL(0.,p1.getOffset());
+
+    Plane p2(e1,e3,0);
+    CPPUNIT_ASSERT(testNormal(e2,p2.getNormal()));
+    CPPUNIT_ASSERT_EQUAL(0.,p2.getOffset());
+
+    Plane p3(e2,e3,0);
+    CPPUNIT_ASSERT(testNormal(e1,p3.getNormal()));
+    CPPUNIT_ASSERT_EQUAL(0.,p3.getOffset());
+  }
+}
+
+void PlaneUnittest::pointsTest(){
+  std::vector<Vector> points1 = p1->getPointsOnPlane();
+  CPPUNIT_ASSERT(p1->isContained(points1[0]));
+  CPPUNIT_ASSERT(p1->isContained(points1[1]));
+  CPPUNIT_ASSERT(p1->isContained(points1[2]));
+  // check that the three points differ
+  CPPUNIT_ASSERT(points1[0]!=points1[1]);
+  CPPUNIT_ASSERT(points1[0]!=points1[2]);
+  CPPUNIT_ASSERT(points1[1]!=points1[2]);
+
+
+  std::vector<Vector> points2 = p2->getPointsOnPlane();
+  CPPUNIT_ASSERT(p2->isContained(points2[0]));
+  CPPUNIT_ASSERT(p2->isContained(points2[1]));
+  CPPUNIT_ASSERT(p2->isContained(points2[2]));
+  // check that the three points differ
+  CPPUNIT_ASSERT(points2[0]!=points2[1]);
+  CPPUNIT_ASSERT(points2[0]!=points2[2]);
+  CPPUNIT_ASSERT(points2[1]!=points2[2]);
+
+  std::vector<Vector> points3 = p3->getPointsOnPlane();
+  CPPUNIT_ASSERT(p3->isContained(points3[0]));
+  CPPUNIT_ASSERT(p3->isContained(points3[1]));
+  CPPUNIT_ASSERT(p3->isContained(points3[2]));
+  // check that the three points differ
+  CPPUNIT_ASSERT(points3[0]!=points3[1]);
+  CPPUNIT_ASSERT(points3[0]!=points3[2]);
+  CPPUNIT_ASSERT(points3[1]!=points3[2]);
+
+  std::vector<Vector> points4 = p4->getPointsOnPlane();
+  CPPUNIT_ASSERT(p4->isContained(points4[0]));
+  CPPUNIT_ASSERT(p4->isContained(points4[1]));
+  CPPUNIT_ASSERT(p4->isContained(points4[2]));
+  // check that the three points differ
+  CPPUNIT_ASSERT(points4[0]!=points4[1]);
+  CPPUNIT_ASSERT(points4[0]!=points4[2]);
+  CPPUNIT_ASSERT(points4[1]!=points4[2]);
+}
+
+
+void PlaneUnittest::operationsTest(){
+  {
+    Vector t = (1./3.)*(e1+e2+e3);
+    CPPUNIT_ASSERT(fabs(p1->distance(zeroVec)-t.Norm()) < MYEPSILON);
+    CPPUNIT_ASSERT_EQUAL(t,p1->getClosestPoint(zeroVec));
+  }
+
+  CPPUNIT_ASSERT(fabs(p2->distance(e3)-1) < MYEPSILON);
+  CPPUNIT_ASSERT_EQUAL(zeroVec,p2->getClosestPoint(e3));
+  CPPUNIT_ASSERT(fabs(p3->distance(e2)-1) < MYEPSILON);
+  CPPUNIT_ASSERT_EQUAL(zeroVec,p3->getClosestPoint(e2));
+  CPPUNIT_ASSERT(fabs(p4->distance(e1)-1) < MYEPSILON);
+  CPPUNIT_ASSERT_EQUAL(zeroVec,p4->getClosestPoint(e1));
+
+
+}
Index: src/unittests/PlaneUnittest.hpp
===================================================================
--- src/unittests/PlaneUnittest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/PlaneUnittest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,40 @@
+/*
+ * PlaneUnittest.hpp
+ *
+ *  Created on: Apr 30, 2010
+ *      Author: crueger
+ */
+
+#ifndef PLANEUNITTEST_HPP_
+#define PLANEUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "Plane.hpp"
+
+class PlaneUnittest : public CppUnit::TestFixture
+{
+  CPPUNIT_TEST_SUITE( PlaneUnittest) ;
+  CPPUNIT_TEST ( constructionErrorTest );
+  CPPUNIT_TEST ( constructionResultTest );
+  CPPUNIT_TEST ( pointsTest );
+  CPPUNIT_TEST ( operationsTest );
+  CPPUNIT_TEST_SUITE_END();
+
+public:
+  void setUp();
+  void tearDown();
+
+  void constructionErrorTest();
+  void constructionResultTest();
+  void pointsTest();
+  void operationsTest();
+
+private:
+  Plane *p1;
+  Plane *p2;
+  Plane *p3;
+  Plane *p4;
+};
+
+#endif /* PLANEUNITTEST_HPP_ */
Index: src/unittests/SingletonTest.cpp
===================================================================
--- src/unittests/SingletonTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/SingletonTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,143 @@
+/*
+ * SingletonTest.cpp
+ *
+ *  Created on: Mar 11, 2010
+ *      Author: crueger
+ */
+
+#include "SingletonTest.hpp"
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+#include <iostream>
+
+#include "Patterns/Singleton.hpp"
+#include "Patterns/Singleton_impl.hpp"
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+CPPUNIT_TEST_SUITE_REGISTRATION( SingletonTest );
+
+// some necessary stubs
+class SingletonStub1 : public Singleton <SingletonStub1>{
+  friend class Singleton<SingletonStub1>;
+private:
+  SingletonStub1(){
+    count1++;
+  }
+  // explicit copy constructor to catch if this is ever called
+  SingletonStub1(const SingletonStub1&){
+    CPPUNIT_FAIL    ( "Copy constructor of Singleton called" );
+  }
+  virtual ~SingletonStub1(){
+    count2++;
+  }
+public:
+  static int count1;
+  static int count2;
+};
+
+int SingletonStub1::count1 = 0;
+int SingletonStub1::count2 = 0;
+
+CONSTRUCT_SINGLETON(SingletonStub1);
+
+class SingletonStub2 : public Singleton<SingletonStub2>{
+  friend class Singleton<SingletonStub2>;
+private:
+  SingletonStub2(){
+    count1++;
+  }
+  // explicit copy constructor to catch if this is ever called
+  SingletonStub2(const SingletonStub2&){
+    CPPUNIT_FAIL    ( "Copy constructor of Singleton called" );
+  }
+  virtual ~SingletonStub2(){
+    count2++;
+  }
+public:
+  static int count1;
+  static int count2;
+};
+
+int SingletonStub2::count1 = 0;
+int SingletonStub2::count2 = 0;
+
+CONSTRUCT_SINGLETON(SingletonStub2);
+
+void SingletonTest::setUp(){}
+void SingletonTest::tearDown(){}
+
+void SingletonTest::ConstructionTest(){
+  void *ptr_1_1 = reinterpret_cast<void*>(SingletonStub1::getPointer());
+  void *ptr_1_2 = reinterpret_cast<void*>(SingletonStub1::getPointer());
+  void *ptr_1_3 = reinterpret_cast<void*>(&(SingletonStub1::getInstance()));
+
+  // test if we always get the same instance of our singleton
+  CPPUNIT_ASSERT_EQUAL(ptr_1_1,ptr_1_2);
+  CPPUNIT_ASSERT_EQUAL(ptr_1_1,ptr_1_3);
+
+  void *ptr_2_1 = reinterpret_cast<void*>(SingletonStub2::getPointer());
+  void *ptr_2_2 = reinterpret_cast<void*>(SingletonStub2::getPointer());
+  void *ptr_2_3 = reinterpret_cast<void*>(&(SingletonStub2::getInstance()));
+
+  // same as above but for a different singleton
+  CPPUNIT_ASSERT_EQUAL(ptr_2_1,ptr_2_2);
+  CPPUNIT_ASSERT_EQUAL(ptr_2_1,ptr_2_3);
+
+  // see if the two singletons actually differ
+  CPPUNIT_ASSERT(ptr_1_1!=ptr_2_1);
+
+  // see if each constructor was called exactly once
+  CPPUNIT_ASSERT_EQUAL(1,SingletonStub1::count1);
+  CPPUNIT_ASSERT_EQUAL(1,SingletonStub2::count1);
+  // no calls to the destructor should have occured so far
+  CPPUNIT_ASSERT_EQUAL(0,SingletonStub1::count2);
+  CPPUNIT_ASSERT_EQUAL(0,SingletonStub2::count2);
+
+  SingletonStub1::purgeInstance();
+
+  void *ptr_3_1 = reinterpret_cast<void*>(SingletonStub1::getPointer());
+  void *ptr_3_2 = reinterpret_cast<void*>(SingletonStub1::getPointer());
+
+  // now the constructor should have been called twice
+  CPPUNIT_ASSERT_EQUAL(2,SingletonStub1::count1);
+  // the destructor should have been called once
+  CPPUNIT_ASSERT_EQUAL(1,SingletonStub1::count2);
+  // see if the singleton Assumption holds
+  CPPUNIT_ASSERT_EQUAL(ptr_3_1,ptr_3_2);
+  // Some esoteric thing might cause our pointer to lay at the position of Singleton2 now
+  // See that those two objects still differ
+  CPPUNIT_ASSERT(ptr_3_1!=ptr_2_1);
+  // don't test for pointer difference between first and second singleton here,
+  // because they might be constructed in the same place
+
+
+  SingletonStub2::resetInstance();
+  // now the constructor should have been called twice
+  CPPUNIT_ASSERT_EQUAL(2,SingletonStub2::count1);
+  // the destructor should have been called once
+  CPPUNIT_ASSERT_EQUAL(1,SingletonStub2::count2);
+
+  void *ptr_4_1 = reinterpret_cast<void*>(SingletonStub2::getPointer());
+  void *ptr_4_2 = reinterpret_cast<void*>(SingletonStub2::getPointer());
+
+  // Still only two calls to the constructor, one call to destructor
+  CPPUNIT_ASSERT_EQUAL(2,SingletonStub2::count1);
+  CPPUNIT_ASSERT_EQUAL(1,SingletonStub2::count2);
+
+  // test if Singleton assumption can be broken by reset
+  CPPUNIT_ASSERT_EQUAL(ptr_4_1,ptr_4_2);
+
+  // and again test if we actually have a object seperate from anything else
+  CPPUNIT_ASSERT(ptr_4_1!=ptr_3_1);
+
+
+  // we don't purge our singletons here. Purging should be done automatically by the Singleton
+  // mechanism. Check with Valgrind to see if memory-leak occurs
+  std::cout << "Not purging Singleton!\n Check with Valgrind to see if automatic purgins is working!" << std::endl;
+
+}
Index: src/unittests/SingletonTest.hpp
===================================================================
--- src/unittests/SingletonTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/SingletonTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,26 @@
+/*
+ * SingletonTest.hpp
+ *
+ *  Created on: Mar 11, 2010
+ *      Author: crueger
+ */
+
+#ifndef SINGLETONTEST_HPP_
+#define SINGLETONTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+class SingletonTest : public CppUnit::TestFixture
+{
+  CPPUNIT_TEST_SUITE( SingletonTest );
+  CPPUNIT_TEST ( ConstructionTest );
+  CPPUNIT_TEST_SUITE_END();
+
+public:
+  void setUp();
+  void tearDown();
+
+  void ConstructionTest();
+};
+
+#endif /* SINGLETONTEST_HPP_ */
Index: src/unittests/analysisbondsunittest.cpp
===================================================================
--- src/unittests/analysisbondsunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/analysisbondsunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -16,4 +16,5 @@
 #include <cstring>
 
+#include "World.hpp"
 #include "analysis_bonds.hpp"
 #include "analysisbondsunittest.hpp"
@@ -52,5 +53,5 @@
   strcpy(hydrogen->symbol, "H");
   carbon = new element;
-  carbon->Z = 1;
+  carbon->Z = 2;
   carbon->Valence = 4;
   carbon->NoValenceOrbitals = 4;
@@ -60,29 +61,29 @@
 
   // construct periodentafel
-  tafel = new periodentafel;
+  tafel = World::getInstance().getPeriode();
   tafel->AddElement(hydrogen);
   tafel->AddElement(carbon);
 
   // construct molecule (tetraeder of hydrogens)
-  TestMolecule = new molecule(tafel);
-  Walker = new atom();
+  TestMolecule = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(1.5, 0., 1.5 );
+  *Walker->node = Vector(1.5, 0., 1.5 );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(0., 1.5, 1.5 );
+  *Walker->node = Vector(0., 1.5, 1.5 );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(1.5, 1.5, 0. );
+  *Walker->node = Vector(1.5, 1.5, 0. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = hydrogen;
-  Walker->node->Init(0., 0., 0. );
+  *Walker->node = Vector(0., 0., 0. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
+  Walker = World::getInstance().createAtom();
   Walker->type = carbon;
-  Walker->node->Init(0.5, 0.5, 0.5 );
+  *Walker->node = Vector(0.5, 0.5, 0.5 );
   TestMolecule->AddAtom(Walker);
 
@@ -116,8 +117,7 @@
 
   // remove molecule
-  delete(TestMolecule);
+  World::getInstance().destroyMolecule(TestMolecule);
   // note that all the atoms are cleaned by TestMolecule
-  delete(tafel);
-  // note that element is cleaned by periodentafel
+  World::purgeInstance();
 };
 
Index: src/unittests/atomsCalculationTest.cpp
===================================================================
--- src/unittests/atomsCalculationTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/atomsCalculationTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,93 @@
+/*
+ * atomsCalculationTest.cpp
+ *
+ *  Created on: Feb 19, 2010
+ *      Author: crueger
+ */
+
+#include "atomsCalculationTest.hpp"
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+#include <iostream>
+#include <boost/bind.hpp>
+
+#include "Descriptors/AtomDescriptor.hpp"
+#include "Descriptors/AtomIdDescriptor.hpp"
+#include "Actions/AtomsCalculation.hpp"
+#include "Actions/AtomsCalculation_impl.hpp"
+#include "Actions/ActionRegistry.hpp"
+
+#include "World.hpp"
+#include "World_calculations.hpp"
+#include "atom.hpp"
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( atomsCalculationTest );
+
+// set up and tear down
+void atomsCalculationTest::setUp(){
+  World::getInstance();
+  for(int i=0;i<ATOM_COUNT;++i){
+    atoms[i]= World::getInstance().createAtom();
+    atomIds[i]= atoms[i]->getId();
+  }
+}
+void atomsCalculationTest::tearDown(){
+  World::purgeInstance();
+  ActionRegistry::purgeInstance();
+}
+
+// some helper functions
+static bool hasAllIds(std::vector<atomId_t> atoms,atomId_t ids[ATOM_COUNT], std::set<atomId_t> excluded = std::set<atomId_t>()){
+  for(int i=0;i<ATOM_COUNT;++i){
+    atomId_t id = ids[i];
+    if(!excluded.count(id)){
+      std::vector<atomId_t>::iterator iter;
+      bool res=false;
+      for(iter=atoms.begin();iter!=atoms.end();++iter){
+        res |= (*iter) == id;
+      }
+      if(!res) {
+        cout << "Atom " << id << " missing in returned list" << endl;
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+static bool hasNoDuplicates(std::vector<atomId_t> ids){
+  std::set<atomId_t> found;
+  std::vector<atomId_t>::iterator iter;
+  for(iter=ids.begin();iter!=ids.end();++iter){
+    int id = (*iter);
+    if(found.count(id))
+      return false;
+    found.insert(id);
+  }
+  return true;
+}
+
+void atomsCalculationTest::testCalculateSimple(){
+  AtomsCalculation<atomId_t> *calc = World::getInstance().calcOnAtoms<atomId_t>(boost::bind(&atom::getId,_1),"FOO",AllAtoms());
+  std::vector<atomId_t> allIds = (*calc)();
+  CPPUNIT_ASSERT(hasAllIds(allIds,atomIds));
+  CPPUNIT_ASSERT(hasNoDuplicates(allIds));
+}
+
+void atomsCalculationTest::testCalculateExcluded(){
+  atomId_t excluded = atomIds[ATOM_COUNT/2];
+  AtomsCalculation<atomId_t> *calc = World::getInstance().calcOnAtoms<atomId_t>(boost::bind(&atom::getId,_1),"FOO",AllAtoms() && !AtomById(excluded));
+  std::vector<atomId_t> allIds = (*calc)();
+  std::set<atomId_t> excluded_set;
+  excluded_set.insert(excluded);
+  CPPUNIT_ASSERT(hasAllIds(allIds,atomIds,excluded_set));
+  CPPUNIT_ASSERT(hasNoDuplicates(allIds));
+  CPPUNIT_ASSERT_EQUAL((size_t)(ATOM_COUNT-1),allIds.size());
+}
Index: src/unittests/atomsCalculationTest.hpp
===================================================================
--- src/unittests/atomsCalculationTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/atomsCalculationTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,38 @@
+/*
+ * atomsCalculationTest.hpp
+ *
+ *  Created on: Feb 19, 2010
+ *      Author: crueger
+ */
+
+#ifndef ATOMSCALCULATIONTEST_HPP_
+#define ATOMSCALCULATIONTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#define ATOM_COUNT (10)
+
+#include "types.hpp"
+
+class atom;
+
+class atomsCalculationTest :  public CppUnit::TestFixture
+{
+  CPPUNIT_TEST_SUITE( atomsCalculationTest );
+  CPPUNIT_TEST ( testCalculateSimple );
+  CPPUNIT_TEST ( testCalculateExcluded );
+  CPPUNIT_TEST_SUITE_END();
+
+public:
+  void setUp();
+  void tearDown();
+
+  void testCalculateSimple();
+  void testCalculateExcluded();
+
+private:
+  atom *atoms [ATOM_COUNT];
+  atomId_t atomIds [ATOM_COUNT];
+};
+
+#endif /* ATOMSCALCULATIONTEST_HPP_ */
Index: src/unittests/bondgraphunittest.cpp
===================================================================
--- src/unittests/bondgraphunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/bondgraphunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -16,11 +16,14 @@
 #include <cstring>
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
 #include "bondgraph.hpp"
 #include "element.hpp"
+#include "log.hpp"
 #include "molecule.hpp"
 #include "periodentafel.hpp"
 #include "bondgraphunittest.hpp"
+#include "World.hpp"
 
 #ifdef HAVE_TESTRUNNER
@@ -46,8 +49,12 @@
   hydrogen = new element;
   hydrogen->Z = 1;
+  hydrogen->CovalentRadius = 0.23;
+  hydrogen->VanDerWaalsRadius = 1.09;
   strcpy(hydrogen->name, "hydrogen");
   strcpy(hydrogen->symbol, "H");
   carbon = new element;
-  carbon->Z = 1;
+  carbon->Z = 2;
+  carbon->CovalentRadius = 0.68;
+  carbon->VanDerWaalsRadius = 1.7;
   strcpy(carbon->name, "carbon");
   strcpy(carbon->symbol, "C");
@@ -55,25 +62,28 @@
 
   // construct periodentafel
-  tafel = new periodentafel;
+  tafel = World::getInstance().getPeriode();
   tafel->AddElement(hydrogen);
   tafel->AddElement(carbon);
 
   // construct molecule (tetraeder of hydrogens)
-  TestMolecule = new molecule(tafel);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(1., 0., 1. );
+  TestMolecule = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
+  Walker->type = carbon;
+  *Walker->node = Vector(1., 0., 1. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(0., 1., 1. );
+
+  Walker = World::getInstance().createAtom();
+  Walker->type = carbon;
+  *Walker->node = Vector(0., 1., 1. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(1., 1., 0. );
+
+  Walker = World::getInstance().createAtom();
+  Walker->type = carbon;
+  *Walker->node = Vector(1., 1., 0. );
   TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(0., 0., 0. );
+
+  Walker = World::getInstance().createAtom();
+  Walker->type = carbon;
+  *Walker->node = Vector(0., 0., 0. );
   TestMolecule->AddAtom(Walker);
 
@@ -82,4 +92,5 @@
 
   // create a small file with table
+  dummyname = new string("dummy.dat");
   filename = new string("test.dat");
   ofstream test(filename->c_str());
@@ -97,11 +108,14 @@
   remove(filename->c_str());
   delete(filename);
+  delete(dummyname);
   delete(BG);
 
   // remove molecule
-  delete(TestMolecule);
-  // note that all the atoms are cleaned by TestMolecule
-  delete(tafel);
-  // note that element is cleaned by periodentafel
+  World::getInstance().destroyMolecule(TestMolecule);
+  // note that all the atoms, molecules, the tafel and the elements
+  // are all cleaned when the world is destroyed
+  World::purgeInstance();
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
 };
 
@@ -118,5 +132,5 @@
 /** UnitTest for BondGraphTest::ConstructBondGraph().
  */
-void BondGraphTest::ConstructGraphTest()
+void BondGraphTest::ConstructGraphFromTableTest()
 {
   atom *Walker = TestMolecule->start->next;
@@ -127,2 +141,15 @@
   CPPUNIT_ASSERT_EQUAL( true , Walker->IsBondedTo(Runner) );
 };
+
+/** UnitTest for BondGraphTest::ConstructBondGraph().
+ */
+void BondGraphTest::ConstructGraphFromCovalentRadiiTest()
+{
+  atom *Walker = TestMolecule->start->next;
+  atom *Runner = TestMolecule->end->previous;
+  CPPUNIT_ASSERT( TestMolecule->end != Walker );
+  CPPUNIT_ASSERT_EQUAL( false , BG->LoadBondLengthTable(*dummyname) );
+  CPPUNIT_ASSERT_EQUAL( true , BG->ConstructBondGraph(TestMolecule) );
+  CPPUNIT_ASSERT_EQUAL( true , Walker->IsBondedTo(Runner) );
+};
+
Index: src/unittests/bondgraphunittest.hpp
===================================================================
--- src/unittests/bondgraphunittest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/bondgraphunittest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -23,5 +23,6 @@
     CPPUNIT_TEST_SUITE( BondGraphTest) ;
     CPPUNIT_TEST ( LoadTableTest );
-    CPPUNIT_TEST ( ConstructGraphTest );
+    CPPUNIT_TEST ( ConstructGraphFromTableTest );
+    CPPUNIT_TEST ( ConstructGraphFromCovalentRadiiTest );
     CPPUNIT_TEST_SUITE_END();
 
@@ -30,5 +31,6 @@
       void tearDown();
       void LoadTableTest();
-      void ConstructGraphTest();
+      void ConstructGraphFromTableTest();
+      void ConstructGraphFromCovalentRadiiTest();
 
 private:
@@ -41,4 +43,5 @@
       BondGraph *BG;
       string *filename;
+      string *dummyname;
 };
 
Index: src/unittests/gslvectorunittest.cpp
===================================================================
--- src/unittests/gslvectorunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/gslvectorunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -117,2 +117,48 @@
     CPPUNIT_ASSERT_EQUAL( (double)(3-j), v->Get(j) );
 };
+
+/** UnitTest for operators.
+ */
+void GSLVectorTest::OperatorIsTest()
+{
+  GSLVector zero(3);
+  GSLVector unit(3);
+  zero.SetZero();
+  unit.SetZero();
+  unit.Set(1,1.);
+  // summation and scaling
+  CPPUNIT_ASSERT_EQUAL( true, unit.IsOne() );
+  CPPUNIT_ASSERT_EQUAL( false, zero.IsOne() );
+  CPPUNIT_ASSERT_EQUAL( false, unit.IsZero() );
+  CPPUNIT_ASSERT_EQUAL( true, zero.IsZero() );
+};
+
+/** UnitTest for operators.
+ */
+void GSLVectorTest::OperatorAlgebraTest()
+{
+  GSLVector zero(3);
+  GSLVector unit(3);
+  zero.SetZero();
+  unit.SetZero();
+  unit.Set(1,1.);
+  // summation and scaling
+  CPPUNIT_ASSERT_EQUAL( true, (zero+unit).IsOne() );
+  CPPUNIT_ASSERT_EQUAL( true, (zero+unit).IsOne() );
+  CPPUNIT_ASSERT_EQUAL( true, (zero-unit).IsOne() );
+  CPPUNIT_ASSERT_EQUAL( false, (zero-unit).IsZero() );
+  CPPUNIT_ASSERT_EQUAL( true, (zero+zero).IsZero() );
+  CPPUNIT_ASSERT_EQUAL( false, (unit*0.98).IsOne() );
+  CPPUNIT_ASSERT_EQUAL( false, (0.98*unit).IsOne() );
+  CPPUNIT_ASSERT_EQUAL( true, (unit*1.).IsOne() );
+  CPPUNIT_ASSERT_EQUAL( true, (1.*unit).IsOne() );
+
+  CPPUNIT_ASSERT_EQUAL( unit, (zero+unit) );
+  CPPUNIT_ASSERT_EQUAL( zero, (zero+zero) );
+  CPPUNIT_ASSERT_EQUAL( unit, (unit+zero) );
+
+  unit += zero;
+  CPPUNIT_ASSERT_EQUAL( true, unit.IsOne() );
+  unit *= 1.;
+  CPPUNIT_ASSERT_EQUAL( true, unit.IsOne() );
+};
Index: src/unittests/gslvectorunittest.hpp
===================================================================
--- src/unittests/gslvectorunittest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/gslvectorunittest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -22,4 +22,6 @@
     CPPUNIT_TEST (CopyTest );
     CPPUNIT_TEST (ExchangeTest );
+    CPPUNIT_TEST (OperatorAlgebraTest );
+    CPPUNIT_TEST (OperatorIsTest );
     CPPUNIT_TEST_SUITE_END();
 
@@ -32,4 +34,6 @@
     void CopyTest();
     void ExchangeTest();
+    void OperatorIsTest();
+    void OperatorAlgebraTest();
 
 private:
Index: src/unittests/infounittest.cpp
===================================================================
--- src/unittests/infounittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/infounittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -17,4 +17,5 @@
 #include "info.hpp"
 #include "infounittest.hpp"
+#include "log.hpp"
 
 #ifdef HAVE_TESTRUNNER
@@ -35,4 +36,5 @@
 void InfoTest::tearDown()
 {
+  logger::purgeInstance();
 };
 
Index: src/unittests/listofbondsunittest.cpp
===================================================================
--- src/unittests/listofbondsunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/listofbondsunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -16,4 +16,5 @@
 #include "listofbondsunittest.hpp"
 
+#include "World.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
@@ -21,4 +22,5 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
+#include "World.hpp"
 
 #ifdef HAVE_TESTRUNNER
@@ -49,24 +51,24 @@
 
   // construct periodentafel
-  tafel = new periodentafel;
+  tafel = World::getInstance().getPeriode();
   tafel->AddElement(hydrogen);
 
   // construct molecule (tetraeder of hydrogens)
-  TestMolecule = new molecule(tafel);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(1., 0., 1. );
-  TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(0., 1., 1. );
-  TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(1., 1., 0. );
-  TestMolecule->AddAtom(Walker);
-  Walker = new atom();
-  Walker->type = hydrogen;
-  Walker->node->Init(0., 0., 0. );
+  TestMolecule = World::getInstance().createMolecule();
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(1., 0., 1. );
+  TestMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(0., 1., 1. );
+  TestMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(1., 1., 0. );
+  TestMolecule->AddAtom(Walker);
+  Walker = World::getInstance().createAtom();
+  Walker->type = hydrogen;
+  *Walker->node = Vector(0., 0., 0. );
   TestMolecule->AddAtom(Walker);
 
@@ -80,8 +82,10 @@
 {
   // remove
-  delete(TestMolecule);
-  // note that all the atoms are cleaned by TestMolecule
-  delete(tafel);
-  // note that element is cleaned by periodentafel
+  World::getInstance().destroyMolecule(TestMolecule);
+  // note that all the atoms, molecules, the tafel and the elements
+  // are all cleaned when the world is destroyed
+  World::purgeInstance();
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
 };
 
@@ -246,5 +250,5 @@
 
   // remove atom2
-  delete(atom2);
+  World::getInstance().destroyAtom(atom2);
 
   // check bond if removed from other atom
Index: src/unittests/logunittest.cpp
===================================================================
--- src/unittests/logunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/logunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -31,4 +31,6 @@
 void LogTest::tearDown()
 {
+  logger::purgeInstance();
+  errorLogger::purgeInstance();
 };
 
@@ -38,16 +40,16 @@
 void LogTest::logTest()
 {
-  logger::getInstance()->setVerbosity(2);
-  Log() << Verbose(0) << "Verbosity level is set to 2." << endl;
-  Log() << Verbose(0) << "Test level 0" << endl;
-  Log() << Verbose(1) << "Test level 1" << endl;
-  Log() << Verbose(2) << "Test level 2" << endl;
-  Log() << Verbose(3) << "Test level 3" << endl;
-  Log() << Verbose(4) << "Test level 4" << endl;
+  logger::getInstance().setVerbosity(2);
+  DoLog(0) && (Log() << Verbose(0) << "Verbosity level is set to 2." << endl);
+  DoLog(0) && (Log() << Verbose(0) << "Test level 0" << endl);
+  DoLog(1) && (Log() << Verbose(1) << "Test level 1" << endl);
+  DoLog(2) && (Log() << Verbose(2) << "Test level 2" << endl);
+  DoLog(3) && (Log() << Verbose(3) << "Test level 3" << endl);
+  DoLog(4) && (Log() << Verbose(4) << "Test level 4" << endl);
 
-  Log() << Verbose(0) << "Output a log message." << endl;
-  eLog() << Verbose(0) << "Output an error message." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Output a log message." << endl);
+  DoeLog(0) && (eLog()<< Verbose(0) << "Output an error message." << endl);
   setVerbosity(3);
-  Log() << Verbose(4) << "This should not be printed." << endl;
-  eLog() << Verbose(4) << "This should not be printed." << endl;
+  DoLog(4) && (Log() << Verbose(4) << "This should not be printed." << endl);
+  DoeLog(4) && (eLog()<< Verbose(4) << "This should not be printed." << endl);
 };
Index: src/unittests/manipulateAtomsTest.cpp
===================================================================
--- src/unittests/manipulateAtomsTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/manipulateAtomsTest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,132 @@
+/*
+ * manipulateAtomsTest.cpp
+ *
+ *  Created on: Feb 18, 2010
+ *      Author: crueger
+ */
+
+#include "manipulateAtomsTest.hpp"
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+#include <iostream>
+#include <boost/bind.hpp>
+
+#include "Descriptors/AtomDescriptor.hpp"
+#include "Descriptors/AtomIdDescriptor.hpp"
+#include "Actions/ManipulateAtomsProcess.hpp"
+#include "Actions/ActionRegistry.hpp"
+#include "Actions/ActionHistory.hpp"
+
+#include "World.hpp"
+#include "atom.hpp"
+
+#ifdef HAVE_TESTRUNNER
+#include "UnitTestMain.hpp"
+#endif /*HAVE_TESTRUNNER*/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( manipulateAtomsTest );
+
+// some stubs
+class AtomStub : public atom {
+public:
+  AtomStub(int _id) :
+  atom(),
+  manipulated(false),
+  id(_id)
+  {}
+
+  virtual atomId_t getId(){
+    return id;
+  }
+
+  virtual void doSomething(){
+    manipulated = true;
+  }
+
+  bool manipulated;
+private:
+  atomId_t id;
+};
+
+class countObserver : public Observer{
+public:
+  countObserver() :
+    count(0)
+    {}
+  virtual ~countObserver(){}
+
+  void update(Observable *){
+    count++;
+  }
+
+  void subjectKilled(Observable *)
+  {}
+
+  int count;
+};
+
+// set up and tear down
+void manipulateAtomsTest::setUp(){
+  ActionHistory::init();
+  World::getInstance();
+  for(int i=0;i<ATOM_COUNT;++i){
+    atoms[i]= new AtomStub(i);
+    World::getInstance().registerAtom(atoms[i]);
+  }
+}
+void manipulateAtomsTest::tearDown(){
+  World::purgeInstance();
+  ActionRegistry::purgeInstance();
+  ActionHistory::purgeInstance();
+}
+
+static void operation(atom* _atom){
+  AtomStub *atom = dynamic_cast<AtomStub*>(_atom);
+  assert(atom);
+  atom->doSomething();
+}
+
+
+void manipulateAtomsTest::testManipulateSimple(){
+  ManipulateAtomsProcess *proc = World::getInstance().manipulateAtoms(boost::bind(operation,_1),"FOO",AllAtoms());
+  proc->call();
+  std::vector<atom*> allAtoms = World::getInstance().getAllAtoms(AllAtoms());
+  std::vector<atom*>::iterator iter;
+  for(iter=allAtoms.begin();iter!=allAtoms.end();++iter){
+    AtomStub *atom;
+    atom = dynamic_cast<AtomStub*>(*iter);
+    assert(atom);
+    CPPUNIT_ASSERT(atom->manipulated);
+  }
+}
+
+void manipulateAtomsTest::testManipulateExcluded(){
+
+  ManipulateAtomsProcess *proc = World::getInstance().manipulateAtoms(boost::bind(operation,_1),"FOO",AllAtoms() && !AtomById(ATOM_COUNT/2));
+  proc->call();
+  std::vector<atom*> allAtoms = World::getInstance().getAllAtoms(AllAtoms());
+  std::vector<atom*>::iterator iter;
+  for(iter=allAtoms.begin();iter!=allAtoms.end();++iter){
+    AtomStub *atom;
+    atom = dynamic_cast<AtomStub*>(*iter);
+    assert(atom);
+    if(atom->getId()!=(int)ATOM_COUNT/2)
+      CPPUNIT_ASSERT(atom->manipulated);
+    else
+      CPPUNIT_ASSERT(!atom->manipulated);
+  }
+}
+
+void manipulateAtomsTest::testObserver(){
+  countObserver *obs = new countObserver();
+  World::getInstance().signOn(obs);
+  ManipulateAtomsProcess *proc = World::getInstance().manipulateAtoms(boost::bind(operation,_1),"FOO",AllAtoms());
+  proc->call();
+
+  CPPUNIT_ASSERT_EQUAL(1,obs->count);
+  World::getInstance().signOff(obs);
+  delete obs;
+}
Index: src/unittests/manipulateAtomsTest.hpp
===================================================================
--- src/unittests/manipulateAtomsTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/unittests/manipulateAtomsTest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,37 @@
+/*
+ * manipulateAtomsTest.hpp
+ *
+ *  Created on: Feb 18, 2010
+ *      Author: crueger
+ */
+
+#ifndef MANIPULATEATOMSTEST_HPP_
+#define MANIPULATEATOMSTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#define ATOM_COUNT (10)
+
+class atom;
+
+class manipulateAtomsTest : public CppUnit::TestFixture
+{
+  CPPUNIT_TEST_SUITE( manipulateAtomsTest );
+  CPPUNIT_TEST ( testManipulateSimple );
+  CPPUNIT_TEST ( testManipulateExcluded );
+  CPPUNIT_TEST ( testObserver );
+  CPPUNIT_TEST_SUITE_END();
+
+public:
+  void setUp();
+  void tearDown();
+
+  void testManipulateSimple();
+  void testManipulateExcluded();
+  void testObserver();
+
+private:
+  atom *atoms [ATOM_COUNT];
+};
+
+#endif /* MANIPULATEATOMSTEST_HPP_ */
Index: src/unittests/memoryallocatorunittest.cpp
===================================================================
--- src/unittests/memoryallocatorunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/memoryallocatorunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -13,4 +13,5 @@
 #include "memoryallocatorunittest.hpp"
 #include "helpers.hpp"
+#include "log.hpp"
 #include "defs.hpp"
 
@@ -33,4 +34,5 @@
 {
   MemoryUsageObserver::getInstance()->purgeInstance();
+  logger::purgeInstance();
 };
 
@@ -50,5 +52,5 @@
   char* buffer3 = NULL;
   buffer3 = Malloc<char>(4, "");
-  Log() << Verbose(0) << buffer3 << endl;
+  DoLog(0) && (Log() << Verbose(0) << buffer3 << endl);
   Free(&buffer3);
 
Index: src/unittests/memoryusageobserverunittest.cpp
===================================================================
--- src/unittests/memoryusageobserverunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/memoryusageobserverunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -31,4 +31,6 @@
 {
   MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
+  errorLogger::purgeInstance();
 };
 
@@ -74,4 +76,5 @@
   MemoryUsageObserver::getInstance()->removeMemory(i);
   CPPUNIT_ASSERT_EQUAL((size_t) 0, MemoryUsageObserver::getInstance()->getUsedMemorySize());
+  Free(i);
 };
 
@@ -84,4 +87,5 @@
   MemoryUsageObserver::getInstance()->removeMemory(i);
   CPPUNIT_ASSERT_EQUAL((size_t) 0, MemoryUsageObserver::getInstance()->getUsedMemorySize());
+  Free(i);
 };
 
@@ -96,4 +100,6 @@
   MemoryUsageObserver::getInstance()->addMemory(j, sizeof(int));
   CPPUNIT_ASSERT_EQUAL(2 * sizeof(int), MemoryUsageObserver::getInstance()->getUsedMemorySize());
+  Free(i);
+  Free(j);
 };
 
@@ -107,4 +113,5 @@
   MemoryUsageObserver::getInstance()->addMemory(i, sizeof(int));
   CPPUNIT_ASSERT_EQUAL(sizeof(int), MemoryUsageObserver::getInstance()->getUsedMemorySize());
+  Free(i);
 };
 
@@ -118,4 +125,5 @@
   MemoryUsageObserver::getInstance()->addMemory(i, sizeof(int));
   CPPUNIT_ASSERT_EQUAL(2 * sizeof(int), MemoryUsageObserver::getInstance()->getMaximumUsedMemory());
+  Free(i);
 };
 
@@ -129,4 +137,5 @@
   MemoryUsageObserver::getInstance()->removeMemory(i);
   CPPUNIT_ASSERT_EQUAL(sizeof(int), MemoryUsageObserver::getInstance()->getMaximumUsedMemory());
+  Free(i);
 };
 
@@ -139,3 +148,4 @@
   MemoryUsageObserver::getInstance()->addMemory(i, sizeof(int));
   CPPUNIT_ASSERT_EQUAL(i, (int*) MemoryUsageObserver::getInstance()->getPointersToAllocatedMemory().begin()->first);
+  Free(i);
 };
Index: src/unittests/stackclassunittest.cpp
===================================================================
--- src/unittests/stackclassunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/stackclassunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -37,4 +37,6 @@
   Stack->ClearStack();
   delete(Stack);
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
 };
 
Index: src/unittests/tesselation_boundarytriangleunittest.cpp
===================================================================
--- src/unittests/tesselation_boundarytriangleunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/tesselation_boundarytriangleunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -35,23 +35,22 @@
 
   // create nodes
-  TesselPoint *Walker = NULL;
-  Walker = new TesselPoint;
-  Walker->node = new Vector(0., 0., 0.);
-  Walker->Name = Malloc<char>(3, "TesselationBoundaryTriangleTest::setUp - *Name");
-  strcpy(Walker->Name, "1");
-  Walker->nr = 1;
-  points[0] = new BoundaryPointSet(Walker);
-  Walker = new TesselPoint;
-  Walker->node = new Vector(0., 1., 0.);
-  Walker->Name = Malloc<char>(3, "TesselationBoundaryTriangleTest::setUp - *Name");
-  strcpy(Walker->Name, "2");
-  Walker->nr = 2;
-  points[1] = new BoundaryPointSet(Walker);
-  Walker = new TesselPoint;
-  Walker->node = new Vector(1., 0., 0.);
-  Walker->Name = Malloc<char>(3, "TesselationBoundaryTriangleTest::setUp - *Name");
-  strcpy(Walker->Name, "3");
-  Walker->nr = 3;
-  points[2] = new BoundaryPointSet(Walker);
+  tesselpoints[0] = new TesselPoint;
+  tesselpoints[0]->node = new Vector(0., 0., 0.);
+  tesselpoints[0]->Name = Malloc<char>(3, "TesselationBoundaryTriangleTest::setUp - *Name");
+  strcpy(tesselpoints[0]->Name, "1");
+  tesselpoints[0]->nr = 1;
+  points[0] = new BoundaryPointSet(tesselpoints[0]);
+  tesselpoints[1] = new TesselPoint;
+  tesselpoints[1]->node = new Vector(0., 1., 0.);
+  tesselpoints[1]->Name = Malloc<char>(3, "TesselationBoundaryTriangleTest::setUp - *Name");
+  strcpy(tesselpoints[1]->Name, "2");
+  tesselpoints[1]->nr = 2;
+  points[1] = new BoundaryPointSet(tesselpoints[1]);
+  tesselpoints[2] = new TesselPoint;
+  tesselpoints[2] ->node = new Vector(1., 0., 0.);
+  tesselpoints[2] ->Name = Malloc<char>(3, "TesselationBoundaryTriangleTest::setUp - *Name");
+  strcpy(tesselpoints[2] ->Name, "3");
+  tesselpoints[2] ->nr = 3;
+  points[2] = new BoundaryPointSet(tesselpoints[2] );
 
   // create line
@@ -69,4 +68,9 @@
 {
   delete(triangle);
+  for (int i=0;i<3;++i) {
+    // TesselPoint does not delete its vector as it only got a reference
+    delete tesselpoints[i]->node;
+    delete tesselpoints[i];
+  }
   MemoryUsageObserver::purgeInstance();
   logger::purgeInstance();
@@ -82,49 +86,49 @@
 
   // simple test on y line
-  Point.Init(-1.,0.5,0.);
-  CPPUNIT_ASSERT_EQUAL( 1., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.,0.5,0.);
-  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
-  Point.Init(-4.,0.5,0.);
+  Point = Vector(-1.,0.5,0.);
+  CPPUNIT_ASSERT_EQUAL( 1., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point = Vector(0.,0.5,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+  Point = Vector(-4.,0.5,0.);
   CPPUNIT_ASSERT_EQUAL( 16., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.,0.5,0.);
+  Point = Vector(0.,0.5,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on x line
-  Point.Init(0.5,-1.,0.);
-  CPPUNIT_ASSERT_EQUAL( 1., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.5,0.,0.);
-  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
-  Point.Init(0.5,-6.,0.);
+  Point = Vector(0.5,-1.,0.);
+  CPPUNIT_ASSERT_EQUAL( 1., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point = Vector(0.5,0.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+  Point = Vector(0.5,-6.,0.);
   CPPUNIT_ASSERT_EQUAL( 36., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.5,0.,0.);
+  Point = Vector(0.5,0.,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on slanted line
-  Point.Init(1.,1.,0.);
+  Point = Vector(1.,1.,0.);
   CPPUNIT_ASSERT_EQUAL( 0.5, triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.5,0.5,0.);
-  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
-  Point.Init(5.,5.,0.);
+  Point = Vector(0.5,0.5,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+  Point = Vector(5.,5.,0.);
   CPPUNIT_ASSERT_EQUAL( 40.5, triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.5,0.5,0.);
+  Point = Vector(0.5,0.5,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on first node
-  Point.Init(-1.,-1.,0.);
+  Point = Vector(-1.,-1.,0.);
   CPPUNIT_ASSERT_EQUAL( 2., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.,0.,0.);
+  Point = Vector(0.,0.,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on second node
-  Point.Init(0.,2.,0.);
-  CPPUNIT_ASSERT_EQUAL( 1., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.,1.,0.);
+  Point = Vector(0.,2.,0.);
+  CPPUNIT_ASSERT_EQUAL( 1., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point = Vector(0.,1.,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on third node
-  Point.Init(2.,0.,0.);
-  CPPUNIT_ASSERT_EQUAL( 1., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(1.,0.,0.);
+  Point = Vector(2.,0.,0.);
+  CPPUNIT_ASSERT_EQUAL( 1., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point = Vector(1.,0.,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 };
@@ -138,59 +142,59 @@
 
   // straight down/up
-  Point.Init(1./3.,1./3.,+5.);
+  Point = Vector(1./3.,1./3.,+5.);
   CPPUNIT_ASSERT_EQUAL( 25. , triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(1./3.,1./3.,0.);
-  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
-  Point.Init(1./3.,1./3.,-5.);
+  Point = Vector(1./3.,1./3.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+  Point = Vector(1./3.,1./3.,-5.);
   CPPUNIT_ASSERT_EQUAL( 25. , triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(1./3.,1./3.,0.);
+  Point = Vector(1./3.,1./3.,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on y line
-  Point.Init(-1.,0.5,+2.);
+  Point = Vector(-1.,0.5,+2.);
   CPPUNIT_ASSERT_EQUAL( 5., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.,0.5,0.);
-  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
-  Point.Init(-1.,0.5,-3.);
+  Point = Vector(0.,0.5,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+  Point = Vector(-1.,0.5,-3.);
   CPPUNIT_ASSERT_EQUAL( 10., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.,0.5,0.);
+  Point = Vector(0.,0.5,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on x line
-  Point.Init(0.5,-1.,+1.);
+  Point = Vector(0.5,-1.,+1.);
   CPPUNIT_ASSERT_EQUAL( 2., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.5,0.,0.);
-  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
-  Point.Init(0.5,-1.,-2.);
+  Point = Vector(0.5,0.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+  Point = Vector(0.5,-1.,-2.);
   CPPUNIT_ASSERT_EQUAL( 5., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.5,0.,0.);
+  Point = Vector(0.5,0.,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on slanted line
-  Point.Init(1.,1.,+3.);
+  Point = Vector(1.,1.,+3.);
   CPPUNIT_ASSERT_EQUAL( 9.5, triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.5,0.5,0.);
-  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
-  Point.Init(1.,1.,-4.);
+  Point = Vector(0.5,0.5,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+  Point = Vector(1.,1.,-4.);
   CPPUNIT_ASSERT_EQUAL( 16.5, triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.5,0.5,0.);
+  Point = Vector(0.5,0.5,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on first node
-  Point.Init(-1.,-1.,5.);
+  Point = Vector(-1.,-1.,5.);
   CPPUNIT_ASSERT_EQUAL( 27., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.,0.,0.);
+  Point = Vector(0.,0.,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on second node
-  Point.Init(0.,2.,5.);
+  Point = Vector(0.,2.,5.);
   CPPUNIT_ASSERT_EQUAL( 26., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(0.,1.,0.);
+  Point = Vector(0.,1.,0.);
   CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
 
   // simple test on third node
-  Point.Init(2.,0.,5.);
+  Point = Vector(2.,0.,5.);
   CPPUNIT_ASSERT_EQUAL( 26., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
-  Point.Init(1.,0.,0.);
-  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
-};
+  Point = Vector(1.,0.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+};
Index: src/unittests/tesselation_boundarytriangleunittest.hpp
===================================================================
--- src/unittests/tesselation_boundarytriangleunittest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/tesselation_boundarytriangleunittest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -35,5 +35,6 @@
       class BoundaryLineSet *lines[3];
       class BoundaryPointSet *points[3];
-      LinkedNodes Corners;
+      class TesselPoint *tesselpoints[3];
+      LinkedCell::LinkedNodes Corners;
 };
 
Index: src/unittests/tesselation_insideoutsideunittest.cpp
===================================================================
--- src/unittests/tesselation_insideoutsideunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/tesselation_insideoutsideunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -98,7 +98,7 @@
   while ((!TesselStruct->OpenLines.empty()) && (OneLoopWithoutSuccessFlag)) {
     // 2a. fill all new OpenLines
-    Log() << Verbose(1) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for candidates:" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for candidates:" << endl);
     for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
-      Log() << Verbose(2) << *(Runner->second) << endl;
+      DoLog(2) && (Log() << Verbose(2) << *(Runner->second) << endl);
 
     for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
@@ -106,5 +106,5 @@
       if (baseline->pointlist.empty()) {
         T = (((baseline->BaseLine->triangles.begin()))->second);
-        Log() << Verbose(1) << "Finding best candidate for open line " << *baseline->BaseLine << " of triangle " << *T << endl;
+        DoLog(1) && (Log() << Verbose(1) << "Finding best candidate for open line " << *baseline->BaseLine << " of triangle " << *T << endl);
         TesselationFailFlag = TesselStruct->FindNextSuitableTriangle(*baseline, *T, SPHERERADIUS, LinkedList); //the line is there, so there is a triangle, but only one.
       }
@@ -113,7 +113,7 @@
     // 2b. search for smallest ShortestAngle among all candidates
     double ShortestAngle = 4.*M_PI;
-    Log() << Verbose(1) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for the best candidates:" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "There are " << TesselStruct->OpenLines.size() << " open lines to scan for the best candidates:" << endl);
     for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++)
-      Log() << Verbose(2) << *(Runner->second) << endl;
+      DoLog(2) && (Log() << Verbose(2) << *(Runner->second) << endl);
 
     for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
@@ -127,5 +127,5 @@
       OneLoopWithoutSuccessFlag = false;
     else {
-      TesselStruct->AddCandidateTriangle(*baseline);
+      TesselStruct->AddCandidatePolygon(*baseline, SPHERERADIUS, LinkedList);
     }
   }
@@ -137,5 +137,5 @@
   delete(LinkedList);
   delete(TesselStruct);
-  for (LinkedNodes::iterator Runner = Corners.begin(); Runner != Corners.end(); Runner++) {
+  for (LinkedCell::LinkedNodes::iterator Runner = Corners.begin(); Runner != Corners.end(); Runner++) {
     delete((*Runner)->node);
     delete(*Runner);
Index: src/unittests/tesselation_insideoutsideunittest.hpp
===================================================================
--- src/unittests/tesselation_insideoutsideunittest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/tesselation_insideoutsideunittest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -31,5 +31,5 @@
 private:
       class Tesselation *TesselStruct;
-      LinkedNodes Corners;
+      LinkedCell::LinkedNodes Corners;
       class LinkedCell *LinkedList;
 };
Index: src/unittests/tesselationunittest.cpp
===================================================================
--- src/unittests/tesselationunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/tesselationunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -95,5 +95,5 @@
       OneLoopWithoutSuccessFlag = false;
     else {
-      TesselStruct->AddCandidateTriangle(*baseline);
+      TesselStruct->AddCandidatePolygon(*baseline, SPHERERADIUS, LinkedList);
     }
   }
@@ -105,5 +105,5 @@
   delete(LinkedList);
   delete(TesselStruct);
-  for (LinkedNodes::iterator Runner = Corners.begin(); Runner != Corners.end(); Runner++) {
+  for (LinkedCell::LinkedNodes::iterator Runner = Corners.begin(); Runner != Corners.end(); Runner++) {
     delete((*Runner)->node);
     delete(*Runner);
Index: src/unittests/tesselationunittest.hpp
===================================================================
--- src/unittests/tesselationunittest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/tesselationunittest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -34,5 +34,5 @@
 private:
       class Tesselation *TesselStruct;
-      LinkedNodes Corners;
+      LinkedCell::LinkedNodes Corners;
       class LinkedCell *LinkedList;
 };
Index: src/unittests/vectorunittest.cpp
===================================================================
--- src/unittests/vectorunittest.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/vectorunittest.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -14,6 +14,11 @@
 
 #include "defs.hpp"
+#include "log.hpp"
+#include "memoryusageobserver.hpp"
 #include "vector.hpp"
+#include "vector_ops.hpp"
 #include "vectorunittest.hpp"
+#include "Plane.hpp"
+#include "Exceptions/LinearDependenceException.hpp"
 
 #ifdef HAVE_TESTRUNNER
@@ -21,4 +26,8 @@
 #endif /*HAVE_TESTRUNNER*/
 
+#include <iostream>
+
+using namespace std;
+
 /********************************************** Test classes **************************************/
 
@@ -29,9 +38,10 @@
 void VectorTest::setUp()
 {
-  zero.Init(0.,0.,0.);
-  unit.Init(1.,0.,0.);
-  otherunit.Init(0.,1.,0.);
-  notunit.Init(0.,1.,1.);
-  two.Init(2.,1.,0.);
+  zero  = Vector(0.,0.,0.);
+  unit = Vector(1.,0.,0.);
+  otherunit = Vector(0.,1.,0.);
+  notunit = Vector(0.,1.,1.);
+  two = Vector(2.,1.,0.);
+  three = Vector(1,2,3);
 };
 
@@ -39,4 +49,7 @@
 void VectorTest::tearDown()
 {
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
+  errorLogger::purgeInstance();
 };
 
@@ -61,40 +74,29 @@
   double factor;
   // copy vector
-  fixture.Init(2.,3.,4.);
+  fixture = Vector(2.,3.,4.);
   CPPUNIT_ASSERT_EQUAL( Vector(2.,3.,4.), fixture );
   // summation and scaling
-  fixture.CopyVector(&zero);
-  fixture.AddVector(&unit);
-  CPPUNIT_ASSERT_EQUAL( true, fixture.IsOne() );
-  fixture.CopyVector(&zero);
-  fixture.SubtractVector(&unit);
+  fixture = zero + unit;
+  CPPUNIT_ASSERT_EQUAL( true, fixture.IsOne() );
+  fixture = zero - unit;
   CPPUNIT_ASSERT_EQUAL( true, fixture.IsOne() );
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsZero() );
-  fixture.CopyVector(&zero);
-  fixture.AddVector(&zero);
+  fixture = zero + zero;
   CPPUNIT_ASSERT_EQUAL( true, fixture.IsZero() );
-  fixture.CopyVector(&notunit);
-  fixture.SubtractVector(&otherunit);
-  CPPUNIT_ASSERT_EQUAL( true, fixture.IsOne() );
-  fixture.CopyVector(&unit);
-  fixture.AddVector(&otherunit);
+  fixture = notunit - otherunit;
+  CPPUNIT_ASSERT_EQUAL( true, fixture.IsOne() );
+  fixture = unit - otherunit;
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsOne() );
-  fixture.CopyVector(&notunit);
-  fixture.SubtractVector(&unit);
-  fixture.SubtractVector(&otherunit);
+  fixture = notunit - unit - otherunit;
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsZero() );
-  fixture.CopyVector(&unit);
-  fixture.Scale(0.98);
+  fixture = 0.98 * unit;
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsOne() );
-  fixture.CopyVector(&unit);
-  fixture.Scale(1.);
-  CPPUNIT_ASSERT_EQUAL( true, fixture.IsOne() );
-  fixture.CopyVector(&unit);
+  fixture = 1. * unit;
+  CPPUNIT_ASSERT_EQUAL( true, fixture.IsOne() );
   factor = 0.98;
-  fixture.Scale(factor);
+  fixture = factor * unit;
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsOne() );
-  fixture.CopyVector(&unit);
   factor = 1.;
-  fixture.Scale(factor);
+  fixture = factor * unit;
   CPPUNIT_ASSERT_EQUAL( true, fixture.IsOne() );
 };
@@ -126,15 +128,15 @@
 void VectorTest::EuclidianScalarProductTest()
 {
-  CPPUNIT_ASSERT_EQUAL( 0., zero.ScalarProduct(&zero) );
-  CPPUNIT_ASSERT_EQUAL( 0., zero.ScalarProduct(&unit) );
-  CPPUNIT_ASSERT_EQUAL( 0., zero.ScalarProduct(&otherunit) );
-  CPPUNIT_ASSERT_EQUAL( 0., zero.ScalarProduct(&notunit) );
-  CPPUNIT_ASSERT_EQUAL( 1., unit.ScalarProduct(&unit) );
-  CPPUNIT_ASSERT_EQUAL( 0., otherunit.ScalarProduct(&unit) );
-  CPPUNIT_ASSERT_EQUAL( 0., otherunit.ScalarProduct(&unit) );
-  CPPUNIT_ASSERT_EQUAL( 1., otherunit.ScalarProduct(&notunit) );
-  CPPUNIT_ASSERT_EQUAL( 2., two.ScalarProduct(&unit) );
-  CPPUNIT_ASSERT_EQUAL( 1., two.ScalarProduct(&otherunit) );
-  CPPUNIT_ASSERT_EQUAL( 1., two.ScalarProduct(&notunit) );
+  CPPUNIT_ASSERT_EQUAL( 0., zero.ScalarProduct(zero) );
+  CPPUNIT_ASSERT_EQUAL( 0., zero.ScalarProduct(unit) );
+  CPPUNIT_ASSERT_EQUAL( 0., zero.ScalarProduct(otherunit) );
+  CPPUNIT_ASSERT_EQUAL( 0., zero.ScalarProduct(notunit) );
+  CPPUNIT_ASSERT_EQUAL( 1., unit.ScalarProduct(unit) );
+  CPPUNIT_ASSERT_EQUAL( 0., otherunit.ScalarProduct(unit) );
+  CPPUNIT_ASSERT_EQUAL( 0., otherunit.ScalarProduct(unit) );
+  CPPUNIT_ASSERT_EQUAL( 1., otherunit.ScalarProduct(notunit) );
+  CPPUNIT_ASSERT_EQUAL( 2., two.ScalarProduct(unit) );
+  CPPUNIT_ASSERT_EQUAL( 1., two.ScalarProduct(otherunit) );
+  CPPUNIT_ASSERT_EQUAL( 1., two.ScalarProduct(notunit) );
 }
 
@@ -157,9 +159,9 @@
 void VectorTest::EuclidianDistancesTest()
 {
-  CPPUNIT_ASSERT_EQUAL( 1., zero.Distance(&unit) );
-  CPPUNIT_ASSERT_EQUAL( sqrt(2.), otherunit.Distance(&unit) );
-  CPPUNIT_ASSERT_EQUAL( sqrt(2.), zero.Distance(&notunit) );
-  CPPUNIT_ASSERT_EQUAL( 1., otherunit.Distance(&notunit) );
-  CPPUNIT_ASSERT_EQUAL( sqrt(5.), two.Distance(&notunit) );
+  CPPUNIT_ASSERT_EQUAL( 1., zero.distance(unit) );
+  CPPUNIT_ASSERT_EQUAL( sqrt(2.), otherunit.distance(unit) );
+  CPPUNIT_ASSERT_EQUAL( sqrt(2.), zero.distance(notunit) );
+  CPPUNIT_ASSERT_EQUAL( 1., otherunit.distance(notunit) );
+  CPPUNIT_ASSERT_EQUAL( sqrt(5.), two.distance(notunit) );
 }
 
@@ -168,9 +170,9 @@
 void VectorTest::EuclidianAnglesTest()
 {
-  CPPUNIT_ASSERT_EQUAL( M_PI, zero.Angle(&unit) );
-  CPPUNIT_ASSERT_EQUAL( 0., unit.Angle(&unit) );
-  CPPUNIT_ASSERT_EQUAL( true, fabs(M_PI/2. - otherunit.Angle(&unit)) < MYEPSILON );
-  CPPUNIT_ASSERT_EQUAL( true, fabs(M_PI/2. - unit.Angle(&notunit)) < MYEPSILON );
-  CPPUNIT_ASSERT_EQUAL( true, fabs(M_PI/4. - otherunit.Angle(&notunit)) < MYEPSILON );
+  CPPUNIT_ASSERT_EQUAL( M_PI, zero.Angle(unit) );
+  CPPUNIT_ASSERT_EQUAL( 0., unit.Angle(unit) );
+  CPPUNIT_ASSERT_EQUAL( true, fabs(M_PI/2. - otherunit.Angle(unit)) < MYEPSILON );
+  CPPUNIT_ASSERT_EQUAL( true, fabs(M_PI/2. - unit.Angle(notunit)) < MYEPSILON );
+  CPPUNIT_ASSERT_EQUAL( true, fabs(M_PI/4. - otherunit.Angle(notunit)) < MYEPSILON );
 };
 
@@ -179,9 +181,38 @@
 void VectorTest::ProjectionTest()
 {
-  CPPUNIT_ASSERT_EQUAL( zero, zero.Projection(&unit) );
-  CPPUNIT_ASSERT_EQUAL( zero, otherunit.Projection(&unit) );
-  CPPUNIT_ASSERT_EQUAL( Vector(0.4,0.2,0.),  otherunit.Projection(&two) );
-  CPPUNIT_ASSERT_EQUAL( Vector(0.,1.,0.),  two.Projection(&otherunit) );
-};
+  CPPUNIT_ASSERT_EQUAL( zero, zero.Projection(unit) );
+  CPPUNIT_ASSERT_EQUAL( zero, otherunit.Projection(unit) );
+  CPPUNIT_ASSERT_EQUAL( Vector(0.4,0.2,0.),  otherunit.Projection(two) );
+  CPPUNIT_ASSERT_EQUAL( Vector(0.,1.,0.),  two.Projection(otherunit) );
+};
+
+/**
+ * Unittest for operation with normals
+ */
+void VectorTest::NormalsTest(){
+  Vector testVector;
+  // the zero Vector should produce an error
+  CPPUNIT_ASSERT(!testVector.GetOneNormalVector(zero));
+
+  // first one-component system
+  CPPUNIT_ASSERT(testVector.GetOneNormalVector(unit));
+  CPPUNIT_ASSERT(testVector.ScalarProduct(unit) < MYEPSILON);
+
+  // second one-component system
+  CPPUNIT_ASSERT(testVector.GetOneNormalVector(otherunit));
+  CPPUNIT_ASSERT(testVector.ScalarProduct(otherunit) < MYEPSILON);
+
+  // first two-component system
+  CPPUNIT_ASSERT(testVector.GetOneNormalVector(notunit));
+  CPPUNIT_ASSERT(testVector.ScalarProduct(notunit) < MYEPSILON);
+
+  // second two-component system
+  CPPUNIT_ASSERT(testVector.GetOneNormalVector(two));
+  CPPUNIT_ASSERT(testVector.ScalarProduct(two) < MYEPSILON);
+
+  // three component system
+  CPPUNIT_ASSERT(testVector.GetOneNormalVector(three));
+  CPPUNIT_ASSERT(testVector.ScalarProduct(three) < MYEPSILON);
+}
 
 /** UnitTest for line intersections.
@@ -190,73 +221,64 @@
 {
   // plane at (0,0,0) normal to (1,0,0) cuts line from (0,0,0) to (2,1,0) at ???
-  CPPUNIT_ASSERT_EQUAL( true, fixture.GetIntersectionWithPlane(&unit, &zero, &zero, &two) );
+  CPPUNIT_ASSERT_NO_THROW(fixture = Plane(unit, zero).GetIntersection(zero, two) );
   CPPUNIT_ASSERT_EQUAL( zero, fixture );
 
   // plane at (2,1,0) normal to (0,1,0) cuts line from (1,0,0) to (0,1,1) at ???
-  CPPUNIT_ASSERT_EQUAL( true, fixture.GetIntersectionWithPlane(&otherunit, &two, &unit, &notunit) );
+  CPPUNIT_ASSERT_NO_THROW(fixture = Plane(otherunit, two).GetIntersection( unit, notunit) );
   CPPUNIT_ASSERT_EQUAL( Vector(0., 1., 1.), fixture );
 
   // four vectors equal to zero
-  CPPUNIT_ASSERT_EQUAL( false, fixture.GetIntersectionOfTwoLinesOnPlane(&zero, &zero, &zero, &zero, NULL) );
+  CPPUNIT_ASSERT_THROW(fixture = GetIntersectionOfTwoLinesOnPlane(zero, zero, zero, zero), LinearDependenceException);
+  //CPPUNIT_ASSERT_EQUAL( zero, fixture );
+
+  // four vectors equal to unit
+  CPPUNIT_ASSERT_THROW(fixture = GetIntersectionOfTwoLinesOnPlane(unit, unit, unit, unit), LinearDependenceException);
+  //CPPUNIT_ASSERT_EQUAL( zero, fixture );
+
+  // two equal lines
+  CPPUNIT_ASSERT_NO_THROW(fixture = GetIntersectionOfTwoLinesOnPlane(unit, two, unit, two));
+  CPPUNIT_ASSERT_EQUAL( unit, fixture );
+
+  // line from (1,0,0) to (2,1,0) cuts line from (1,0,0) to (0,1,0) at ???
+  CPPUNIT_ASSERT_NO_THROW( fixture = GetIntersectionOfTwoLinesOnPlane(unit, two, unit, otherunit) );
+  CPPUNIT_ASSERT_EQUAL( unit, fixture );
+
+  // line from (1,0,0) to (0,0,0) cuts line from (0,0,0) to (2,1,0) at ???
+  CPPUNIT_ASSERT_NO_THROW( fixture = GetIntersectionOfTwoLinesOnPlane(unit, zero, zero, two) );
   CPPUNIT_ASSERT_EQUAL( zero, fixture );
 
-  // four vectors equal to unit
-  CPPUNIT_ASSERT_EQUAL( false, fixture.GetIntersectionOfTwoLinesOnPlane(&unit, &unit, &unit, &unit, NULL) );
+  // line from (1,0,0) to (2,1,0) cuts line from (0,0,0) to (0,1,0) at ???
+  CPPUNIT_ASSERT_NO_THROW(fixture = GetIntersectionOfTwoLinesOnPlane(unit, two, zero, otherunit) );
+  CPPUNIT_ASSERT_EQUAL( Vector(0., -1., 0.), fixture );
+};
+
+/** UnitTest for vector rotations.
+ */
+void VectorTest::VectorRotationTest()
+{
+  fixture = Vector(-1.,0.,0.);
+
+  // zero vector does not change
+  fixture = RotateVector(zero,unit, 1.);
   CPPUNIT_ASSERT_EQUAL( zero, fixture );
 
-  // two equal lines
-  CPPUNIT_ASSERT_EQUAL( true, fixture.GetIntersectionOfTwoLinesOnPlane(&unit, &two, &unit, &two, NULL) );
+  fixture = RotateVector(zero, two, 1.);
+  CPPUNIT_ASSERT_EQUAL( zero,  fixture);
+
+  // vector on axis does not change
+  fixture = RotateVector(unit,unit, 1.);
   CPPUNIT_ASSERT_EQUAL( unit, fixture );
 
-  // line from (1,0,0) to (2,1,0) cuts line from (1,0,0) to (0,1,0) at ???
-  CPPUNIT_ASSERT_EQUAL( true, fixture.GetIntersectionOfTwoLinesOnPlane(&unit, &two, &unit, &otherunit, NULL) );
-  CPPUNIT_ASSERT_EQUAL( unit, fixture );
-
-  // line from (1,0,0) to (0,0,0) cuts line from (0,0,0) to (2,1,0) at ???
-  CPPUNIT_ASSERT_EQUAL( true, fixture.GetIntersectionOfTwoLinesOnPlane(&unit, &zero, &zero, &two, NULL) );
-  CPPUNIT_ASSERT_EQUAL( zero, fixture );
-
-  // line from (1,0,0) to (2,1,0) cuts line from (0,0,0) to (0,1,0) at ???
-  CPPUNIT_ASSERT_EQUAL( true, fixture.GetIntersectionOfTwoLinesOnPlane(&unit, &two, &zero, &otherunit, NULL) );
-  CPPUNIT_ASSERT_EQUAL( Vector(0., -1., 0.), fixture );
-};
-
-/** UnitTest for vector rotations.
- */
-void VectorTest::VectorRotationTest()
-{
-  fixture.Init(-1.,0.,0.);
-
-  // zero vector does not change
-  fixture.CopyVector(&zero);
-  fixture.RotateVector(&unit, 1.);
-  CPPUNIT_ASSERT_EQUAL( zero, fixture );
-
-  fixture.RotateVector(&two, 1.);
-  CPPUNIT_ASSERT_EQUAL( zero,  fixture);
-
-  // vector on axis does not change
-  fixture.CopyVector(&unit);
-  fixture.RotateVector(&unit, 1.);
-  CPPUNIT_ASSERT_EQUAL( unit, fixture );
-
-  fixture.RotateVector(&unit, 1.);
-  CPPUNIT_ASSERT_EQUAL( unit, fixture );
-
   // rotations
-  fixture.CopyVector(&otherunit);
-  fixture.RotateVector(&unit, M_PI);
+  fixture = RotateVector(otherunit, unit, M_PI);
   CPPUNIT_ASSERT_EQUAL( Vector(0.,-1.,0.), fixture );
 
-  fixture.CopyVector(&otherunit);
-  fixture.RotateVector(&unit, 2. * M_PI);
+  fixture = RotateVector(otherunit, unit, 2. * M_PI);
   CPPUNIT_ASSERT_EQUAL( otherunit, fixture );
 
-  fixture.CopyVector(&otherunit);
-  fixture.RotateVector(&unit, 0);
+  fixture = RotateVector(otherunit,unit, 0);
   CPPUNIT_ASSERT_EQUAL( otherunit, fixture );
 
-  fixture.Init(0.,0.,1.);
-  fixture.RotateVector(&notunit, M_PI);
+  fixture = RotateVector(Vector(0.,0.,1.), notunit, M_PI);
   CPPUNIT_ASSERT_EQUAL( otherunit, fixture );
 }
@@ -278,17 +300,17 @@
   parallelepiped[8] = 1;
 
-  fixture.CopyVector(zero);
+  fixture = zero;
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsInParallelepiped(Vector(2.,2.,2.), parallelepiped) );
-  fixture.Init(2.5,2.5,2.5);
+  fixture = Vector(2.5,2.5,2.5);
   CPPUNIT_ASSERT_EQUAL( true, fixture.IsInParallelepiped(Vector(2.,2.,2.), parallelepiped) );
-  fixture.Init(1.,1.,1.);
+  fixture = Vector(1.,1.,1.);
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsInParallelepiped(Vector(2.,2.,2.), parallelepiped) );
-  fixture.Init(3.5,3.5,3.5);
+  fixture = Vector(3.5,3.5,3.5);
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsInParallelepiped(Vector(2.,2.,2.), parallelepiped) );
-  fixture.Init(2.,2.,2.);
+  fixture = Vector(2.,2.,2.);
   CPPUNIT_ASSERT_EQUAL( true, fixture.IsInParallelepiped(Vector(2.,2.,2.), parallelepiped) );
-  fixture.Init(2.,3.,2.);
+  fixture = Vector(2.,3.,2.);
   CPPUNIT_ASSERT_EQUAL( true, fixture.IsInParallelepiped(Vector(2.,2.,2.), parallelepiped) );
-  fixture.Init(-2.,2.,-1.);
+  fixture = Vector(-2.,2.,-1.);
   CPPUNIT_ASSERT_EQUAL( false, fixture.IsInParallelepiped(Vector(2.,2.,2.), parallelepiped) );
 }
Index: src/unittests/vectorunittest.hpp
===================================================================
--- src/unittests/vectorunittest.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/unittests/vectorunittest.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -26,4 +26,5 @@
     CPPUNIT_TEST ( EuclidianAnglesTest );
     CPPUNIT_TEST ( ProjectionTest );
+    CPPUNIT_TEST ( NormalsTest );
     CPPUNIT_TEST ( LineIntersectionTest );
     CPPUNIT_TEST ( VectorRotationTest );
@@ -43,4 +44,5 @@
     void EuclidianAnglesTest();
     void ProjectionTest();
+    void NormalsTest();
     void LineIntersectionTest();
     void VectorRotationTest();
@@ -56,4 +58,5 @@
     Vector notunit;
     Vector two;
+    Vector three;
 };
 
Index: src/vector.cpp
===================================================================
--- src/vector.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/vector.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -6,18 +6,14 @@
 
 
-#include "defs.hpp"
-#include "helpers.hpp"
-#include "info.hpp"
-#include "gslmatrix.hpp"
-#include "leastsquaremin.hpp"
-#include "log.hpp"
-#include "memoryallocator.hpp"
 #include "vector.hpp"
 #include "verbose.hpp"
-
-#include <gsl/gsl_linalg.h>
-#include <gsl/gsl_matrix.h>
-#include <gsl/gsl_permutation.h>
-#include <gsl/gsl_vector.h>
+#include "World.hpp"
+#include "Helpers/Assert.hpp"
+#include "Helpers/fast_functions.hpp"
+
+#include <iostream>
+
+using namespace std;
+
 
 /************************************ Functions for class vector ************************************/
@@ -25,9 +21,41 @@
 /** Constructor of class vector.
  */
-Vector::Vector() { x[0] = x[1] = x[2] = 0.; };
+Vector::Vector()
+{
+  x[0] = x[1] = x[2] = 0.;
+};
+
+/**
+ * Copy constructor
+ */
+
+Vector::Vector(const Vector& src)
+{
+  x[0] = src[0];
+  x[1] = src[1];
+  x[2] = src[2];
+}
 
 /** Constructor of class vector.
  */
-Vector::Vector(const double x1, const double x2, const double x3) { x[0] = x1; x[1] = x2; x[2] = x3; };
+Vector::Vector(const double x1, const double x2, const double x3)
+{
+  x[0] = x1;
+  x[1] = x2;
+  x[2] = x3;
+};
+
+/**
+ * Assignment operator
+ */
+Vector& Vector::operator=(const Vector& src){
+  // check for self assignment
+  if(&src!=this){
+    x[0] = src[0];
+    x[1] = src[1];
+    x[2] = src[2];
+  }
+  return *this;
+}
 
 /** Desctructor of class vector.
@@ -39,9 +67,9 @@
  * \return \f$| x - y |^2\f$
  */
-double Vector::DistanceSquared(const Vector * const y) const
+double Vector::DistanceSquared(const Vector &y) const
 {
   double res = 0.;
   for (int i=NDIM;i--;)
-    res += (x[i]-y->x[i])*(x[i]-y->x[i]);
+    res += (x[i]-y[i])*(x[i]-y[i]);
   return (res);
 };
@@ -51,11 +79,13 @@
  * \return \f$| x - y |\f$
  */
-double Vector::Distance(const Vector * const y) const
-{
-  double res = 0.;
-  for (int i=NDIM;i--;)
-    res += (x[i]-y->x[i])*(x[i]-y->x[i]);
-  return (sqrt(res));
-};
+double Vector::distance(const Vector &y) const
+{
+  return (sqrt(DistanceSquared(y)));
+};
+
+Vector Vector::getClosestPoint(const Vector &point) const{
+  // the closest point to a single point space is always the single point itself
+  return *this;
+}
 
 /** Calculates distance between this and another vector in a periodic cell.
@@ -64,35 +94,34 @@
  * \return \f$| x - y |\f$
  */
-double Vector::PeriodicDistance(const Vector * const y, const double * const cell_size) const
-{
-  double res = Distance(y), tmp, matrix[NDIM*NDIM];
-  Vector Shiftedy, TranslationVector;
-  int N[NDIM];
-  matrix[0] = cell_size[0];
-  matrix[1] = cell_size[1];
-  matrix[2] = cell_size[3];
-  matrix[3] = cell_size[1];
-  matrix[4] = cell_size[2];
-  matrix[5] = cell_size[4];
-  matrix[6] = cell_size[3];
-  matrix[7] = cell_size[4];
-  matrix[8] = cell_size[5];
-  // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
-  for (N[0]=-1;N[0]<=1;N[0]++)
-    for (N[1]=-1;N[1]<=1;N[1]++)
-      for (N[2]=-1;N[2]<=1;N[2]++) {
-        // create the translation vector
-        TranslationVector.Zero();
-        for (int i=NDIM;i--;)
-          TranslationVector.x[i] = (double)N[i];
-        TranslationVector.MatrixMultiplication(matrix);
-        // add onto the original vector to compare with
-        Shiftedy.CopyVector(y);
-        Shiftedy.AddVector(&TranslationVector);
-        // get distance and compare with minimum so far
-        tmp = Distance(&Shiftedy);
-        if (tmp < res) res = tmp;
-      }
-  return (res);
+double Vector::PeriodicDistance(const Vector &y, const double * const cell_size) const
+{
+  double res = distance(y), tmp, matrix[NDIM*NDIM];
+    Vector Shiftedy, TranslationVector;
+    int N[NDIM];
+    matrix[0] = cell_size[0];
+    matrix[1] = cell_size[1];
+    matrix[2] = cell_size[3];
+    matrix[3] = cell_size[1];
+    matrix[4] = cell_size[2];
+    matrix[5] = cell_size[4];
+    matrix[6] = cell_size[3];
+    matrix[7] = cell_size[4];
+    matrix[8] = cell_size[5];
+    // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
+    for (N[0]=-1;N[0]<=1;N[0]++)
+      for (N[1]=-1;N[1]<=1;N[1]++)
+        for (N[2]=-1;N[2]<=1;N[2]++) {
+          // create the translation vector
+          TranslationVector.Zero();
+          for (int i=NDIM;i--;)
+            TranslationVector[i] = (double)N[i];
+          TranslationVector.MatrixMultiplication(matrix);
+          // add onto the original vector to compare with
+          Shiftedy = y + TranslationVector;
+          // get distance and compare with minimum so far
+          tmp = distance(Shiftedy);
+          if (tmp < res) res = tmp;
+        }
+    return (res);
 };
 
@@ -102,35 +131,34 @@
  * \return \f$| x - y |^2\f$
  */
-double Vector::PeriodicDistanceSquared(const Vector * const y, const double * const cell_size) const
+double Vector::PeriodicDistanceSquared(const Vector &y, const double * const cell_size) const
 {
   double res = DistanceSquared(y), tmp, matrix[NDIM*NDIM];
-  Vector Shiftedy, TranslationVector;
-  int N[NDIM];
-  matrix[0] = cell_size[0];
-  matrix[1] = cell_size[1];
-  matrix[2] = cell_size[3];
-  matrix[3] = cell_size[1];
-  matrix[4] = cell_size[2];
-  matrix[5] = cell_size[4];
-  matrix[6] = cell_size[3];
-  matrix[7] = cell_size[4];
-  matrix[8] = cell_size[5];
-  // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
-  for (N[0]=-1;N[0]<=1;N[0]++)
-    for (N[1]=-1;N[1]<=1;N[1]++)
-      for (N[2]=-1;N[2]<=1;N[2]++) {
-        // create the translation vector
-        TranslationVector.Zero();
-        for (int i=NDIM;i--;)
-          TranslationVector.x[i] = (double)N[i];
-        TranslationVector.MatrixMultiplication(matrix);
-        // add onto the original vector to compare with
-        Shiftedy.CopyVector(y);
-        Shiftedy.AddVector(&TranslationVector);
-        // get distance and compare with minimum so far
-        tmp = DistanceSquared(&Shiftedy);
-        if (tmp < res) res = tmp;
-      }
-  return (res);
+    Vector Shiftedy, TranslationVector;
+    int N[NDIM];
+    matrix[0] = cell_size[0];
+    matrix[1] = cell_size[1];
+    matrix[2] = cell_size[3];
+    matrix[3] = cell_size[1];
+    matrix[4] = cell_size[2];
+    matrix[5] = cell_size[4];
+    matrix[6] = cell_size[3];
+    matrix[7] = cell_size[4];
+    matrix[8] = cell_size[5];
+    // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
+    for (N[0]=-1;N[0]<=1;N[0]++)
+      for (N[1]=-1;N[1]<=1;N[1]++)
+        for (N[2]=-1;N[2]<=1;N[2]++) {
+          // create the translation vector
+          TranslationVector.Zero();
+          for (int i=NDIM;i--;)
+            TranslationVector[i] = (double)N[i];
+          TranslationVector.MatrixMultiplication(matrix);
+          // add onto the original vector to compare with
+          Shiftedy = y + TranslationVector;
+          // get distance and compare with minimum so far
+          tmp = DistanceSquared(Shiftedy);
+          if (tmp < res) res = tmp;
+        }
+    return (res);
 };
 
@@ -141,27 +169,24 @@
 void Vector::KeepPeriodic(const double * const matrix)
 {
-//  int N[NDIM];
-//  bool flag = false;
-  //vector Shifted, TranslationVector;
-  Vector TestVector;
-//  Log() << Verbose(1) << "Begin of KeepPeriodic." << endl;
-//  Log() << Verbose(2) << "Vector is: ";
-//  Output(out);
-//  Log() << Verbose(0) << endl;
-  TestVector.CopyVector(this);
-  TestVector.InverseMatrixMultiplication(matrix);
-  for(int i=NDIM;i--;) { // correct periodically
-    if (TestVector.x[i] < 0) {  // get every coefficient into the interval [0,1)
-      TestVector.x[i] += ceil(TestVector.x[i]);
-    } else {
-      TestVector.x[i] -= floor(TestVector.x[i]);
+  //  int N[NDIM];
+  //  bool flag = false;
+    //vector Shifted, TranslationVector;
+  //  Log() << Verbose(1) << "Begin of KeepPeriodic." << endl;
+  //  Log() << Verbose(2) << "Vector is: ";
+  //  Output(out);
+  //  Log() << Verbose(0) << endl;
+    InverseMatrixMultiplication(matrix);
+    for(int i=NDIM;i--;) { // correct periodically
+      if (at(i) < 0) {  // get every coefficient into the interval [0,1)
+        at(i) += ceil(at(i));
+      } else {
+        at(i) -= floor(at(i));
+      }
     }
-  }
-  TestVector.MatrixMultiplication(matrix);
-  CopyVector(&TestVector);
-//  Log() << Verbose(2) << "New corrected vector is: ";
-//  Output(out);
-//  Log() << Verbose(0) << endl;
-//  Log() << Verbose(1) << "End of KeepPeriodic." << endl;
+    MatrixMultiplication(matrix);
+  //  Log() << Verbose(2) << "New corrected vector is: ";
+  //  Output(out);
+  //  Log() << Verbose(0) << endl;
+  //  Log() << Verbose(1) << "End of KeepPeriodic." << endl;
 };
 
@@ -170,9 +195,9 @@
  * \return \f$\langle x, y \rangle\f$
  */
-double Vector::ScalarProduct(const Vector * const y) const
+double Vector::ScalarProduct(const Vector &y) const
 {
   double res = 0.;
   for (int i=NDIM;i--;)
-    res += x[i]*y->x[i];
+    res += x[i]*y[i];
   return (res);
 };
@@ -185,11 +210,11 @@
  *  \return \f$ x \times y \f&
  */
-void Vector::VectorProduct(const Vector * const y)
+void Vector::VectorProduct(const Vector &y)
 {
   Vector tmp;
-  tmp.x[0] = x[1]* (y->x[2]) - x[2]* (y->x[1]);
-  tmp.x[1] = x[2]* (y->x[0]) - x[0]* (y->x[2]);
-  tmp.x[2] = x[0]* (y->x[1]) - x[1]* (y->x[0]);
-  this->CopyVector(&tmp);
+  tmp[0] = x[1]* (y[2]) - x[2]* (y[1]);
+  tmp[1] = x[2]* (y[0]) - x[0]* (y[2]);
+  tmp[2] = x[0]* (y[1]) - x[1]* (y[0]);
+  (*this) = tmp;
 };
 
@@ -199,90 +224,27 @@
  * \return \f$\langle x, y \rangle\f$
  */
-void Vector::ProjectOntoPlane(const Vector * const y)
+void Vector::ProjectOntoPlane(const Vector &y)
 {
   Vector tmp;
-  tmp.CopyVector(y);
+  tmp = y;
   tmp.Normalize();
-  tmp.Scale(ScalarProduct(&tmp));
-  this->SubtractVector(&tmp);
-};
-
-/** Calculates the intersection point between a line defined by \a *LineVector and \a *LineVector2 and a plane defined by \a *Normal and \a *PlaneOffset.
- * According to [Bronstein] the vectorial plane equation is:
- *   -# \f$\stackrel{r}{\rightarrow} \cdot \stackrel{N}{\rightarrow} + D = 0\f$,
- * where \f$\stackrel{r}{\rightarrow}\f$ is the vector to be testet, \f$\stackrel{N}{\rightarrow}\f$ is the plane's normal vector and
- * \f$D = - \stackrel{a}{\rightarrow} \stackrel{N}{\rightarrow}\f$, the offset with respect to origin, if \f$\stackrel{a}{\rightarrow}\f$,
- * is an offset vector onto the plane. The line is parametrized by \f$\stackrel{x}{\rightarrow} + k \stackrel{t}{\rightarrow}\f$, where
- * \f$\stackrel{x}{\rightarrow}\f$ is the offset and \f$\stackrel{t}{\rightarrow}\f$ the directional vector (NOTE: No need to normalize
- * the latter). Inserting the parametrized form into the plane equation and solving for \f$k\f$, which we insert then into the parametrization
- * of the line yields the intersection point on the plane.
- * \param *out output stream for debugging
- * \param *PlaneNormal Plane's normal vector
- * \param *PlaneOffset Plane's offset vector
- * \param *Origin first vector of line
- * \param *LineVector second vector of line
- * \return true -  \a this contains intersection point on return, false - line is parallel to plane (even if in-plane)
- */
-bool Vector::GetIntersectionWithPlane(const Vector * const PlaneNormal, const Vector * const PlaneOffset, const Vector * const Origin, const Vector * const LineVector)
-{
-  Info FunctionInfo(__func__);
-  double factor;
-  Vector Direction, helper;
-
-  // find intersection of a line defined by Offset and Direction with a  plane defined by triangle
-  Direction.CopyVector(LineVector);
-  Direction.SubtractVector(Origin);
-  Direction.Normalize();
-  Log() << Verbose(1) << "INFO: Direction is " << Direction << "." << endl;
-  //Log() << Verbose(1) << "INFO: PlaneNormal is " << *PlaneNormal << " and PlaneOffset is " << *PlaneOffset << "." << endl;
-  factor = Direction.ScalarProduct(PlaneNormal);
-  if (fabs(factor) < MYEPSILON) { // Uniqueness: line parallel to plane?
-    Log() << Verbose(1) << "BAD: Line is parallel to plane, no intersection." << endl;
-    return false;
-  }
-  helper.CopyVector(PlaneOffset);
-  helper.SubtractVector(Origin);
-  factor = helper.ScalarProduct(PlaneNormal)/factor;
-  if (fabs(factor) < MYEPSILON) { // Origin is in-plane
-    Log() << Verbose(1) << "GOOD: Origin of line is in-plane." << endl;
-    CopyVector(Origin);
-    return true;
-  }
-  //factor = Origin->ScalarProduct(PlaneNormal)*(-PlaneOffset->ScalarProduct(PlaneNormal))/(Direction.ScalarProduct(PlaneNormal));
-  Direction.Scale(factor);
-  CopyVector(Origin);
-  Log() << Verbose(1) << "INFO: Scaled direction is " << Direction << "." << endl;
-  AddVector(&Direction);
-
-  // test whether resulting vector really is on plane
-  helper.CopyVector(this);
-  helper.SubtractVector(PlaneOffset);
-  if (helper.ScalarProduct(PlaneNormal) < MYEPSILON) {
-    Log() << Verbose(1) << "GOOD: Intersection is " << *this << "." << endl;
-    return true;
-  } else {
-    eLog() << Verbose(2) << "Intersection point " << *this << " is not on plane." << endl;
-    return false;
-  }
-};
-
-/** Calculates the minimum distance of this vector to the plane.
+  tmp.Scale(ScalarProduct(tmp));
+  *this -= tmp;
+};
+
+/** Calculates the minimum distance vector of this vector to the plane.
  * \param *out output stream for debugging
  * \param *PlaneNormal normal of plane
  * \param *PlaneOffset offset of plane
  * \return distance to plane
- */
-double Vector::DistanceToPlane(const Vector * const PlaneNormal, const Vector * const PlaneOffset) const
-{
-  Vector temp;
-
-  // first create part that is orthonormal to PlaneNormal with withdraw
-  temp.CopyVector(this);
-  temp.SubtractVector(PlaneOffset);
-  temp.MakeNormalVector(PlaneNormal);
+ * \return distance vector onto to plane
+ */
+Vector Vector::GetDistanceVectorToPlane(const Vector &PlaneNormal, const Vector &PlaneOffset) const
+{
+  Vector temp = (*this) - PlaneOffset;
+  temp.MakeNormalTo(PlaneNormal);
   temp.Scale(-1.);
   // then add connecting vector from plane to point
-  temp.AddVector(this);
-  temp.SubtractVector(PlaneOffset);
+  temp += (*this)-PlaneOffset;
   double sign = temp.ScalarProduct(PlaneNormal);
   if (fabs(sign) > MYEPSILON)
@@ -291,111 +253,20 @@
     sign = 0.;
 
-  return (temp.Norm()*sign);
-};
-
-/** Calculates the intersection of the two lines that are both on the same plane.
- * This is taken from Weisstein, Eric W. "Line-Line Intersection." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/Line-LineIntersection.html 
+  temp.Normalize();
+  temp.Scale(sign);
+  return temp;
+};
+
+
+/** Calculates the minimum distance of this vector to the plane.
+ * \sa Vector::GetDistanceVectorToPlane()
  * \param *out output stream for debugging
- * \param *Line1a first vector of first line
- * \param *Line1b second vector of first line
- * \param *Line2a first vector of second line
- * \param *Line2b second vector of second line
- * \param *PlaneNormal normal of plane, is supplemental/arbitrary
- * \return true - \a this will contain the intersection on return, false - lines are parallel
- */
-bool Vector::GetIntersectionOfTwoLinesOnPlane(const Vector * const Line1a, const Vector * const Line1b, const Vector * const Line2a, const Vector * const Line2b, const Vector *PlaneNormal)
-{
-  Info FunctionInfo(__func__);
-
-  GSLMatrix *M = new GSLMatrix(4,4);
-
-  M->SetAll(1.);
-  for (int i=0;i<3;i++) {
-    M->Set(0, i, Line1a->x[i]);
-    M->Set(1, i, Line1b->x[i]);
-    M->Set(2, i, Line2a->x[i]);
-    M->Set(3, i, Line2b->x[i]);
-  }
-  
-  //Log() << Verbose(1) << "Coefficent matrix is:" << endl;
-  //for (int i=0;i<4;i++) {
-  //  for (int j=0;j<4;j++)
-  //    cout << "\t" << M->Get(i,j);
-  //  cout << endl;
-  //}
-  if (fabs(M->Determinant()) > MYEPSILON) {
-    Log() << Verbose(1) << "Determinant of coefficient matrix is NOT zero." << endl;
-    return false;
-  }
-  Log() << Verbose(1) << "INFO: Line1a = " << *Line1a << ", Line1b = " << *Line1b << ", Line2a = " << *Line2a << ", Line2b = " << *Line2b << "." << endl;
-
-
-  // constuct a,b,c
-  Vector a;
-  Vector b;
-  Vector c;
-  Vector d;
-  a.CopyVector(Line1b);
-  a.SubtractVector(Line1a);
-  b.CopyVector(Line2b);
-  b.SubtractVector(Line2a);
-  c.CopyVector(Line2a);
-  c.SubtractVector(Line1a);
-  d.CopyVector(Line2b);
-  d.SubtractVector(Line1b);
-  Log() << Verbose(1) << "INFO: a = " << a << ", b = " << b << ", c = " << c << "." << endl;
-  if ((a.NormSquared() < MYEPSILON) || (b.NormSquared() < MYEPSILON)) {
-   Zero();
-   Log() << Verbose(1) << "At least one of the lines is ill-defined, i.e. offset equals second vector." << endl;
-   return false;
-  }
-
-  // check for parallelity
-  Vector parallel;
-  double factor = 0.;
-  if (fabs(a.ScalarProduct(&b)*a.ScalarProduct(&b)/a.NormSquared()/b.NormSquared() - 1.) < MYEPSILON) {
-    parallel.CopyVector(Line1a);
-    parallel.SubtractVector(Line2a);
-    factor = parallel.ScalarProduct(&a)/a.Norm();
-    if ((factor >= -MYEPSILON) && (factor - 1. < MYEPSILON)) {
-      CopyVector(Line2a);
-      Log() << Verbose(1) << "Lines conincide." << endl;
-      return true;
-    } else {
-      parallel.CopyVector(Line1a);
-      parallel.SubtractVector(Line2b);
-      factor = parallel.ScalarProduct(&a)/a.Norm();
-      if ((factor >= -MYEPSILON) && (factor - 1. < MYEPSILON)) {
-        CopyVector(Line2b);
-        Log() << Verbose(1) << "Lines conincide." << endl;
-        return true;
-      }
-    }
-    Log() << Verbose(1) << "Lines are parallel." << endl;
-    Zero();
-    return false;
-  }
-
-  // obtain s
-  double s;
-  Vector temp1, temp2;
-  temp1.CopyVector(&c);
-  temp1.VectorProduct(&b);
-  temp2.CopyVector(&a);
-  temp2.VectorProduct(&b);
-  Log() << Verbose(1) << "INFO: temp1 = " << temp1 << ", temp2 = " << temp2 << "." << endl;
-  if (fabs(temp2.NormSquared()) > MYEPSILON)
-    s = temp1.ScalarProduct(&temp2)/temp2.NormSquared();
-  else
-    s = 0.;
-  Log() << Verbose(1) << "Factor s is " << temp1.ScalarProduct(&temp2) << "/" << temp2.NormSquared() << " = " << s << "." << endl;
-
-  // construct intersection
-  CopyVector(&a);
-  Scale(s);
-  AddVector(Line1a);
-  Log() << Verbose(1) << "Intersection is at " << *this << "." << endl;
-
-  return true;
+ * \param *PlaneNormal normal of plane
+ * \param *PlaneOffset offset of plane
+ * \return distance to plane
+ */
+double Vector::DistanceToPlane(const Vector &PlaneNormal, const Vector &PlaneOffset) const
+{
+  return GetDistanceVectorToPlane(PlaneNormal,PlaneOffset).Norm();
 };
 
@@ -403,9 +274,7 @@
  * \param *y array to second vector
  */
-void Vector::ProjectIt(const Vector * const y)
-{
-  Vector helper(*y);
-  helper.Scale(-(ScalarProduct(y)));
-  AddVector(&helper);
+void Vector::ProjectIt(const Vector &y)
+{
+  (*this) += (-ScalarProduct(y))*y;
 };
 
@@ -414,8 +283,8 @@
  * \return Vector
  */
-Vector Vector::Projection(const Vector * const y) const
-{
-  Vector helper(*y);
-  helper.Scale((ScalarProduct(y)/y->NormSquared()));
+Vector Vector::Projection(const Vector &y) const
+{
+  Vector helper = y;
+  helper.Scale((ScalarProduct(y)/y.NormSquared()));
 
   return helper;
@@ -427,8 +296,5 @@
 double Vector::Norm() const
 {
-  double res = 0.;
-  for (int i=NDIM;i--;)
-    res += this->x[i]*this->x[i];
-  return (sqrt(res));
+  return (sqrt(NormSquared()));
 };
 
@@ -438,5 +304,5 @@
 double Vector::NormSquared() const
 {
-  return (ScalarProduct(this));
+  return (ScalarProduct(*this));
 };
 
@@ -445,10 +311,6 @@
 void Vector::Normalize()
 {
-  double res = 0.;
-  for (int i=NDIM;i--;)
-    res += this->x[i]*this->x[i];
-  if (fabs(res) > MYEPSILON)
-    res = 1./sqrt(res);
-  Scale(&res);
+  double factor = Norm();
+  (*this) *= 1/factor;
 };
 
@@ -457,6 +319,5 @@
 void Vector::Zero()
 {
-  for (int i=NDIM;i--;)
-    this->x[i] = 0.;
+  at(0)=at(1)=at(2)=0;
 };
 
@@ -465,15 +326,5 @@
 void Vector::One(const double one)
 {
-  for (int i=NDIM;i--;)
-    this->x[i] = one;
-};
-
-/** Initialises all components of this vector.
- */
-void Vector::Init(const double x1, const double x2, const double x3)
-{
-  x[0] = x1;
-  x[1] = x2;
-  x[2] = x3;
+  at(0)=at(1)=at(2)=one;
 };
 
@@ -497,5 +348,5 @@
  * @return true - vector is normalized, false - vector is not
  */
-bool Vector::IsNormalTo(const Vector * const normal) const
+bool Vector::IsNormalTo(const Vector &normal) const
 {
   if (ScalarProduct(normal) < MYEPSILON)
@@ -508,9 +359,9 @@
  * @return true - vector is normalized, false - vector is not
  */
-bool Vector::IsEqualTo(const Vector * const a) const
+bool Vector::IsEqualTo(const Vector &a) const
 {
   bool status = true;
   for (int i=0;i<NDIM;i++) {
-    if (fabs(x[i] - a->x[i]) > MYEPSILON)
+    if (fabs(x[i] - a[i]) > MYEPSILON)
       status = false;
   }
@@ -522,7 +373,7 @@
  * \return \f$\acos\bigl(frac{\langle x, y \rangle}{|x||y|}\bigr)\f$
  */
-double Vector::Angle(const Vector * const y) const
-{
-  double norm1 = Norm(), norm2 = y->Norm();
+double Vector::Angle(const Vector &y) const
+{
+  double norm1 = Norm(), norm2 = y.Norm();
   double angle = -1;
   if ((fabs(norm1) > MYEPSILON) && (fabs(norm2) > MYEPSILON))
@@ -537,31 +388,26 @@
 };
 
-/** Rotates the vector relative to the origin around the axis given by \a *axis by an angle of \a alpha.
- * \param *axis rotation axis
- * \param alpha rotation angle in radian
- */
-void Vector::RotateVector(const Vector * const axis, const double alpha)
-{
-  Vector a,y;
-  // normalise this vector with respect to axis
-  a.CopyVector(this);
-  a.ProjectOntoPlane(axis);
-  // construct normal vector
-  bool rotatable = y.MakeNormalVector(axis,&a);
-  // The normal vector cannot be created if there is linar dependency.
-  // Then the vector to rotate is on the axis and any rotation leads to the vector itself.
-  if (!rotatable) {
-    return;
-  }
-  y.Scale(Norm());
-  // scale normal vector by sine and this vector by cosine
-  y.Scale(sin(alpha));
-  a.Scale(cos(alpha));
-  CopyVector(Projection(axis));
-  // add scaled normal vector onto this vector
-  AddVector(&y);
-  // add part in axis direction
-  AddVector(&a);
-};
+
+double& Vector::operator[](size_t i){
+  ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
+  return x[i];
+}
+
+const double& Vector::operator[](size_t i) const{
+  ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
+  return x[i];
+}
+
+double& Vector::at(size_t i){
+  return (*this)[i];
+}
+
+const double& Vector::at(size_t i) const{
+  return (*this)[i];
+}
+
+double* Vector::get(){
+  return x;
+}
 
 /** Compares vector \a to vector \a b component-wise.
@@ -570,11 +416,13 @@
  * \return a == b
  */
-bool operator==(const Vector& a, const Vector& b)
-{
-  bool status = true;
-  for (int i=0;i<NDIM;i++)
-    status = status && (fabs(a.x[i] - b.x[i]) < MYEPSILON);
-  return status;
-};
+bool Vector::operator==(const Vector& b) const
+{
+  return IsEqualTo(b);
+};
+
+bool Vector::operator!=(const Vector& b) const
+{
+  return !IsEqualTo(b);
+}
 
 /** Sums vector \a to this lhs component-wise.
@@ -583,8 +431,8 @@
  * \return lhs + a
  */
-Vector& operator+=(Vector& a, const Vector& b)
-{
-  a.AddVector(&b);
-  return a;
+const Vector& Vector::operator+=(const Vector& b)
+{
+  this->AddVector(b);
+  return *this;
 };
 
@@ -594,8 +442,8 @@
  * \return lhs - a
  */
-Vector& operator-=(Vector& a, const Vector& b)
-{
-  a.SubtractVector(&b);
-  return a;
+const Vector& Vector::operator-=(const Vector& b)
+{
+  this->SubtractVector(b);
+  return *this;
 };
 
@@ -605,5 +453,5 @@
  * \return lhs.x[i] * m
  */
-Vector& operator*=(Vector& a, const double m)
+const Vector& operator*=(Vector& a, const double m)
 {
   a.Scale(m);
@@ -616,10 +464,9 @@
  * \return a + b
  */
-Vector& operator+(const Vector& a, const Vector& b)
-{
-  Vector *x = new Vector;
-  x->CopyVector(&a);
-  x->AddVector(&b);
-  return *x;
+Vector const Vector::operator+(const Vector& b) const
+{
+  Vector x = *this;
+  x.AddVector(b);
+  return x;
 };
 
@@ -629,10 +476,9 @@
  * \return a - b
  */
-Vector& operator-(const Vector& a, const Vector& b)
-{
-  Vector *x = new Vector;
-  x->CopyVector(&a);
-  x->SubtractVector(&b);
-  return *x;
+Vector const Vector::operator-(const Vector& b) const
+{
+  Vector x = *this;
+  x.SubtractVector(b);
+  return x;
 };
 
@@ -642,10 +488,9 @@
  * \return m * a
  */
-Vector& operator*(const Vector& a, const double m)
-{
-  Vector *x = new Vector;
-  x->CopyVector(&a);
-  x->Scale(m);
-  return *x;
+Vector const operator*(const Vector& a, const double m)
+{
+  Vector x(a);
+  x.Scale(m);
+  return x;
 };
 
@@ -655,29 +500,9 @@
  * \return m * a
  */
-Vector& operator*(const double m, const Vector& a )
-{
-  Vector *x = new Vector;
-  x->CopyVector(&a);
-  x->Scale(m);
-  return *x;
-};
-
-Vector& Vector::operator=(const Vector& src) {
-  CopyVector(src);
-  return *this;
-}
-
-/** Prints a 3dim vector.
- * prints no end of line.
- */
-void Vector::Output() const
-{
-  Log() << Verbose(0) << "(";
-  for (int i=0;i<NDIM;i++) {
-    Log() << Verbose(0) << x[i];
-    if (i != 2)
-      Log() << Verbose(0) << ",";
-  }
-  Log() << Verbose(0) << ")";
+Vector const operator*(const double m, const Vector& a )
+{
+  Vector x(a);
+  x.Scale(m);
+  return x;
 };
 
@@ -686,5 +511,5 @@
   ost << "(";
   for (int i=0;i<NDIM;i++) {
-    ost << m.x[i];
+    ost << m[i];
     if (i != 2)
       ost << ",";
@@ -694,18 +519,12 @@
 };
 
-/** Scales each atom coordinate by an individual \a factor.
- * \param *factor pointer to scaling factor
- */
-void Vector::Scale(const double ** const factor)
+
+void Vector::ScaleAll(const double *factor)
 {
   for (int i=NDIM;i--;)
-    x[i] *= (*factor)[i];
-};
-
-void Vector::Scale(const double * const factor)
-{
-  for (int i=NDIM;i--;)
-    x[i] *= *factor;
-};
+    x[i] *= factor[i];
+};
+
+
 
 void Vector::Scale(const double factor)
@@ -713,13 +532,4 @@
   for (int i=NDIM;i--;)
     x[i] *= factor;
-};
-
-/** Translate atom by given vector.
- * \param trans[] translation vector.
- */
-void Vector::Translate(const Vector * const trans)
-{
-  for (int i=NDIM;i--;)
-    x[i] += trans->x[i];
 };
 
@@ -747,12 +557,8 @@
 void Vector::MatrixMultiplication(const double * const M)
 {
-  Vector C;
   // do the matrix multiplication
-  C.x[0] = M[0]*x[0]+M[3]*x[1]+M[6]*x[2];
-  C.x[1] = M[1]*x[0]+M[4]*x[1]+M[7]*x[2];
-  C.x[2] = M[2]*x[0]+M[5]*x[1]+M[8]*x[2];
-  // transfer the result into this
-  for (int i=NDIM;i--;)
-    x[i] = C.x[i];
+  at(0) = M[0]*x[0]+M[3]*x[1]+M[6]*x[2];
+  at(1) = M[1]*x[0]+M[4]*x[1]+M[7]*x[2];
+  at(2) = M[2]*x[0]+M[5]*x[1]+M[8]*x[2];
 };
 
@@ -760,7 +566,6 @@
  * \param *matrix NDIM_NDIM array
  */
-void Vector::InverseMatrixMultiplication(const double * const A)
-{
-  Vector C;
+bool Vector::InverseMatrixMultiplication(const double * const A)
+{
   double B[NDIM*NDIM];
   double detA = RDET3(A);
@@ -781,12 +586,11 @@
 
     // do the matrix multiplication
-    C.x[0] = B[0]*x[0]+B[3]*x[1]+B[6]*x[2];
-    C.x[1] = B[1]*x[0]+B[4]*x[1]+B[7]*x[2];
-    C.x[2] = B[2]*x[0]+B[5]*x[1]+B[8]*x[2];
-    // transfer the result into this
-    for (int i=NDIM;i--;)
-      x[i] = C.x[i];
+    at(0) = B[0]*x[0]+B[3]*x[1]+B[6]*x[2];
+    at(1) = B[1]*x[0]+B[4]*x[1]+B[7]*x[2];
+    at(2) = B[2]*x[0]+B[5]*x[1]+B[8]*x[2];
+
+    return true;
   } else {
-    eLog() << Verbose(1) << "inverse of matrix does not exists: det A = " << detA << "." << endl;
+    return false;
   }
 };
@@ -800,8 +604,9 @@
  * \param *factors three-component vector with the factor for each given vector
  */
-void Vector::LinearCombinationOfVectors(const Vector * const x1, const Vector * const x2, const Vector * const x3, const double * const factors)
-{
-  for(int i=NDIM;i--;)
-    x[i] = factors[0]*x1->x[i] + factors[1]*x2->x[i] + factors[2]*x3->x[i];
+void Vector::LinearCombinationOfVectors(const Vector &x1, const Vector &x2, const Vector &x3, const double * const factors)
+{
+  (*this) = (factors[0]*x1) +
+            (factors[1]*x2) +
+            (factors[2]*x3);
 };
 
@@ -809,85 +614,11 @@
  * \param n[] normal vector of mirror plane.
  */
-void Vector::Mirror(const Vector * const n)
+void Vector::Mirror(const Vector &n)
 {
   double projection;
-  projection = ScalarProduct(n)/n->ScalarProduct(n);    // remove constancy from n (keep as logical one)
+  projection = ScalarProduct(n)/n.NormSquared();    // remove constancy from n (keep as logical one)
   // withdraw projected vector twice from original one
-  Log() << Verbose(1) << "Vector: ";
-  Output();
-  Log() << Verbose(0) << "\t";
   for (int i=NDIM;i--;)
-    x[i] -= 2.*projection*n->x[i];
-  Log() << Verbose(0) << "Projected vector: ";
-  Output();
-  Log() << Verbose(0) << endl;
-};
-
-/** Calculates normal vector for three given vectors (being three points in space).
- * Makes this vector orthonormal to the three given points, making up a place in 3d space.
- * \param *y1 first vector
- * \param *y2 second vector
- * \param *y3 third vector
- * \return true - success, vectors are linear independent, false - failure due to linear dependency
- */
-bool Vector::MakeNormalVector(const Vector * const y1, const Vector * const y2, const Vector * const y3)
-{
-  Vector x1, x2;
-
-  x1.CopyVector(y1);
-  x1.SubtractVector(y2);
-  x2.CopyVector(y3);
-  x2.SubtractVector(y2);
-  if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
-    eLog() << Verbose(2) << "Given vectors are linear dependent." << endl;
-    return false;
-  }
-//  Log() << Verbose(4) << "relative, first plane coordinates:";
-//  x1.Output((ofstream *)&cout);
-//  Log() << Verbose(0) << endl;
-//  Log() << Verbose(4) << "second plane coordinates:";
-//  x2.Output((ofstream *)&cout);
-//  Log() << Verbose(0) << endl;
-
-  this->x[0] = (x1.x[1]*x2.x[2] - x1.x[2]*x2.x[1]);
-  this->x[1] = (x1.x[2]*x2.x[0] - x1.x[0]*x2.x[2]);
-  this->x[2] = (x1.x[0]*x2.x[1] - x1.x[1]*x2.x[0]);
-  Normalize();
-
-  return true;
-};
-
-
-/** Calculates orthonormal vector to two given vectors.
- * Makes this vector orthonormal to two given vectors. This is very similar to the other
- * vector::MakeNormalVector(), only there three points whereas here two difference
- * vectors are given.
- * \param *x1 first vector
- * \param *x2 second vector
- * \return true - success, vectors are linear independent, false - failure due to linear dependency
- */
-bool Vector::MakeNormalVector(const Vector * const y1, const Vector * const y2)
-{
-  Vector x1,x2;
-  x1.CopyVector(y1);
-  x2.CopyVector(y2);
-  Zero();
-  if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
-    eLog() << Verbose(2) << "Given vectors are linear dependent." << endl;
-    return false;
-  }
-//  Log() << Verbose(4) << "relative, first plane coordinates:";
-//  x1.Output((ofstream *)&cout);
-//  Log() << Verbose(0) << endl;
-//  Log() << Verbose(4) << "second plane coordinates:";
-//  x2.Output((ofstream *)&cout);
-//  Log() << Verbose(0) << endl;
-
-  this->x[0] = (x1.x[1]*x2.x[2] - x1.x[2]*x2.x[1]);
-  this->x[1] = (x1.x[2]*x2.x[0] - x1.x[0]*x2.x[2]);
-  this->x[2] = (x1.x[0]*x2.x[1] - x1.x[1]*x2.x[0]);
-  Normalize();
-
-  return true;
+    at(i) -= 2.*projection*n[i];
 };
 
@@ -898,12 +629,11 @@
  * \return true - success, false - vector is zero
  */
-bool Vector::MakeNormalVector(const Vector * const y1)
+bool Vector::MakeNormalTo(const Vector &y1)
 {
   bool result = false;
-  double factor = y1->ScalarProduct(this)/y1->NormSquared();
+  double factor = y1.ScalarProduct(*this)/y1.NormSquared();
   Vector x1;
-  x1.CopyVector(y1);
-  x1.Scale(factor);
-  SubtractVector(&x1);
+  x1 = factor * y1;
+  SubtractVector(x1);
   for (int i=NDIM;i--;)
     result = result || (fabs(x[i]) > MYEPSILON);
@@ -918,5 +648,5 @@
  * \return true - success, false - failure (null vector given)
  */
-bool Vector::GetOneNormalVector(const Vector * const GivenVector)
+bool Vector::GetOneNormalVector(const Vector &GivenVector)
 {
   int Components[NDIM]; // contains indices of non-zero components
@@ -925,30 +655,35 @@
   double norm;
 
-  Log() << Verbose(4);
-  GivenVector->Output();
-  Log() << Verbose(0) << endl;
   for (j=NDIM;j--;)
     Components[j] = -1;
+
+  // in two component-systems we need to find the one position that is zero
+  int zeroPos = -1;
   // find two components != 0
-  for (j=0;j<NDIM;j++)
-    if (fabs(GivenVector->x[j]) > MYEPSILON)
+  for (j=0;j<NDIM;j++){
+    if (fabs(GivenVector[j]) > MYEPSILON)
       Components[Last++] = j;
-  Log() << Verbose(4) << Last << " Components != 0: (" << Components[0] << "," << Components[1] << "," << Components[2] << ")" << endl;
+    else
+      // this our zero Position
+      zeroPos = j;
+  }
 
   switch(Last) {
     case 3:  // threecomponent system
+      // the position of the zero is arbitrary in three component systems
+      zeroPos = Components[2];
     case 2:  // two component system
-      norm = sqrt(1./(GivenVector->x[Components[1]]*GivenVector->x[Components[1]]) + 1./(GivenVector->x[Components[0]]*GivenVector->x[Components[0]]));
-      x[Components[2]] = 0.;
+      norm = sqrt(1./(GivenVector[Components[1]]*GivenVector[Components[1]]) + 1./(GivenVector[Components[0]]*GivenVector[Components[0]]));
+      at(zeroPos) = 0.;
       // in skp both remaining parts shall become zero but with opposite sign and third is zero
-      x[Components[1]] = -1./GivenVector->x[Components[1]] / norm;
-      x[Components[0]] = 1./GivenVector->x[Components[0]] / norm;
+      at(Components[1]) = -1./GivenVector[Components[1]] / norm;
+      at(Components[0]) = 1./GivenVector[Components[0]] / norm;
       return true;
       break;
     case 1: // one component system
       // set sole non-zero component to 0, and one of the other zero component pendants to 1
-      x[(Components[0]+2)%NDIM] = 0.;
-      x[(Components[0]+1)%NDIM] = 1.;
-      x[Components[0]] = 0.;
+      at((Components[0]+2)%NDIM) = 0.;
+      at((Components[0]+1)%NDIM) = 1.;
+      at(Components[0]) = 0.;
       return true;
       break;
@@ -958,111 +693,11 @@
 };
 
-/** Determines parameter needed to multiply this vector to obtain intersection point with plane defined by \a *A, \a *B and \a *C.
- * \param *A first plane vector
- * \param *B second plane vector
- * \param *C third plane vector
- * \return scaling parameter for this vector
- */
-double Vector::CutsPlaneAt(const Vector * const A, const Vector * const B, const Vector * const C) const
-{
-//  Log() << Verbose(3) << "For comparison: ";
-//  Log() << Verbose(0) << "A " << A->Projection(this) << "\t";
-//  Log() << Verbose(0) << "B " << B->Projection(this) << "\t";
-//  Log() << Verbose(0) << "C " << C->Projection(this) << "\t";
-//  Log() << Verbose(0) << endl;
-  return A->ScalarProduct(this);
-};
-
-/** Creates a new vector as the one with least square distance to a given set of \a vectors.
- * \param *vectors set of vectors
- * \param num number of vectors
- * \return true if success, false if failed due to linear dependency
- */
-bool Vector::LSQdistance(const Vector **vectors, int num)
-{
-  int j;
-
-  for (j=0;j<num;j++) {
-    Log() << Verbose(1) << j << "th atom's vector: ";
-    (vectors[j])->Output();
-    Log() << Verbose(0) << endl;
-  }
-
-  int np = 3;
-  struct LSQ_params par;
-
-   const gsl_multimin_fminimizer_type *T =
-     gsl_multimin_fminimizer_nmsimplex;
-   gsl_multimin_fminimizer *s = NULL;
-   gsl_vector *ss, *y;
-   gsl_multimin_function minex_func;
-
-   size_t iter = 0, i;
-   int status;
-   double size;
-
-   /* Initial vertex size vector */
-   ss = gsl_vector_alloc (np);
-   y = gsl_vector_alloc (np);
-
-   /* Set all step sizes to 1 */
-   gsl_vector_set_all (ss, 1.0);
-
-   /* Starting point */
-   par.vectors = vectors;
-   par.num = num;
-
-   for (i=NDIM;i--;)
-    gsl_vector_set(y, i, (vectors[0]->x[i] - vectors[1]->x[i])/2.);
-
-   /* Initialize method and iterate */
-   minex_func.f = &LSQ;
-   minex_func.n = np;
-   minex_func.params = (void *)&par;
-
-   s = gsl_multimin_fminimizer_alloc (T, np);
-   gsl_multimin_fminimizer_set (s, &minex_func, y, ss);
-
-   do
-     {
-       iter++;
-       status = gsl_multimin_fminimizer_iterate(s);
-
-       if (status)
-         break;
-
-       size = gsl_multimin_fminimizer_size (s);
-       status = gsl_multimin_test_size (size, 1e-2);
-
-       if (status == GSL_SUCCESS)
-         {
-           printf ("converged to minimum at\n");
-         }
-
-       printf ("%5d ", (int)iter);
-       for (i = 0; i < (size_t)np; i++)
-         {
-           printf ("%10.3e ", gsl_vector_get (s->x, i));
-         }
-       printf ("f() = %7.3f size = %.3f\n", s->fval, size);
-     }
-   while (status == GSL_CONTINUE && iter < 100);
-
-  for (i=(size_t)np;i--;)
-    this->x[i] = gsl_vector_get(s->x, i);
-   gsl_vector_free(y);
-   gsl_vector_free(ss);
-   gsl_multimin_fminimizer_free (s);
-
-  return true;
-};
-
 /** Adds vector \a *y componentwise.
  * \param *y vector
  */
-void Vector::AddVector(const Vector * const y)
-{
-  for (int i=NDIM;i--;)
-    this->x[i] += y->x[i];
+void Vector::AddVector(const Vector &y)
+{
+  for(int i=NDIM;i--;)
+    x[i] += y[i];
 }
 
@@ -1070,222 +705,9 @@
  * \param *y vector
  */
-void Vector::SubtractVector(const Vector * const y)
-{
-  for (int i=NDIM;i--;)
-    this->x[i] -= y->x[i];
-}
-
-/** Copy vector \a *y componentwise.
- * \param *y vector
- */
-void Vector::CopyVector(const Vector * const y)
-{
-  // check for self assignment
-  if(y!=this){
-    for (int i=NDIM;i--;)
-      this->x[i] = y->x[i];
-  }
-}
-
-/** Copy vector \a y componentwise.
- * \param y vector
- */
-void Vector::CopyVector(const Vector &y)
-{
-  // check for self assignment
-  if(&y!=this) {
-    for (int i=NDIM;i--;)
-      this->x[i] = y.x[i];
-  }
-}
-
-
-/** Asks for position, checks for boundary.
- * \param cell_size unitary size of cubic cell, coordinates must be within 0...cell_size
- * \param check whether bounds shall be checked (true) or not (false)
- */
-void Vector::AskPosition(const double * const cell_size, const bool check)
-{
-  char coords[3] = {'x','y','z'};
-  int j = -1;
-  for (int i=0;i<3;i++) {
-    j += i+1;
-    do {
-      Log() << Verbose(0) << coords[i] << "[0.." << cell_size[j] << "]: ";
-      cin >> x[i];
-    } while (((x[i] < 0) || (x[i] >= cell_size[j])) && (check));
-  }
-};
-
-/** Solves a vectorial system consisting of two orthogonal statements and a norm statement.
- * This is linear system of equations to be solved, however of the three given (skp of this vector\
- * with either of the three hast to be zero) only two are linear independent. The third equation
- * is that the vector should be of magnitude 1 (orthonormal). This all leads to a case-based solution
- * where very often it has to be checked whether a certain value is zero or not and thus forked into
- * another case.
- * \param *x1 first vector
- * \param *x2 second vector
- * \param *y third vector
- * \param alpha first angle
- * \param beta second angle
- * \param c norm of final vector
- * \return a vector with \f$\langle x1,x2 \rangle=A\f$, \f$\langle x1,y \rangle = B\f$ and with norm \a c.
- * \bug this is not yet working properly
- */
-bool Vector::SolveSystem(Vector * x1, Vector * x2, Vector * y, const double alpha, const double beta, const double c)
-{
-  double D1,D2,D3,E1,E2,F1,F2,F3,p,q=0., A, B1, B2, C;
-  double ang; // angle on testing
-  double sign[3];
-  int i,j,k;
-  A = cos(alpha) * x1->Norm() * c;
-  B1 = cos(beta + M_PI/2.) * y->Norm() * c;
-  B2 = cos(beta) * x2->Norm() * c;
-  C = c * c;
-  Log() << Verbose(2) << "A " << A << "\tB " << B1 << "\tC " << C << endl;
-  int flag = 0;
-  if (fabs(x1->x[0]) < MYEPSILON) { // check for zero components for the later flipping and back-flipping
-    if (fabs(x1->x[1]) > MYEPSILON) {
-      flag = 1;
-    } else if (fabs(x1->x[2]) > MYEPSILON) {
-       flag = 2;
-    } else {
-      return false;
-    }
-  }
-  switch (flag) {
-    default:
-    case 0:
-      break;
-    case 2:
-      flip(x1->x[0],x1->x[1]);
-      flip(x2->x[0],x2->x[1]);
-      flip(y->x[0],y->x[1]);
-      //flip(x[0],x[1]);
-      flip(x1->x[1],x1->x[2]);
-      flip(x2->x[1],x2->x[2]);
-      flip(y->x[1],y->x[2]);
-      //flip(x[1],x[2]);
-    case 1:
-      flip(x1->x[0],x1->x[1]);
-      flip(x2->x[0],x2->x[1]);
-      flip(y->x[0],y->x[1]);
-      //flip(x[0],x[1]);
-      flip(x1->x[1],x1->x[2]);
-      flip(x2->x[1],x2->x[2]);
-      flip(y->x[1],y->x[2]);
-      //flip(x[1],x[2]);
-      break;
-  }
-  // now comes the case system
-  D1 = -y->x[0]/x1->x[0]*x1->x[1]+y->x[1];
-  D2 = -y->x[0]/x1->x[0]*x1->x[2]+y->x[2];
-  D3 = y->x[0]/x1->x[0]*A-B1;
-  Log() << Verbose(2) << "D1 " << D1 << "\tD2 " << D2 << "\tD3 " << D3 << "\n";
-  if (fabs(D1) < MYEPSILON) {
-    Log() << Verbose(2) << "D1 == 0!\n";
-    if (fabs(D2) > MYEPSILON) {
-      Log() << Verbose(3) << "D2 != 0!\n";
-      x[2] = -D3/D2;
-      E1 = A/x1->x[0] + x1->x[2]/x1->x[0]*D3/D2;
-      E2 = -x1->x[1]/x1->x[0];
-      Log() << Verbose(3) << "E1 " << E1 << "\tE2 " << E2 << "\n";
-      F1 = E1*E1 + 1.;
-      F2 = -E1*E2;
-      F3 = E1*E1 + D3*D3/(D2*D2) - C;
-      Log() << Verbose(3) << "F1 " << F1 << "\tF2 " << F2 << "\tF3 " << F3 << "\n";
-      if (fabs(F1) < MYEPSILON) {
-        Log() << Verbose(4) << "F1 == 0!\n";
-        Log() << Verbose(4) << "Gleichungssystem linear\n";
-        x[1] = F3/(2.*F2);
-      } else {
-        p = F2/F1;
-        q = p*p - F3/F1;
-        Log() << Verbose(4) << "p " << p << "\tq " << q << endl;
-        if (q < 0) {
-          Log() << Verbose(4) << "q < 0" << endl;
-          return false;
-        }
-        x[1] = p + sqrt(q);
-      }
-      x[0] =  A/x1->x[0] - x1->x[1]/x1->x[0]*x[1] + x1->x[2]/x1->x[0]*x[2];
-    } else {
-      Log() << Verbose(2) << "Gleichungssystem unterbestimmt\n";
-      return false;
-    }
-  } else {
-    E1 = A/x1->x[0]+x1->x[1]/x1->x[0]*D3/D1;
-    E2 = x1->x[1]/x1->x[0]*D2/D1 - x1->x[2];
-    Log() << Verbose(2) << "E1 " << E1 << "\tE2 " << E2 << "\n";
-    F1 = E2*E2 + D2*D2/(D1*D1) + 1.;
-    F2 = -(E1*E2 + D2*D3/(D1*D1));
-    F3 = E1*E1 + D3*D3/(D1*D1) - C;
-    Log() << Verbose(2) << "F1 " << F1 << "\tF2 " << F2 << "\tF3 " << F3 << "\n";
-    if (fabs(F1) < MYEPSILON) {
-      Log() << Verbose(3) << "F1 == 0!\n";
-      Log() << Verbose(3) << "Gleichungssystem linear\n";
-      x[2] = F3/(2.*F2);
-    } else {
-      p = F2/F1;
-      q = p*p - F3/F1;
-      Log() << Verbose(3) << "p " << p << "\tq " << q << endl;
-      if (q < 0) {
-        Log() << Verbose(3) << "q < 0" << endl;
-        return false;
-      }
-      x[2] = p + sqrt(q);
-    }
-    x[1] = (-D2 * x[2] - D3)/D1;
-    x[0] = A/x1->x[0] - x1->x[1]/x1->x[0]*x[1] + x1->x[2]/x1->x[0]*x[2];
-  }
-  switch (flag) { // back-flipping
-    default:
-    case 0:
-      break;
-    case 2:
-      flip(x1->x[0],x1->x[1]);
-      flip(x2->x[0],x2->x[1]);
-      flip(y->x[0],y->x[1]);
-      flip(x[0],x[1]);
-      flip(x1->x[1],x1->x[2]);
-      flip(x2->x[1],x2->x[2]);
-      flip(y->x[1],y->x[2]);
-      flip(x[1],x[2]);
-    case 1:
-      flip(x1->x[0],x1->x[1]);
-      flip(x2->x[0],x2->x[1]);
-      flip(y->x[0],y->x[1]);
-      //flip(x[0],x[1]);
-      flip(x1->x[1],x1->x[2]);
-      flip(x2->x[1],x2->x[2]);
-      flip(y->x[1],y->x[2]);
-      flip(x[1],x[2]);
-      break;
-  }
-  // one z component is only determined by its radius (without sign)
-  // thus check eight possible sign flips and determine by checking angle with second vector
-  for (i=0;i<8;i++) {
-    // set sign vector accordingly
-    for (j=2;j>=0;j--) {
-      k = (i & pot(2,j)) << j;
-      Log() << Verbose(2) << "k " << k << "\tpot(2,j) " << pot(2,j) << endl;
-      sign[j] = (k == 0) ? 1. : -1.;
-    }
-    Log() << Verbose(2) << i << ": sign matrix is " << sign[0] << "\t" << sign[1] << "\t" << sign[2] << "\n";
-    // apply sign matrix
-    for (j=NDIM;j--;)
-      x[j] *= sign[j];
-    // calculate angle and check
-    ang = x2->Angle (this);
-    Log() << Verbose(1) << i << "th angle " << ang << "\tbeta " << cos(beta) << " :\t";
-    if (fabs(ang - cos(beta)) < MYEPSILON) {
-      break;
-    }
-    // unapply sign matrix (is its own inverse)
-    for (j=NDIM;j--;)
-      x[j] *= sign[j];
-  }
-  return true;
-};
+void Vector::SubtractVector(const Vector &y)
+{
+  for(int i=NDIM;i--;)
+    x[i] -= y[i];
+}
 
 /**
@@ -1298,13 +720,18 @@
 bool Vector::IsInParallelepiped(const Vector &offset, const double * const parallelepiped) const
 {
-  Vector a;
-  a.CopyVector(this);
-  a.SubtractVector(&offset);
+  Vector a = (*this)-offset;
   a.InverseMatrixMultiplication(parallelepiped);
   bool isInside = true;
 
   for (int i=NDIM;i--;)
-    isInside = isInside && ((a.x[i] <= 1) && (a.x[i] >= 0));
+    isInside = isInside && ((a[i] <= 1) && (a[i] >= 0));
 
   return isInside;
 }
+
+
+// some comonly used vectors
+const Vector zeroVec(0,0,0);
+const Vector e1(1,0,0);
+const Vector e2(0,1,0);
+const Vector e3(0,0,1);
Index: src/vector.hpp
===================================================================
--- src/vector.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/vector.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -15,5 +15,8 @@
 #include <gsl/gsl_multimin.h>
 
+#include <memory>
+
 #include "defs.hpp"
+#include "Space.hpp"
 
 /********************************************** declarations *******************************/
@@ -22,76 +25,95 @@
  * basically, just a x[3] but with helpful functions
  */
-class Vector {
-  public:
-    double x[NDIM];
+class Vector : public Space{
+protected:
+  // this struct is used to indicate calls to the Baseconstructor from inside vectors.
+  struct Baseconstructor{};
+public:
 
   Vector();
   Vector(const double x1, const double x2, const double x3);
-  ~Vector();
+  Vector(const Vector& src);
+  virtual ~Vector();
 
-  double Distance(const Vector * const y) const;
-  double DistanceSquared(const Vector * const y) const;
-  double DistanceToPlane(const Vector * const PlaneNormal, const Vector * const PlaneOffset) const;
-  double PeriodicDistance(const Vector * const y, const double * const cell_size) const;
-  double PeriodicDistanceSquared(const Vector * const y, const double * const cell_size) const;
-  double ScalarProduct(const Vector * const y) const;
-  double Norm() const;
-  double NormSquared() const;
-  double Angle(const Vector * const y) const;
+  // Method implemented by forwarding to the Representation
+
+  double DistanceSquared(const Vector &y) const;
+  Vector GetDistanceVectorToPlane(const Vector &PlaneNormal, const Vector &PlaneOffset) const;
+  double DistanceToPlane(const Vector &PlaneNormal, const Vector &PlaneOffset) const;
+  double PeriodicDistance(const Vector &y, const double * const cell_size) const;
+  double PeriodicDistanceSquared(const Vector &y, const double * const cell_size) const;
+  double ScalarProduct(const Vector &y) const;
+  double Angle(const Vector &y) const;
   bool IsZero() const;
   bool IsOne() const;
-  bool IsNormalTo(const Vector * const normal) const;
-  bool IsEqualTo(const Vector * const a) const;
+  bool IsNormalTo(const Vector &normal) const;
+  bool IsEqualTo(const Vector &a) const;
 
-  void AddVector(const Vector * const y);
-  void SubtractVector(const Vector * const y);
-  void CopyVector(const Vector * const y);
-  void CopyVector(const Vector &y);
-  void RotateVector(const Vector * const y, const double alpha);
-  void VectorProduct(const Vector * const y);
-  void ProjectOntoPlane(const Vector * const y);
-  void ProjectIt(const Vector * const y);
-  Vector Projection(const Vector * const y) const;
-  void Zero();
-  void One(const double one);
-  void Init(const double x1, const double x2, const double x3);
-  void Normalize();
-  void Translate(const Vector * const x);
-  void Mirror(const Vector * const x);
-  void Scale(const double ** const factor);
-  void Scale(const double * const factor);
+  void AddVector(const Vector &y);
+  void SubtractVector(const Vector &y);
+  void VectorProduct(const Vector &y);
+  void ProjectOntoPlane(const Vector &y);
+  void ProjectIt(const Vector &y);
+  Vector Projection(const Vector &y) const;
+  void Mirror(const Vector &x);
+  void ScaleAll(const double *factor);
   void Scale(const double factor);
   void MatrixMultiplication(const double * const M);
-  void InverseMatrixMultiplication(const double * const M);
+  bool InverseMatrixMultiplication(const double * const M);
   void KeepPeriodic(const double * const matrix);
-  void LinearCombinationOfVectors(const Vector * const x1, const Vector * const x2, const Vector * const x3, const double * const factors);
-  double CutsPlaneAt(const Vector * const A, const Vector * const B, const Vector * const C) const;
-  bool GetIntersectionWithPlane(const Vector * const PlaneNormal, const Vector * const PlaneOffset, const Vector * const Origin, const Vector * const LineVector);
-  bool GetIntersectionOfTwoLinesOnPlane(const Vector * const Line1a, const Vector * const Line1b, const Vector * const Line2a, const Vector * const Line2b, const Vector *Normal = NULL);
-  bool GetOneNormalVector(const Vector * const x1);
-  bool MakeNormalVector(const Vector * const y1);
-  bool MakeNormalVector(const Vector * const y1, const Vector * const y2);
-  bool MakeNormalVector(const Vector * const x1, const Vector * const x2, const Vector * const x3);
-  bool SolveSystem(Vector * x1, Vector * x2, Vector * y, const double alpha, const double beta, const double c);
-  bool LSQdistance(const Vector ** vectors, int dim);
-  void AskPosition(const double * const cell_size, const bool check);
-  void Output() const;
+  bool GetOneNormalVector(const Vector &x1);
+  bool MakeNormalTo(const Vector &y1);
   bool IsInParallelepiped(const Vector &offset, const double * const parallelepiped) const;
   void WrapPeriodically(const double * const M, const double * const Minv);
 
-  Vector& operator=(const Vector &src);
+  // Accessors ussually come in pairs... and sometimes even more than that
+  double& operator[](size_t i);
+  const double& operator[](size_t i) const;
+  double& at(size_t i);
+  const double& at(size_t i) const;
+
+  // Assignment operator
+  Vector &operator=(const Vector& src);
+
+  // Access to internal structure
+  double* get();
+
+  // Methods that are derived directly from other methods
+  double Norm() const;
+  double NormSquared() const;
+  void Normalize();
+  void Zero();
+  void One(const double one);
+  void LinearCombinationOfVectors(const Vector &x1, const Vector &x2, const Vector &x3, const double * const factors);
+
+  // operators for mathematical operations
+  bool operator==(const Vector& b) const;
+  bool operator!=(const Vector& b) const;
+  const Vector& operator+=(const Vector& b);
+  const Vector& operator-=(const Vector& b);
+  Vector const operator+(const Vector& b) const;
+  Vector const operator-(const Vector& b) const;
+
+  // Methods inherited from Space
+  virtual double distance(const Vector &point) const;
+  virtual Vector getClosestPoint(const Vector &point) const;
+
+protected:
+
+private:
+  double x[NDIM];
 
 };
 
+// some commonly used and fixed vectors
+const extern Vector zeroVec;
+const extern Vector e1;
+const extern Vector e2;
+const extern Vector e3;
+
 ostream & operator << (ostream& ost, const Vector &m);
-bool operator==(const Vector& a, const Vector& b);
-Vector& operator+=(Vector& a, const Vector& b);
-Vector& operator-=(Vector& a, const Vector& b);
-Vector& operator*=(Vector& a, const double m);
-Vector& operator*(const Vector& a, const double m);
-Vector& operator*(const double m, const Vector& a);
-Vector& operator+(const Vector& a, const Vector& b);
-Vector& operator-(const Vector& a, const Vector& b);
-
+const Vector& operator*=(Vector& a, const double m);
+Vector const operator*(const Vector& a, const double m);
+Vector const operator*(const double m, const Vector& a);
 
 #endif /*VECTOR_HPP_*/
Index: src/vector_ops.cpp
===================================================================
--- src/vector_ops.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/vector_ops.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,241 @@
+/*
+ * vector_ops.cpp
+ *
+ *  Created on: Apr 1, 2010
+ *      Author: crueger
+ */
+
+#include "vector.hpp"
+#include "Plane.hpp"
+#include "log.hpp"
+#include "verbose.hpp"
+#include "gslmatrix.hpp"
+#include "leastsquaremin.hpp"
+#include "info.hpp"
+#include "Helpers/fast_functions.hpp"
+#include "Exceptions/LinearDependenceException.hpp"
+
+#include <gsl/gsl_linalg.h>
+#include <gsl/gsl_matrix.h>
+#include <gsl/gsl_permutation.h>
+#include <gsl/gsl_vector.h>
+
+/**
+ * !@file
+ * These files defines several common operation on vectors that should not
+ * become part of the main vector class, because they are either to complex
+ * or need methods from other subsystems that should not be moved to
+ * the LinAlg-Subsystem
+ */
+
+/** Creates a new vector as the one with least square distance to a given set of \a vectors.
+ * \param *vectors set of vectors
+ * \param num number of vectors
+ * \return true if success, false if failed due to linear dependency
+ */
+bool LSQdistance(Vector &res,const Vector **vectors, int num)
+{
+  int j;
+
+  for (j=0;j<num;j++) {
+    Log() << Verbose(1) << j << "th atom's vector: " << vectors[j] << endl;
+  }
+
+  int np = 3;
+  struct LSQ_params par;
+
+   const gsl_multimin_fminimizer_type *T =
+     gsl_multimin_fminimizer_nmsimplex;
+   gsl_multimin_fminimizer *s = NULL;
+   gsl_vector *ss, *y;
+   gsl_multimin_function minex_func;
+
+   size_t iter = 0, i;
+   int status;
+   double size;
+
+   /* Initial vertex size vector */
+   ss = gsl_vector_alloc (np);
+   y = gsl_vector_alloc (np);
+
+   /* Set all step sizes to 1 */
+   gsl_vector_set_all (ss, 1.0);
+
+   /* Starting point */
+   par.vectors = vectors;
+   par.num = num;
+
+   for (i=NDIM;i--;)
+    gsl_vector_set(y, i, (vectors[0]->at(i) - vectors[1]->at(i))/2.);
+
+   /* Initialize method and iterate */
+   minex_func.f = &LSQ;
+   minex_func.n = np;
+   minex_func.params = (void *)&par;
+
+   s = gsl_multimin_fminimizer_alloc (T, np);
+   gsl_multimin_fminimizer_set (s, &minex_func, y, ss);
+
+   do
+     {
+       iter++;
+       status = gsl_multimin_fminimizer_iterate(s);
+
+       if (status)
+         break;
+
+       size = gsl_multimin_fminimizer_size (s);
+       status = gsl_multimin_test_size (size, 1e-2);
+
+       if (status == GSL_SUCCESS)
+         {
+           printf ("converged to minimum at\n");
+         }
+
+       printf ("%5d ", (int)iter);
+       for (i = 0; i < (size_t)np; i++)
+         {
+           printf ("%10.3e ", gsl_vector_get (s->x, i));
+         }
+       printf ("f() = %7.3f size = %.3f\n", s->fval, size);
+     }
+   while (status == GSL_CONTINUE && iter < 100);
+
+  for (i=(size_t)np;i--;)
+    res[i] = gsl_vector_get(s->x, i);
+   gsl_vector_free(y);
+   gsl_vector_free(ss);
+   gsl_multimin_fminimizer_free (s);
+
+  return true;
+};
+
+/** Rotates the vector relative to the origin around the axis given by \a *axis by an angle of \a alpha.
+ * \param *axis rotation axis
+ * \param alpha rotation angle in radian
+ */
+Vector RotateVector(const Vector &vec,const Vector &axis, const double alpha)
+{
+  Vector a,y;
+  Vector res;
+  // normalise this vector with respect to axis
+  a = vec;
+  a.ProjectOntoPlane(axis);
+  // construct normal vector
+  try {
+    y = Plane(axis,a,0).getNormal();
+  }
+  catch (MathException &excp) {
+    // The normal vector cannot be created if there is linar dependency.
+    // Then the vector to rotate is on the axis and any rotation leads to the vector itself.
+    return vec;
+  }
+  y.Scale(vec.Norm());
+  // scale normal vector by sine and this vector by cosine
+  y.Scale(sin(alpha));
+  a.Scale(cos(alpha));
+  res = vec.Projection(axis);
+  // add scaled normal vector onto this vector
+  res += y;
+  // add part in axis direction
+  res += a;
+  return res;
+};
+
+/** Calculates the intersection of the two lines that are both on the same plane.
+ * This is taken from Weisstein, Eric W. "Line-Line Intersection." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/Line-LineIntersection.html
+ * \param *out output stream for debugging
+ * \param *Line1a first vector of first line
+ * \param *Line1b second vector of first line
+ * \param *Line2a first vector of second line
+ * \param *Line2b second vector of second line
+ * \return true - \a this will contain the intersection on return, false - lines are parallel
+ */
+Vector GetIntersectionOfTwoLinesOnPlane(const Vector &Line1a, const Vector &Line1b, const Vector &Line2a, const Vector &Line2b)
+{
+  Info FunctionInfo(__func__);
+
+  Vector res;
+
+  auto_ptr<GSLMatrix> M = auto_ptr<GSLMatrix>(new GSLMatrix(4,4));
+
+  M->SetAll(1.);
+  for (int i=0;i<3;i++) {
+    M->Set(0, i, Line1a[i]);
+    M->Set(1, i, Line1b[i]);
+    M->Set(2, i, Line2a[i]);
+    M->Set(3, i, Line2b[i]);
+  }
+
+  //Log() << Verbose(1) << "Coefficent matrix is:" << endl;
+  //for (int i=0;i<4;i++) {
+  //  for (int j=0;j<4;j++)
+  //    cout << "\t" << M->Get(i,j);
+  //  cout << endl;
+  //}
+  if (fabs(M->Determinant()) > MYEPSILON) {
+    Log() << Verbose(1) << "Determinant of coefficient matrix is NOT zero." << endl;
+    throw LinearDependenceException(__FILE__,__LINE__);
+  }
+
+  Log() << Verbose(1) << "INFO: Line1a = " << Line1a << ", Line1b = " << Line1b << ", Line2a = " << Line2a << ", Line2b = " << Line2b << "." << endl;
+
+
+  // constuct a,b,c
+  Vector a = Line1b - Line1a;
+  Vector b = Line2b - Line2a;
+  Vector c = Line2a - Line1a;
+  Vector d = Line2b - Line1b;
+  Log() << Verbose(1) << "INFO: a = " << a << ", b = " << b << ", c = " << c << "." << endl;
+  if ((a.NormSquared() < MYEPSILON) || (b.NormSquared() < MYEPSILON)) {
+   res.Zero();
+   Log() << Verbose(1) << "At least one of the lines is ill-defined, i.e. offset equals second vector." << endl;
+   throw LinearDependenceException(__FILE__,__LINE__);
+  }
+
+  // check for parallelity
+  Vector parallel;
+  double factor = 0.;
+  if (fabs(a.ScalarProduct(b)*a.ScalarProduct(b)/a.NormSquared()/b.NormSquared() - 1.) < MYEPSILON) {
+    parallel = Line1a - Line2a;
+    factor = parallel.ScalarProduct(a)/a.Norm();
+    if ((factor >= -MYEPSILON) && (factor - 1. < MYEPSILON)) {
+      res = Line2a;
+      Log() << Verbose(1) << "Lines conincide." << endl;
+      return res;
+    } else {
+      parallel = Line1a - Line2b;
+      factor = parallel.ScalarProduct(a)/a.Norm();
+      if ((factor >= -MYEPSILON) && (factor - 1. < MYEPSILON)) {
+        res = Line2b;
+        Log() << Verbose(1) << "Lines conincide." << endl;
+        return res;
+      }
+    }
+    Log() << Verbose(1) << "Lines are parallel." << endl;
+    res.Zero();
+    throw LinearDependenceException(__FILE__,__LINE__);
+  }
+
+  // obtain s
+  double s;
+  Vector temp1, temp2;
+  temp1 = c;
+  temp1.VectorProduct(b);
+  temp2 = a;
+  temp2.VectorProduct(b);
+  Log() << Verbose(1) << "INFO: temp1 = " << temp1 << ", temp2 = " << temp2 << "." << endl;
+  if (fabs(temp2.NormSquared()) > MYEPSILON)
+    s = temp1.ScalarProduct(temp2)/temp2.NormSquared();
+  else
+    s = 0.;
+  Log() << Verbose(1) << "Factor s is " << temp1.ScalarProduct(temp2) << "/" << temp2.NormSquared() << " = " << s << "." << endl;
+
+  // construct intersection
+  res = a;
+  res.Scale(s);
+  res += Line1a;
+  Log() << Verbose(1) << "Intersection is at " << res << "." << endl;
+
+  return res;
+};
Index: src/vector_ops.hpp
===================================================================
--- src/vector_ops.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
+++ src/vector_ops.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -0,0 +1,15 @@
+/*
+ * vector_ops.hpp
+ *
+ *  Created on: Apr 1, 2010
+ *      Author: crueger
+ */
+
+#ifndef VECTOR_OPS_HPP_
+#define VECTOR_OPS_HPP_
+
+bool LSQdistance(Vector &res,const Vector **vectors, int num);
+Vector RotateVector(const Vector &vec,const Vector &axis, const double alpha);
+Vector GetIntersectionOfTwoLinesOnPlane(const Vector &Line1a, const Vector &Line1b, const Vector &Line2a, const Vector &Line2b);
+
+#endif /* VECTOR_OPS_HPP_ */
Index: src/verbose.cpp
===================================================================
--- src/verbose.cpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/verbose.cpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -17,5 +17,5 @@
 
 /** States whether current output message should be print or not.
- * Compares Verbose::Verbosity against \a verbosityLevel.
+ * Compares Verbose::Verbosity plus Info::verbosity against \a verbosityLevel.
  * \param verbosityLevel given global level of verbosity
  * \return true - do output, false - don't
@@ -26,4 +26,13 @@
 };
 
+/** States whether current error output message should be print or not.
+ * Compares Verbose::Verbosity against \a verbosityLevel.
+ * \param verbosityLevel given global level of verbosity
+ * \return true - do output, false - don't
+ */
+bool Verbose::DoErrorOutput(int verbosityLevel) const
+{
+  return (verbosityLevel >= Verbosity);
+};
 
 /** Operator for the Verbose(arg) call.
Index: src/verbose.hpp
===================================================================
--- src/verbose.hpp	(revision cee0a17a1e62832f65ac6bb6775b3263ef3122d0)
+++ src/verbose.hpp	(revision 498c519f5f85d12aba5dc98b7adde3d2c7f45c5b)
@@ -37,4 +37,5 @@
     ostream& print (ostream &ost) const;
     bool DoOutput(int verbosityLevel) const;
+    bool DoErrorOutput(int verbosityLevel) const;
   private:
     int Verbosity;
