Index: src/Makefile.am
===================================================================
--- src/Makefile.am	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/Makefile.am	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -1,22 +1,26 @@
 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
 
-SOURCE = ${ANALYSISSOURCE} ${ATOMSOURCE} bond.cpp bondgraph.cpp boundary.cpp config.cpp element.cpp ellipsoid.cpp errorlogger.cpp graph.cpp helpers.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
-HEADER = ${ANALYSISHEADER} ${ATOMHEADER} bond.hpp bondgraph.hpp boundary.hpp config.hpp defs.hpp element.hpp ellipsoid.hpp errorlogger.hpp graph.hpp helpers.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
+SOURCE = ${ANALYSISSOURCE} ${ATOMSOURCE} 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 triangleintersectionlist.cpp vector.cpp verbose.cpp World.cpp
+HEADER = ${ANALYSISHEADER} ${ATOMHEADER} 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 triangleintersectionlist.cpp vector.hpp verbose.hpp World.hpp
 
 BOOST_LIB = $(BOOST_LDFLAGS) $(BOOST_MPL_LIB)
 INCLUDES = -I$(top_srcdir)/src/unittests
 
-noinst_LIBRARIES = libmolecuilder.a
+noinst_LIBRARIES = libmolecuilder.a libgslwrapper.a
 bin_PROGRAMS = molecuilder joiner analyzer
 molecuilderdir = ${bindir}
 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_LIB)
 molecuilder_SOURCES = builder.cpp
-molecuilder_LDADD = libmolecuilder.a
+molecuilder_LDADD = libmolecuilder.a libgslwrapper.a
 joiner_SOURCES = joiner.cpp datacreator.cpp parser.cpp datacreator.hpp helpers.hpp parser.hpp periodentafel.hpp
 joiner_LDADD = libmolecuilder.a 
@@ -25,2 +29,18 @@
 
 #EXTRA_DIST = ${molecuilder_DATA}
+
+FORCE:
+$(srcdir)/.git-version: FORCE
+	@if (test -d $(top_srcdir)/../.git && cd $(srcdir) && git describe HEAD) > .git-version-t 2>/dev/null \
+	  && ! diff .git-version-t $(srcdir)/.git-version >/dev/null 2>&1; then \
+	  mv -f .git-version-t $(srcdir)/.git-version; \
+	else \
+	  rm -f .git-version-t; \
+	fi
+
+EXTRA_DIST = $(srcdir)/.git-version
+
+$(srcdir)/version.c: $(srcdir)/.git-version
+	echo "const char *ESPACKVersion = \"$(PACKAGE_NAME) -- git version: "`cat $(srcdir)/.git-version`"\";" > $@
+
+molecuilder_SOURCES += $(srcdir)/version.c
Index: src/World.cpp
===================================================================
--- src/World.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/World.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,70 @@
+/*
+ * world.cpp
+ *
+ *  Created on: Mar 3, 2010
+ *      Author: heber
+ */
+
+#include <string.h>
+
+#include "defs.hpp"
+#include "World.hpp"
+
+double *World::cell_size = 0;
+char *World::DefaultName = 0;
+
+/** Constructor of World.
+ *
+ */
+World::World()
+{
+  cell_size = new double[6];
+  DefaultName = new char[MAXSTRINGSIZE];
+  strcpy(DefaultName, "none");
+};
+
+/** Destructor of World.
+ *
+ */
+World::~World()
+{
+  delete[](cell_size);
+  delete[](DefaultName);
+};
+
+
+// TODO: Hide boost-thread using Autotools stuff when no threads are used
+World* World::theWorld = 0;
+
+
+World* World::get(){
+  // boost supports RAII-Style locking, so we don't need to unlock
+  if(!theWorld) {
+    theWorld = new World();
+  }
+  return theWorld;
+}
+
+void World::destroy(){
+  delete theWorld;
+  theWorld = 0;
+}
+
+World* World::reset(){
+  World* oldWorld = 0;
+  {
+    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;
+}
Index: src/World.hpp
===================================================================
--- src/World.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/World.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,43 @@
+/*
+ * world.hpp
+ *
+ *  Created on: Mar 3, 2010
+ *      Author: heber
+ */
+
+#ifndef WORLD_HPP_
+#define WORLD_HPP_
+
+using namespace std;
+
+/*********************************************** includes ***********************************/
+
+// include config.h
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+
+/****************************************** forward declarations *****************************/
+
+/********************************************** Class World *******************************/
+
+class World
+{
+  /***** singleton Stuff *****/
+public:
+  static World* get();
+  static void destroy();
+  static World* reset();
+
+  static double *cell_size;
+  static char *DefaultName;
+
+private:
+  World();
+  virtual ~World();
+
+  static World *theWorld;
+};
+
+#endif /* WORLD_HPP_ */
Index: src/analysis_bonds.cpp
===================================================================
--- src/analysis_bonds.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/analysis_bonds.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -6,2 +6,270 @@
  */
 
+#include "analysis_bonds.hpp"
+#include "atom.hpp"
+#include "bond.hpp"
+#include "element.hpp"
+#include "info.hpp"
+#include "log.hpp"
+#include "molecule.hpp"
+
+/** Calculates the min, mean and maximum bond counts for the given molecule.
+ * \param *mol molecule with atoms and atom::ListOfBonds
+ * \param &Min minimum count on return
+ * \param &Mean mean count on return
+ * \param &Max maximum count on return
+ */
+void GetMaxMinMeanBondCount(const molecule * const mol, double &Min, double &Mean, double &Max)
+{
+  Min = 2e+6;
+  Max = -2e+5;
+  Mean = 0.;
+
+  atom *Walker = mol->start;
+  int AtomCount = 0;
+  while (Walker->next != mol->end) {
+    Walker = Walker->next;
+    const int count = Walker->ListOfBonds.size();
+    if (Max < count)
+      Max = count;
+    if (Min > count)
+      Min = count;
+    Mean += count;
+    AtomCount++;
+  }
+  if (((int)Mean % 2) != 0)
+    DoeLog(1) && (eLog()<< Verbose(1) << "Something is wrong with the bond structure, the number of bonds is not even!" << endl);
+  Mean /= (double)AtomCount;
+};
+
+/** Calculates the min and max bond distance of all atoms of two given elements.
+ * \param *mol molecule with atoms
+ * \param *type1 one element
+ * \param *type2 other element
+ * \param &Min minimum distance on return, 0 if no bond between the two elements
+ * \param &Mean mean distance (i.e. sum of distance for matching element pairs, divided by number) on return, 0 if no bond between the two elements
+ * \param &Max maximum distance on return, 0 if no bond between the two elements
+ */
+void MinMeanMaxBondDistanceBetweenElements(const molecule *mol, element *type1, element *type2, double &Min, double &Mean, double &Max)
+{
+  Min = 2e+6;
+  Mean = 0.;
+  Max = -2e+6;
+
+  int AtomNo = 0;
+  atom *Walker = mol->start;
+  while (Walker->next != mol->end) {
+    Walker = Walker->next;
+    if (Walker->type == type1)
+      for (BondList::const_iterator BondRunner = Walker->ListOfBonds.begin(); BondRunner != Walker->ListOfBonds.end(); BondRunner++)
+        if ((*BondRunner)->GetOtherAtom(Walker)->type == type2) {
+          const double distance = (*BondRunner)->GetDistanceSquared();
+          if (Min > distance)
+            Min = distance;
+          if (Max < distance)
+            Max = distance;
+          Mean += sqrt(distance);
+          AtomNo++;
+        }
+  }
+  if (Max < 0) {
+    Max = Min = 0.;
+  } else {
+    Max = sqrt(Max);
+    Min = sqrt(Min);
+    Mean = Mean/(double)AtomNo;
+  }
+};
+
+/** 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.CopyVector(first);
+  OHBond.SubtractVector(central);
+  OOBond.CopyVector(second);
+  OOBond.SubtractVector(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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/analysis_bonds.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -18,9 +18,22 @@
 #endif
 
+/*********************************************** defines ***********************************/
+
+#define HBRIDGEDISTANCE 3.5   //!< HBridge distance from PCCP Vol 10. 4802-4813
 
 /****************************************** forward declarations *****************************/
 
+class element;
+class MoleculeListClass;
+class molecule;
 
 /********************************************** declarations *******************************/
 
+void GetMaxMinMeanBondCount(const molecule * const mol, double &Min, double &Mean, double &Max);
+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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/analysis_correlation.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -10,10 +10,13 @@
 #include "analysis_correlation.hpp"
 #include "element.hpp"
+#include "info.hpp"
 #include "log.hpp"
 #include "molecule.hpp"
 #include "tesselation.hpp"
 #include "tesselationhelpers.hpp"
+#include "triangleintersectionlist.hpp"
 #include "vector.hpp"
 #include "verbose.hpp"
+#include "World.hpp"
 
 
@@ -28,9 +31,10 @@
 PairCorrelationMap *PairCorrelation(MoleculeListClass * const &molecules, const element * const type1, const element * const type2 )
 {
+  Info FunctionInfo(__func__);
   PairCorrelationMap *outmap = NULL;
   double distance = 0.;
 
   if (molecules->ListOfMolecules.empty()) {
-    eLog() << Verbose(1) <<"No molecule given." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) <<"No molecule given." << endl);
     return outmap;
   }
@@ -38,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::get()->cell_size);
                     //Log() << Verbose(1) <<"Inserting " << *Walker << " and " << *OtherWalker << endl;
                     outmap->insert ( pair<double, pair <atom *, atom*> > (distance, pair<atom *, atom*> (Walker, OtherWalker) ) );
@@ -77,4 +81,5 @@
 PairCorrelationMap *PeriodicPairCorrelation(MoleculeListClass * const &molecules, const element * const type1, const element * const type2, const int ranges[NDIM] )
 {
+  Info FunctionInfo(__func__);
   PairCorrelationMap *outmap = NULL;
   double distance = 0.;
@@ -87,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;
   }
@@ -93,11 +98,11 @@
   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::get()->cell_size);
       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);
@@ -112,9 +117,9 @@
                 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)) {
@@ -154,9 +159,10 @@
 CorrelationToPointMap *CorrelationToPoint(MoleculeListClass * const &molecules, const element * const type, const Vector *point )
 {
+  Info FunctionInfo(__func__);
   CorrelationToPointMap *outmap = NULL;
   double distance = 0.;
 
   if (molecules->ListOfMolecules.empty()) {
-    Log() << Verbose(1) <<"No molecule given." << endl;
+    DoLog(1) && (Log() << Verbose(1) <<"No molecule given." << endl);
     return outmap;
   }
@@ -164,12 +170,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::get()->cell_size);
+          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) ) );
         }
@@ -190,4 +196,5 @@
 CorrelationToPointMap *PeriodicCorrelationToPoint(MoleculeListClass * const &molecules, const element * const type, const Vector *point, const int ranges[NDIM] )
 {
+  Info FunctionInfo(__func__);
   CorrelationToPointMap *outmap = NULL;
   double distance = 0.;
@@ -197,5 +204,5 @@
 
   if (molecules->ListOfMolecules.empty()) {
-    Log() << Verbose(1) <<"No molecule given." << endl;
+    DoLog(1) && (Log() << Verbose(1) <<"No molecule given." << endl);
     return outmap;
   }
@@ -203,11 +210,11 @@
   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::get()->cell_size);
       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);
@@ -221,5 +228,5 @@
                 checkX.MatrixMultiplication(FullMatrix);
                 distance = checkX.Distance(point);
-                Log() << Verbose(4) << "Current distance is " << distance << "." << endl;
+                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) ) );
               }
@@ -243,4 +250,5 @@
 CorrelationToSurfaceMap *CorrelationToSurface(MoleculeListClass * const &molecules, const element * const type, const Tesselation * const Surface, const LinkedCell *LC )
 {
+  Info FunctionInfo(__func__);
   CorrelationToSurfaceMap *outmap = NULL;
   double distance = 0;
@@ -249,5 +257,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;
   }
@@ -255,18 +263,19 @@
   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->FindClosestTriangleToPoint(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;
@@ -288,4 +297,5 @@
 CorrelationToSurfaceMap *PeriodicCorrelationToSurface(MoleculeListClass * const &molecules, const element * const type, const Tesselation * const Surface, const LinkedCell *LC, const int ranges[NDIM] )
 {
+  Info FunctionInfo(__func__);
   CorrelationToSurfaceMap *outmap = NULL;
   double distance = 0;
@@ -297,21 +307,24 @@
 
   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;
   }
   outmap = new CorrelationToSurfaceMap;
-  for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin(); MolWalker != molecules->ListOfMolecules.end(); MolWalker++)
-    if ((*MolWalker)->ActiveFlag) {
-      double * FullMatrix = ReturnFullMatrixforSymmetric((*MolWalker)->cell_size);
+  double ShortestDistance = 0.;
+  BoundaryTriangleSet *ShortestTriangle = NULL;
+  for (MoleculeList::const_iterator MolWalker = molecules->ListOfMolecules.begin(); MolWalker != molecules->ListOfMolecules.end(); MolWalker++)
+    if ((*MolWalker)->ActiveFlag) {
+      double * FullMatrix = ReturnFullMatrixforSymmetric(World::get()->cell_size);
       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.MatrixMultiplication(FullInverseMatrix);  // x now in [0,1)^3
           // go through every range in xyz and get distance
+          ShortestDistance = -1.;
           for (n[0]=-ranges[0]; n[0] <= ranges[0]; n[0]++)
             for (n[1]=-ranges[1]; n[1] <= ranges[1]; n[1]++)
@@ -320,10 +333,15 @@
                 checkX.AddVector(&periodicX);
                 checkX.MatrixMultiplication(FullMatrix);
-                triangle = Surface->FindClosestTriangleToPoint(&checkX, LC );
-                if (triangle != NULL) {
-                  distance = DistanceToTrianglePlane(&checkX, triangle);
-                  outmap->insert ( pair<double, pair<atom *, BoundaryTriangleSet*> >(distance, pair<atom *, BoundaryTriangleSet*> (Walker, triangle) ) );
+                TriangleIntersectionList Intersections(&checkX,Surface,LC);
+                distance = Intersections.GetSmallestDistance();
+                triangle = Intersections.GetClosestTriangle();
+                if ((ShortestDistance == -1.) || (distance < ShortestDistance)) {
+                  ShortestDistance = distance;
+                  ShortestTriangle = triangle;
                 }
-          }
+              }
+          // insert
+          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;
         }
       }
@@ -335,13 +353,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 )
-{
-  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);
 };
 
@@ -353,7 +372,8 @@
 void OutputCorrelation( ofstream * const file, const BinPairMap * const map )
 {
-  *file << "# BinStart\tCount" << endl;
+  Info FunctionInfo(__func__);
+  *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;
   }
 };
@@ -365,7 +385,8 @@
 void OutputPairCorrelation( ofstream * const file, const PairCorrelationMap * const map )
 {
-  *file << "# BinStart\tAtom1\tAtom2" << endl;
+  Info FunctionInfo(__func__);
+  *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;
   }
 };
@@ -377,9 +398,10 @@
 void OutputCorrelationToPoint( ofstream * const file, const CorrelationToPointMap * const map )
 {
-  *file << "# BinStart\tAtom::x[i]-point.x[i]" << endl;
+  Info FunctionInfo(__func__);
+  *file << "BinStart\tAtom::x[i]-point.x[i]" << endl;
   for (CorrelationToPointMap::const_iterator runner = map->begin(); runner != map->end(); ++runner) {
     *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->x[i] - runner->second.second->x[i]);
     *file << endl;
   }
@@ -392,8 +414,10 @@
 void OutputCorrelationToSurface( ofstream * const file, const CorrelationToSurfaceMap * const map )
 {
-  *file << "# BinStart\tTriangle" << endl;
-  for (CorrelationToSurfaceMap::const_iterator runner = map->begin(); runner != map->end(); ++runner) {
-    *file << runner->first << "\t" << *(runner->second.second) << endl;
-  }
-};
-
+  Info FunctionInfo(__func__);
+  *file << "BinStart\tTriangle" << 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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/analysis_correlation.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -51,9 +51,9 @@
 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 BinPairMap * const map );
-void OutputCorrelationToPoint( ofstream * const file, const BinPairMap * const map );
-void OutputCorrelationToSurface( ofstream * const file, const BinPairMap * const map );
+void OutputPairCorrelation( ofstream * const file, const PairCorrelationMap * const map );
+void OutputCorrelationToPoint( ofstream * const file, const CorrelationToPointMap * const map );
+void OutputCorrelationToSurface( ofstream * const file, const CorrelationToSurfaceMap * const map );
 
 
@@ -71,5 +71,6 @@
 
   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;
   }
@@ -89,5 +90,7 @@
 /** Puts given correlation data into bins of given size (histogramming).
  * Note that BinStart and BinEnd are desired to fill the complete range, even where Bins are zero. If this is
- * not desired, give equal BinStart and BinEnd and the map will contain only Bins where the count is one or greater.
+ * not desired, give equal BinStart and BinEnd and the map will contain only Bins where the count is one or greater. If a
+ * certain start value is desired, give BinStart and a BinEnd that is smaller than BinStart, then only BinEnd will be
+ * calculated automatically, i.e. BinStart = 0. and BinEnd = -1. .
  * Also note that the range is given inclusive, i.e. [ BinStart, BinEnd ].
  * \param *map map of doubles to count
@@ -100,5 +103,5 @@
 {
   BinPairMap *outmap = new BinPairMap;
-  double bin = 0.;
+  int bin = 0;
   double start = 0.;
   double end = 0.;
@@ -106,5 +109,6 @@
 
   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;
   }
@@ -112,14 +116,17 @@
   if (BinStart == BinEnd) { // if same, find range ourselves
     GetMinMax( map, start, end);
-  } else { // if not, initialise range to zero
+  } else if (BinEnd < BinStart) { // if BinEnd smaller, just look for new max
+    GetMinMax( map, start, end);
+    start = BinStart;
+  } else { // else take both values
     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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/analyzer.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -7,4 +7,6 @@
 
 //============================ INCLUDES ===========================
+
+#include <cstring>
 
 #include "datacreator.hpp"
@@ -61,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 {
@@ -79,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]);
@@ -94,5 +96,5 @@
   if (!Hcorrection.ParseFragmentMatrix(argv[1], "", HCORRECTIONSUFFIX,0,0)) {
     NoHCorrection = true;
-    Log() << Verbose(0) << "No HCorrection file found, skipping these." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "No HCorrection file found, skipping these." << endl);
   }
   
@@ -100,9 +102,9 @@
   if (!Hessian.ParseFragmentMatrix(argv[1], dir, HessianSuffix,0,0)) {
     NoHessian = true;
-    Log() << Verbose(0) << "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;
-    Log() << Verbose(0) << "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
@@ -246,5 +248,5 @@
   // +++++++++++++++ ANALYZING ++++++++++++++++++++++++++++++
 
-  Log() << Verbose(0) << "Analyzing ..." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Analyzing ..." << endl);
 
   // ======================================= Creating the data files ==============================================================
@@ -557,5 +559,5 @@
   delete(periode);
   Free(&dir);
-  Log() << Verbose(0) << "done." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done." << endl);
   return 0;
 };
Index: src/atom_bondedparticle.cpp
===================================================================
--- src/atom_bondedparticle.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/atom_bondedparticle.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -44,11 +44,11 @@
 void BondedParticle::OutputBondOfAtom() const
 {
-  Log() << Verbose(4) << "Atom " << Name << "/" << nr << " with " << ListOfBonds.size() << " bonds: ";
+  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(0) << **Runner << "\t";
+    DoLog(4) && (Log() << Verbose(4) << **Runner << endl);
     TotalDegree += (*Runner)->BondDegree;
   }
-  Log() << Verbose(0) << " -- TotalDegree: " << TotalDegree << endl;
+  DoLog(4) && (Log() << Verbose(4) << " -- TotalDegree: " << TotalDegree << endl);
 };
 
@@ -56,5 +56,5 @@
  * \param *AdjacencyFile output stream
  */
-void BondedParticle::OutputAdjacency(ofstream *AdjacencyFile) const
+void BondedParticle::OutputAdjacency(ofstream * const AdjacencyFile) const
 {
   *AdjacencyFile << nr << "\t";
@@ -62,4 +62,15 @@
     *AdjacencyFile << (*Runner)->GetOtherAtom(this)->nr << "\t";
   *AdjacencyFile << endl;
+};
+
+/** Output of atom::nr along each bond partner per line.
+ * Only bonds are printed where atom::nr is smaller than the one of the bond partner.
+ * \param *AdjacencyFile output stream
+ */
+void BondedParticle::OutputBonds(ofstream * const BondFile) const
+{
+  for (BondList::const_iterator Runner = ListOfBonds.begin(); Runner != ListOfBonds.end(); (++Runner))
+    if (nr < (*Runner)->GetOtherAtom(this)->nr)
+      *BondFile << nr << "\t" << (*Runner)->GetOtherAtom(this)->nr << "\n";
 };
 
@@ -75,8 +86,8 @@
       status = true;
     } else {
-      Log() << Verbose(1) << "ERROR: " << *Binder << " does not contain " << *this << "." << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << *Binder << " does not contain " << *this << "." << endl);
     }
   } else {
-    Log() << Verbose(1) << "ERROR: Binder is " << Binder << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Binder is " << Binder << "." << endl);
   }
   return status;
@@ -94,8 +105,8 @@
       status = true;
     } else {
-      Log() << Verbose(1) << "ERROR: " << *Binder << " does not contain " << *this << "." << endl;
+      DoeLog(1) && (eLog()<< Verbose(1) << *Binder << " does not contain " << *this << "." << endl);
     }
   } else {
-    Log() << Verbose(1) << "ERROR: Binder is " << Binder << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Binder is " << Binder << "." << endl);
   }
   return status;
@@ -121,12 +132,12 @@
   bond *CandidateBond = NULL;
 
+  NoBonds = CountBonds();
   //Log() << Verbose(3) << "Walker " << *this << ": " << (int)this->type->NoValenceOrbitals << " > " << NoBonds << "?" << endl;
-  NoBonds = CountBonds();
   if ((int)(type->NoValenceOrbitals) > NoBonds) { // we have a mismatch, check all bonding partners for mismatch
     for (BondList::const_iterator Runner = ListOfBonds.begin(); Runner != ListOfBonds.end(); (++Runner)) {
       OtherWalker = (*Runner)->GetOtherAtom(this);
       OtherNoBonds = OtherWalker->CountBonds();
-      //Log() << Verbose(3) << "OtherWalker " << *OtherWalker << ": " << (int)OtherWalker->type->NoValenceOrbitals << " > " << NoBonds << "?" << endl;
-      if ((int)(OtherWalker->type->NoValenceOrbitals) > NoBonds) { // check if possible candidate
+      //Log() << Verbose(3) << "OtherWalker " << *OtherWalker << ": " << (int)OtherWalker->type->NoValenceOrbitals << " > " << OtherNoBonds << "?" << endl;
+      if ((int)(OtherWalker->type->NoValenceOrbitals) > OtherNoBonds) { // check if possible candidate
         if ((CandidateBond == NULL) || (ListOfBonds.size() > OtherWalker->ListOfBonds.size())) { // pick the one with fewer number of bonds first
           CandidateBond = (*Runner);
@@ -137,7 +148,7 @@
     if ((CandidateBond != NULL)) {
       CandidateBond->BondDegree++;
-      Log() << Verbose(2) << "Increased bond degree for bond " << *CandidateBond << "." << endl;
+      //Log() << Verbose(2) << "Increased bond degree for bond " << *CandidateBond << "." << endl;
     } else {
-      //Log() << 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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/atom_bondedparticle.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -44,5 +44,6 @@
   int CorrectBondDegree();
   void OutputBondOfAtom() const;
-  void OutputAdjacency(ofstream *AdjacencyFile) const;
+  void OutputAdjacency(ofstream * const AdjacencyFile) const;
+  void OutputBonds(ofstream * const BondFile) const;
   void OutputOrder(ofstream *file) const;
 
Index: src/atom_graphnode.cpp
===================================================================
--- src/atom_graphnode.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/atom_graphnode.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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(0) << " 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(0) << ComponentNr[i] << " ";
+      DoLog(2) && (Log() << Verbose(2) << ComponentNr[i] << " ");
   }
 };
Index: src/atom_particleinfo.cpp
===================================================================
--- src/atom_particleinfo.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/atom_particleinfo.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -22,5 +22,8 @@
 ostream & operator << (ostream &ost, const ParticleInfo &a)
 {
-  ost << "[" << a.Name << "|" << &a << "]";
+  if (a.Name == NULL)
+    ost << "[NULL]";
+  else
+    ost << "[" << a.Name << "|" << &a << "]";
   return ost;
 };
@@ -28,5 +31,8 @@
 ostream & ParticleInfo::operator << (ostream &ost) const
 {
-  ost << "[" << Name << "|" << this << "]";
+  if (Name == NULL)
+    ost << "[NULL]";
+  else
+    ost << "[" << Name << "|" << this << "]";
   return ost;
 };
Index: src/atom_trajectoryparticle.cpp
===================================================================
--- src/atom_trajectoryparticle.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/atom_trajectoryparticle.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -198,10 +198,10 @@
     // 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(0) << 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++)
Index: src/bond.cpp
===================================================================
--- src/bond.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/bond.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -63,5 +63,5 @@
   if(rightatom == Atom) 
     return leftatom;
-  eLog() << Verbose(0) << "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 +99,5 @@
 bool bond::MarkUsed(const enum Shading color) {
   if (Used == black) {
-    eLog() << Verbose(0) << "ERROR: Bond " << this << " was already marked black!." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Bond " << this << " was already marked black!." << endl);
     return false;
   } else {
@@ -113,2 +113,18 @@
   Used = white;
 };
+
+/** Calculates the bond length.
+ * \return |a - b| with a = bond::leftatom and b = bond::rightatom.
+ */
+double bond::GetDistance() const
+{
+  return (leftatom->node->Distance(rightatom->node));
+};
+
+/** Calculates the bond length.
+ * \return |a - b|^2 with a = bond::leftatom and b = bond::rightatom.
+ */
+double bond::GetDistanceSquared() const
+{
+  return (leftatom->node->DistanceSquared(rightatom->node));
+};
Index: src/bond.hpp
===================================================================
--- src/bond.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/bond.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -51,4 +51,6 @@
   bool Contains(const ParticleInfo * const ptr);
   bool Contains(const int nr);
+  double GetDistance() const;
+  double GetDistanceSquared() const;
 
   bond();
Index: src/bondgraph.cpp
===================================================================
--- src/bondgraph.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/bondgraph.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -9,6 +9,8 @@
 
 #include "atom.hpp"
+#include "bond.hpp"
 #include "bondgraph.hpp"
 #include "element.hpp"
+#include "info.hpp"
 #include "log.hpp"
 #include "molecule.hpp"
@@ -35,5 +37,5 @@
 /** Parses the bond lengths in a given file and puts them int a matrix form.
  * Allocates \a MatrixContainer for BondGraph::BondLengthMatrix, using MatrixContainer::ParseMatrix(),
- * but only if parsing is successfull. Otherwise variable is left as NULL.
+ * but only if parsing is successful. Otherwise variable is left as NULL.
  * \param *out output stream for debugging
  * \param filename file with bond lengths to parse
@@ -42,4 +44,5 @@
 bool BondGraph::LoadBondLengthTable(const string &filename)
 {
+  Info FunctionInfo(__func__);
   bool status = true;
   MatrixContainer *TempContainer = NULL;
@@ -47,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);
   }
@@ -53,5 +56,9 @@
 
   // parse in matrix
-  status = TempContainer->ParseMatrix(filename.c_str(), 0, 1, 0);
+  if ((status = TempContainer->ParseMatrix(filename.c_str(), 0, 1, 0))) {
+    DoLog(1) && (Log() << Verbose(1) << "Parsing bond length matrix successful." << endl);
+  } else {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Parsing bond length matrix failed." << endl);
+  }
 
   // find greatest distance
@@ -80,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
@@ -113,4 +121,5 @@
 double BondGraph::SetMaxDistanceToMaxOfCovalentRadii(const molecule * const mol)
 {
+  Info FunctionInfo(__func__);
   max_distance = 0.;
 
@@ -153,5 +162,5 @@
 {
   if (BondLengthMatrix == NULL) {// safety measure if no matrix has been parsed yet
-    eLog() << Verbose(1) << "WARNING:  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 {
@@ -162,3 +171,2 @@
   }
 };
-
Index: src/bondgraph.hpp
===================================================================
--- src/bondgraph.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/bondgraph.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/boundary.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -10,4 +10,5 @@
 #include "element.hpp"
 #include "helpers.hpp"
+#include "info.hpp"
 #include "linkedcell.hpp"
 #include "log.hpp"
@@ -16,6 +17,8 @@
 #include "tesselation.hpp"
 #include "tesselationhelpers.hpp"
+#include "World.hpp"
 
 #include<gsl/gsl_poly.h>
+#include<time.h>
 
 // ========================================== F U N C T I O N S =================================
@@ -33,4 +36,5 @@
 double *GetDiametersOfCluster(const Boundaries *BoundaryPtr, const molecule *mol, Tesselation *&TesselStruct, const bool IsAngstroem)
 {
+	Info FunctionInfo(__func__);
   // get points on boundary of NULL was given as parameter
   bool BoundaryFreeFlag = false;
@@ -53,5 +57,5 @@
   } else {
     BoundaryPoints = BoundaryPtr;
-    Log() << Verbose(1) << "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
@@ -67,5 +71,5 @@
           //Log() << Verbose(1) << "Current component is " << component << ", Othercomponent is " << Othercomponent << "." << endl;
           for (Boundaries::const_iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
-              //Log() << Verbose(2) << "Current runner is " << *(runner->second.second) << "." << endl;
+              //Log() << Verbose(1) << "Current runner is " << *(runner->second.second) << "." << endl;
               // seek for the neighbours pair where the Othercomponent sign flips
               Neighbour = runner;
@@ -82,5 +86,5 @@
                   DistanceVector.CopyVector(&runner->second.second->x);
                   DistanceVector.SubtractVector(&Neighbour->second.second->x);
-                  //Log() << Verbose(3) << "OldComponent is " << OldComponent << ", new one is " << DistanceVector.x[Othercomponent] << "." << endl;
+                  //Log() << Verbose(2) << "OldComponent is " << OldComponent << ", new one is " << DistanceVector.x[Othercomponent] << "." << endl;
                 } while ((runner != Neighbour) && (fabs(OldComponent / fabs(
                   OldComponent) - DistanceVector.x[Othercomponent] / fabs(
@@ -91,10 +95,10 @@
                     OtherNeighbour = BoundaryPoints[axis].end();
                   OtherNeighbour--;
-                  //Log() << Verbose(2) << "The pair, where the sign of OtherComponent flips, is: " << *(Neighbour->second.second) << " and " << *(OtherNeighbour->second.second) << "." << endl;
+                  //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);
-                  //Log() << Verbose(2) << "Distances to Neighbour and OtherNeighbour are " << DistanceVector.x[component] << " and " << OtherVector.x[component] << "." << endl;
-                  //Log() << Verbose(2) << "OtherComponents to Neighbour and OtherNeighbour are " << DistanceVector.x[Othercomponent] << " and " << OtherVector.x[Othercomponent] << "." << endl;
+                  //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]);
@@ -103,9 +107,9 @@
                       * OtherVector.x[component]) / (w1 + w2));
                   // mark if it has greater diameter
-                  //Log() << Verbose(2) << "Comparing current greatest " << GreatestDiameter[component] << " to new " << tmp << "." << endl;
+                  //Log() << Verbose(1) << "Comparing current greatest " << GreatestDiameter[component] << " to new " << tmp << "." << endl;
                   GreatestDiameter[component] = (GreatestDiameter[component]
                       > tmp) ? GreatestDiameter[component] : tmp;
                 } //else
-              //Log() << Verbose(2) << "Saw no sign flip, probably top or bottom node." << endl;
+              //Log() << Verbose(1) << "Saw no sign flip, probably top or bottom node." << endl;
             }
         }
@@ -135,4 +139,5 @@
 Boundaries *GetBoundaryPoints(const molecule *mol, Tesselation *&TesselStruct)
 {
+	Info FunctionInfo(__func__);
   atom *Walker = NULL;
   PointMap PointsOnBoundary;
@@ -149,5 +154,4 @@
   double angle = 0.;
 
-  Log() << Verbose(1) << "Finding all boundary points." << endl;
   // 3a. Go through every axis
   for (int axis = 0; axis < NDIM; axis++) {
@@ -159,5 +163,5 @@
     AngleReferenceNormalVector.x[(axis + 2) % NDIM] = 1.;
 
-    Log() << Verbose(1) << "Axisvector is " << AxisVector << " and AngleReferenceVector is " << AngleReferenceVector << ", and AngleReferenceNormalVector is " << AngleReferenceNormalVector << "." << endl;
+    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
@@ -176,19 +180,19 @@
         angle = 0.; // otherwise it's a vector in Axis Direction and unimportant for boundary issues
 
-      //Log() << Verbose(0) << "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << "." << endl;
+      //Log() << Verbose(1) << "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << "." << endl;
       if (ProjectedVector.ScalarProduct(&AngleReferenceNormalVector) > 0) {
         angle = 2. * M_PI - angle;
       }
-      Log() << Verbose(2) << "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);
@@ -199,10 +203,10 @@
           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);
         }
       }
@@ -210,5 +214,5 @@
     // printing all inserted for debugging
     //    {
-    //      Log() << Verbose(2) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
+    //      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++) {
@@ -223,5 +227,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,28 +253,20 @@
           SideA.SubtractVector(MolCenter);
           SideA.ProjectOntoPlane(&AxisVector);
-          //          Log() << Verbose(0) << "SideA: ";
-          //          SideA.Output(out);
-          //          Log() << Verbose(0) << endl;
+          //          Log() << Verbose(1) << "SideA: " << SideA << endl;
 
           SideB.CopyVector(&right->second.second->x);
           SideB.SubtractVector(MolCenter);
           SideB.ProjectOntoPlane(&AxisVector);
-          //          Log() << Verbose(0) << "SideB: ";
-          //          SideB.Output(out);
-          //          Log() << Verbose(0) << endl;
+          //          Log() << Verbose(1) << "SideB: " << SideB << endl;
 
           SideC.CopyVector(&left->second.second->x);
           SideC.SubtractVector(&right->second.second->x);
           SideC.ProjectOntoPlane(&AxisVector);
-          //          Log() << Verbose(0) << "SideC: ";
-          //          SideC.Output(out);
-          //          Log() << Verbose(0) << endl;
+          //          Log() << Verbose(1) << "SideC: " << SideC << endl;
 
           SideH.CopyVector(&runner->second.second->x);
           SideH.SubtractVector(MolCenter);
           SideH.ProjectOntoPlane(&AxisVector);
-          //          Log() << Verbose(0) << "SideH: ";
-          //          SideH.Output(out);
-          //          Log() << Verbose(0) << endl;
+          //          Log() << Verbose(1) << "SideH: " << SideH << endl;
 
           // calculate each length
@@ -285,9 +281,9 @@
           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(2) << " 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;
+          //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;
+          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;
@@ -311,8 +307,7 @@
 void FindConvexBorder(const molecule* mol, Tesselation *&TesselStruct, const LinkedCell *LCList, const char *filename)
 {
+	Info FunctionInfo(__func__);
   bool BoundaryFreeFlag = false;
   Boundaries *BoundaryPoints = NULL;
-
-  Log() << Verbose(1) << "Begin of FindConvexBorder" << endl;
 
   if (TesselStruct != NULL) // free if allocated
@@ -325,5 +320,5 @@
       BoundaryPoints = GetBoundaryPoints(mol, TesselStruct);
   } else {
-      Log() << Verbose(1) << "Using given boundary points set." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Using given boundary points set." << endl);
   }
 
@@ -331,14 +326,14 @@
   for (int axis=0; axis < NDIM; axis++)
     {
-      Log() << Verbose(2) << "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);
     }
 
@@ -347,7 +342,7 @@
     for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++)
         if (!TesselStruct->AddBoundaryPoint(runner->second.second, 0))
-          Log() << Verbose(3) << "WARNING: Point " << *(runner->second.second) << " is already present!" << endl;
-
-  Log() << Verbose(2) << "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
 
@@ -367,7 +362,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))
-    Log() << Verbose(1) << "Insertion of straddling points failed!" << endl;
-
-  Log() << Verbose(2) << "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
@@ -400,14 +395,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.)
-          Log() << Verbose(1) << "ERROR: 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);
         }
       }
@@ -419,5 +414,5 @@
 //    Log() << Verbose(1) << "Correction of concave tesselpoints failed!" << endl;
 
-  Log() << Verbose(2) << "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
@@ -445,6 +440,4 @@
   if (BoundaryFreeFlag)
     delete[] (BoundaryPoints);
-
-  Log() << Verbose(1) << "End of FindConvexBorder" << endl;
 };
 
@@ -458,9 +451,10 @@
 bool RemoveAllBoundaryPoints(class Tesselation *&TesselStruct, const molecule * const mol, const char * const filename)
 {
+	Info FunctionInfo(__func__);
   int i=0;
   char number[MAXSTRINGSIZE];
 
   if ((TesselStruct == NULL) || (TesselStruct->PointsOnBoundary.empty())) {
-    Log() << Verbose(2) << "ERROR: TesselStruct is empty." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "TesselStruct is empty." << endl);
     return false;
   }
@@ -468,8 +462,8 @@
   PointMap::iterator PointRunner;
   while (!TesselStruct->PointsOnBoundary.empty()) {
-    Log() << Verbose(2) << "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();
@@ -511,4 +505,5 @@
 double ConvexizeNonconvexEnvelope(class Tesselation *&TesselStruct, const molecule * const mol, const char * const filename)
 {
+	Info FunctionInfo(__func__);
   double volume = 0;
   class BoundaryPointSet *point = NULL;
@@ -524,9 +519,7 @@
   int run = 0;
 
-  Log() << Verbose(0) << "Begin of ConvexizeNonconvexEnvelope" << endl;
-
   // check whether there is something to work on
   if (TesselStruct == NULL) {
-    Log() << Verbose(1) << "ERROR: TesselStruct is empty!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "TesselStruct is empty!" << endl);
     return volume;
   }
@@ -544,11 +537,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(2) << "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);
@@ -571,5 +564,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) {
@@ -612,6 +605,5 @@
 
   // end
-  Log() << Verbose(1) << "Volume is " << volume << "." << endl;
-  Log() << Verbose(0) << "End of ConvexizeNonconvexEnvelope" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Volume is " << volume << "." << endl);
   return volume;
 };
@@ -627,4 +619,5 @@
 double VolumeOfConvexEnvelope(class Tesselation *TesselStruct, class config *configuration)
 {
+	Info FunctionInfo(__func__);
   bool IsAngstroem = configuration->GetIsAngstroem();
   double volume = 0.;
@@ -633,7 +626,4 @@
 
   // 6a. Every triangle forms a pyramid with the center of gravity as its peak, sum up the volumes
-  Log() << Verbose(1)
-      << "Calculating the volume of the pyramids formed out of triangles and center of gravity."
-      << endl;
   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
@@ -650,5 +640,5 @@
       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)
-      Log() << Verbose(2) << "Area of triangle is " << setprecision(10) << G << " "
+      Log() << Verbose(1) << "Area of triangle is " << setprecision(10) << G << " "
           << (IsAngstroem ? "angstrom" : "atomiclength") << "^2, height is "
           << h << " and the volume is " << PyramidVolume << " "
@@ -666,10 +656,11 @@
  * \param *out output stream for debugging
  * \param *mol molecule with atoms and bonds
- * \param *&TesselStruct Tesselation with boundary triangles
+ * \param *TesselStruct Tesselation with boundary triangles
  * \param *filename prefix of filename
  * \param *extraSuffix intermediate suffix
  */
-void StoreTrianglesinFile(const molecule * const mol, const Tesselation *&TesselStruct, const char *filename, const char *extraSuffix)
+void StoreTrianglesinFile(const molecule * const mol, const Tesselation * const TesselStruct, const char *filename, const char *extraSuffix)
 {
+	Info FunctionInfo(__func__);
   // 4. Store triangles in tecplot file
   if (filename != NULL) {
@@ -679,5 +670,5 @@
       OutputName.append(TecplotSuffix);
       ofstream *tecplot = new ofstream(OutputName.c_str());
-      WriteTecplotFile(tecplot, TesselStruct, mol, 0);
+      WriteTecplotFile(tecplot, TesselStruct, mol, -1);
       tecplot->close();
       delete(tecplot);
@@ -706,4 +697,5 @@
 void PrepareClustersinWater(config *configuration, molecule *mol, double ClusterVolume, double celldensity)
 {
+	Info FunctionInfo(__func__);
   bool IsAngstroem = true;
   double *GreatestDiameter = NULL;
@@ -742,20 +734,20 @@
       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(0) << "ERROR: 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];
@@ -769,7 +761,7 @@
     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;
+      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
     }
@@ -782,5 +774,5 @@
 
     // 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();
@@ -788,5 +780,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.x[0] << " and " << BoxLengths.x[1] << " and " << BoxLengths.x[2] << " with total volume of " << cellvolume << " " << (IsAngstroem ? "angstrom" : "atomiclength") << "^3." << endl);
 };
 
@@ -798,5 +790,8 @@
  * \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
+ * \param epsilon distance to surface which is not filled
  * \param RandAtomDisplacement maximum distance for random displacement per atom
  * \param RandMolDisplacement maximum distance for random displacement per filler molecule
@@ -804,39 +799,43 @@
  * \return *mol pointer to new molecule with filled atoms
  */
-molecule * FillBoxWithMolecule(MoleculeListClass *List, molecule *filler, config &configuration, double distance[NDIM], double RandomAtomDisplacement, double RandomMolDisplacement, 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);
   Vector CurrentPosition;
   int N[NDIM];
   int n[NDIM];
-  double *M =  ReturnFullMatrixforSymmetric(filler->cell_size);
+  double *M =  ReturnFullMatrixforSymmetric(World::get()->cell_size);
   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()];
-
-  Log() << Verbose(0) << "Begin of FillBoxWithMolecule" << endl;
-
-  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), 5.); // get linked cell list
-    if (TesselStruct[i] == NULL) {
-      Log() << Verbose(1) << "Pre-creating tesselation for molecule " << *ListRunner << "." << endl;
-      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();
@@ -846,13 +845,10 @@
   FillerDistance.Init(distance[0], distance[1], distance[2]);
   FillerDistance.InverseMatrixMultiplication(M);
-  Log() << Verbose(1) << "INFO: Grid steps are ";
-  for(int i=0;i<NDIM;i++) {
+  for(int i=0;i<NDIM;i++)
     N[i] = (int) ceil(1./FillerDistance.x[i]);
-    Log() << Verbose(0) << N[i];
-    if (i != NDIM-1)
-      Log() << Verbose(0)<< ", ";
-    else
-      Log() << Verbose(0) << "." << endl;
-  }
+  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
+  srand ( time(NULL) );
 
   // go over [0,1]^3 filler grid
@@ -863,88 +859,86 @@
         CurrentPosition.Init((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) {
-            Log() << Verbose(1) << "ERROR: 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.x[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.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
+          Inserter.CopyVector(&(Walker->x));
+          if (DoRandomRotation)
+            Inserter.MatrixMultiplication(Rotations);
+          Inserter.AddVector(&AtomTranslations);
+          Inserter.AddVector(&FillerTranslations);
+          Inserter.AddVector(&CurrentPosition);
+
+          // check whether inserter is inside box
+          Inserter.MatrixMultiplication(MInverse);
+          FillIt = true;
+          for (int i=0;i<NDIM;i++)
+            FillIt = FillIt && (Inserter.x[i] >= -MYEPSILON) && ((Inserter.x[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] = new atom(Walker);
+            CopyAtoms[Walker->nr]->x.CopyVector(&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 {
-            FillIt = FillIt && (!TesselStruct[i]->IsInnerPoint(CurrentPosition, LCList[i]));
-            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(3) << "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);
-  for (size_t i=0;i<List->ListOfMolecules.size();i++) {
-  	delete(LCList[i]);
-	delete(TesselStruct[i]);
-  }
-  Log() << Verbose(0) << "End of FillBoxWithMolecule" << endl;
+  Free(&MInverse);
 
   return Filling;
@@ -959,24 +953,23 @@
  * \param RADIUS radius of the virtual sphere
  * \param *filename filename prefix for output of vertex data
- */
-void FindNonConvexBorder(const molecule* const mol, Tesselation *&TesselStruct, const LinkedCell *&LCList, const double RADIUS, const char *filename = NULL)
+ * \return true - tesselation successful, false - tesselation failed
+ */
+bool FindNonConvexBorder(const molecule* const mol, Tesselation *&TesselStruct, const LinkedCell *&LCList, const double RADIUS, const char *filename = NULL)
 {
+	Info FunctionInfo(__func__);
   bool freeLC = false;
-  LineMap::iterator baseline;
-  LineMap::iterator testline;
-  bool OneLoopWithoutSuccessFlag = false;  // marks whether we went once through all baselines without finding any without two triangles
+  bool status = false;
+  CandidateForTesselation *baseline = NULL;
+  bool OneLoopWithoutSuccessFlag = true;  // marks whether we went once through all baselines without finding any without two triangles
   bool TesselationFailFlag = false;
 
-  Log() << Verbose(1) << "Entering search for non convex hull. " << endl;
   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;
   }
-
-  Log() << Verbose(0) << "Begin of FindNonConvexBorder\n";
 
   // initialise Linked Cell
@@ -987,42 +980,59 @@
 
   // 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
-  baseline = TesselStruct->LinesOnBoundary.begin();
-  baseline++; // skip first line
-  while ((baseline != TesselStruct->LinesOnBoundary.end()) || (OneLoopWithoutSuccessFlag)) {
-    if (baseline->second->triangles.size() == 1) {
-      // 3. find next triangle
-      TesselationFailFlag = TesselStruct->FindNextSuitableTriangle(*(baseline->second), *(((baseline->second->triangles.begin()))->second), RADIUS, LCList); //the line is there, so there is a triangle, but only one.
-      OneLoopWithoutSuccessFlag = OneLoopWithoutSuccessFlag || TesselationFailFlag;
-      if (!TesselationFailFlag)
-        eLog() << Verbose(0) << "WARNING: FindNextSuitableTriangle failed." << endl;
-
-      // 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
-          TesselStruct->Output(filename, mol);
-        }
+  while ((!TesselStruct->OpenLines.empty()) && (OneLoopWithoutSuccessFlag)) {
+    (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++)
+      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;
+    for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
+      if (Runner->second->ShortestAngle < ShortestAngle) {
+        baseline = Runner->second;
+        ShortestAngle = baseline->ShortestAngle;
+        DoLog(1) && (Log() << Verbose(1) << "New best candidate is " << *baseline->BaseLine << " with point " << *(*baseline->pointlist.begin()) << " and angle " << baseline->ShortestAngle << endl);
       }
-      baseline = TesselStruct->LinesOnBoundary.end();
-      Log() << Verbose(2) << "Baseline set to end." << endl;
-    } else {
-      //Log() << Verbose(1) << "Line " << *baseline->second << " has " << baseline->second->triangles.size() << " triangles adjacent" << endl;
-      if (baseline->second->triangles.size() != 2)
-        Log() << Verbose(1) << "ERROR: TESSELATION FINISHED WITH INVALID TRIANGLE COUNT!" << endl;
-    }
-
-    if ((baseline == TesselStruct->LinesOnBoundary.end()) && (OneLoopWithoutSuccessFlag)) {
-      baseline = TesselStruct->LinesOnBoundary.begin();   // restart if we reach end due to newly inserted lines
+    }
+    // 2e. if we found one, add candidate
+    if ((ShortestAngle == 4.*M_PI) || (baseline->pointlist.empty()))
       OneLoopWithoutSuccessFlag = false;
-    }
-    baseline++;
-  }
-  // check envelope for consistency
-  CheckListOfBaselines(TesselStruct);
-
-  // look whether all points are inside of the convex envelope, otherwise add them via degenerated triangles
-  //->InsertStraddlingPoints(mol, LCList);
+    else {
+      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
+        TesselStruct->Output(filename, mol);
+      }
+    }
+  }
+//  // check envelope for consistency
+//  status = CheckListOfBaselines(TesselStruct);
+//
+//  // look whether all points are inside of the convex envelope, otherwise add them via degenerated triangles
+//  //->InsertStraddlingPoints(mol, LCList);
 //  mol->GoToFirst();
 //  class TesselPoint *Runner = NULL;
@@ -1039,9 +1049,18 @@
 //  }
 
-  // Purges surplus triangles.
-  TesselStruct->RemoveDegeneratedTriangles();
+//  // Purges surplus triangles.
+//  TesselStruct->RemoveDegeneratedTriangles();
 
   // check envelope for consistency
-  CheckListOfBaselines(TesselStruct);
+  status = CheckListOfBaselines(TesselStruct);
+
+  // store before correction
+  StoreTrianglesinFile(mol, (const Tesselation *&)TesselStruct, filename, "");
+
+//  // correct degenerated polygons
+//  TesselStruct->CorrectAllDegeneratedPolygons();
+//
+//  // check envelope for consistency
+//  status = CheckListOfBaselines(TesselStruct);
 
   // write final envelope
@@ -1051,5 +1070,6 @@
   if (freeLC)
     delete(LCList);
-  Log() << Verbose(0) << "End of FindNonConvexBorder\n";
+
+  return status;
 };
 
@@ -1063,4 +1083,5 @@
 Vector* FindEmbeddingHole(MoleculeListClass *mols, molecule *srcmol)
 {
+	Info FunctionInfo(__func__);
   Vector *Center = new Vector;
   Center->Zero();
Index: src/boundary.hpp
===================================================================
--- src/boundary.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/boundary.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -36,5 +36,5 @@
 #define DEBUG 1
 #define DoSingleStepOutput 0
-#define SingleStepWidth 1
+#define SingleStepWidth 10
 
 #define DistancePair pair < double, atom* >
@@ -49,14 +49,14 @@
 
 double ConvexizeNonconvexEnvelope(class Tesselation *&TesselStruct, const molecule * const mol, const char * const filename);
-molecule * FillBoxWithMolecule(MoleculeListClass *List, molecule *filler, config &configuration, double distance[NDIM], double RandAtomDisplacement, double RandMolDisplacement, 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);
 void FindNextSuitablePoint(class BoundaryTriangleSet *BaseTriangle, class BoundaryLineSet *BaseLine, atom*& OptCandidate, Vector *OptCandidateCenter, double *ShortestAngle, const double RADIUS, LinkedCell *LC);
-void FindNonConvexBorder(const molecule* const mol, Tesselation *&TesselStruct, const LinkedCell *&LC, const double RADIUS, const char *tempbasename);
+bool FindNonConvexBorder(const molecule* const mol, Tesselation *&TesselStruct, const LinkedCell *&LC, const double RADIUS, const char *tempbasename);
 Boundaries *GetBoundaryPoints(const molecule *mol, Tesselation *&TesselStruct);
 double * GetDiametersOfCluster(const Boundaries *BoundaryPtr, const molecule *mol, Tesselation *&TesselStruct, const bool IsAngstroem);
 void PrepareClustersinWater(config *configuration, molecule *mol, double ClusterVolume, double celldensity);
 bool RemoveAllBoundaryPoints(class Tesselation *&TesselStruct, const molecule * const mol, const char * const filename);
-void StoreTrianglesinFile(const molecule * const mol, const Tesselation *&TesselStruct, const char *filename, const char *extraSuffix);
+void StoreTrianglesinFile(const molecule * const mol, const Tesselation * const TesselStruct, const char *filename, const char *extraSuffix);
 double VolumeOfConvexEnvelope(class Tesselation *TesselStruct, class config *configuration);
 
Index: src/builder.cpp
===================================================================
--- src/builder.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/builder.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -50,4 +50,7 @@
 using namespace std;
 
+#include <cstring>
+
+#include "analysis_bonds.hpp"
 #include "analysis_correlation.hpp"
 #include "atom.hpp"
@@ -65,4 +68,6 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
+#include "version.h"
+#include "World.hpp"
 
 /********************************************* Subsubmenu routine ************************************/
@@ -81,24 +86,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:
-      Log() << Verbose(0) << "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::get()->cell_size, false);
         first->type = periode->AskElement();  // give type
         mol->AddAtom(first);  // add to molecule
@@ -109,11 +114,11 @@
         valid = true;
         do {
-          if (!valid) Log() << Verbose(0) << "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::get()->cell_size, true);
+          cout << Verbose(0) << "Enter relative coordinates." << endl;
+          first->x.AskPosition(World::get()->cell_size, 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
@@ -125,8 +130,8 @@
         valid = true;
         do {
-          if (!valid) Log() << Verbose(0) << "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::get()->cell_size, false);
           for (int i=NDIM;i--;) {
             first->x.x[i] += second->x.x[i];
@@ -142,9 +147,7 @@
         do {
           if (!valid) {
-            Log() << Verbose(0) << "Resulting coordinates out of cell - ";
-            first->x.Output();
-            Log() << Verbose(0) << 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): ");
@@ -157,5 +160,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);
@@ -169,10 +172,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
@@ -182,13 +185,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
@@ -197,5 +200,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);
@@ -203,18 +206,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
@@ -223,5 +226,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
@@ -231,7 +234,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
@@ -246,7 +249,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) {
@@ -263,5 +266,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;
@@ -277,30 +280,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];
       }
@@ -313,7 +316,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];
       }
@@ -336,12 +339,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;
 
@@ -356,6 +359,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::get()->cell_size,0);
       n.Normalize();
       break;
@@ -376,5 +379,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--;) {
@@ -383,13 +386,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);
 };
@@ -404,11 +407,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;
 
@@ -423,6 +426,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::get()->cell_size,0);
       n.Normalize();
       break;
@@ -436,7 +439,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);
 };
@@ -452,11 +455,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;
 
@@ -465,11 +468,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;
@@ -483,9 +486,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;
@@ -517,20 +520,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':
@@ -564,11 +567,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: ");
@@ -579,10 +582,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))
@@ -593,5 +596,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;
@@ -599,5 +602,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);
@@ -610,12 +613,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);
@@ -634,6 +637,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
@@ -641,7 +644,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);
 };
 
@@ -654,5 +657,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
@@ -662,20 +665,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)
-    Log() << Verbose(0) << "WARNING: 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;
 
@@ -684,5 +688,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);
       }
@@ -693,6 +697,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: ");
@@ -701,6 +705,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--;) {
@@ -716,7 +720,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];
@@ -733,5 +737,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);
       }
@@ -742,7 +746,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;
 
@@ -752,14 +789,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;
@@ -782,23 +819,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)
-    Log() << Verbose(0) << "WARNING: 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;
 
@@ -807,8 +844,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;
 
@@ -827,8 +864,8 @@
           }
           if (count != j)
-            Log() << Verbose(0) << "ERROR: 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::get()->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
@@ -853,5 +890,5 @@
             mol->Translate(&x);
           }
-          mol->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor;
+          World::get()->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor;
         }
       }
@@ -866,5 +903,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);
       }
@@ -875,5 +912,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);
       }
@@ -884,5 +921,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);
       }
@@ -895,10 +932,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;
@@ -908,7 +945,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::get()->cell_size,0);
         mol->Center.AddVector((const Vector *)&x);
      }
@@ -937,19 +974,19 @@
   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':
@@ -961,8 +998,8 @@
       {
         char filename[MAXSTRINGSIZE];
-        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);
         mol = new molecule(periode);
         do {
-          Log() << Verbose(0) << "Enter file name: ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter file name: ");
           cin >> filename;
         } while (!mol->AddXYZFile(filename));
@@ -970,10 +1007,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::get()->cell_size;
+        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);
       }
@@ -984,9 +1022,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);
@@ -998,9 +1036,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);
@@ -1013,11 +1051,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));
@@ -1027,5 +1065,5 @@
 
     case 'r':
-      Log() << Verbose(0) << "Enter index of molecule: ";
+      DoLog(0) && (Log() << Verbose(0) << "Enter index of molecule: ");
       cin >> nr;
       count = 1;
@@ -1050,18 +1088,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;
 
@@ -1072,10 +1114,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);
@@ -1087,4 +1129,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':
       {
@@ -1092,10 +1186,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);
@@ -1106,4 +1200,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':
       {
@@ -1111,5 +1215,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);
@@ -1128,5 +1232,5 @@
 
     case 's':
-      Log() << Verbose(0) << "Not implemented yet." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "Not implemented yet." << endl);
       break;
 
@@ -1137,10 +1241,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);
@@ -1171,5 +1275,6 @@
     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;
   }
@@ -1177,5 +1282,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;
@@ -1187,11 +1292,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);
@@ -1199,37 +1304,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 +1353,32 @@
   ofstream output;
   molecule *mol = new molecule(periode);
+  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
@@ -1267,5 +1400,5 @@
   }
 
-  Log() << Verbose(0) << "Storing configuration ... " << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Storing configuration ... " << endl);
   // get correct valence orbitals
   mol->CalculateOrbitals(*configuration);
@@ -1283,9 +1416,9 @@
   output.close();
   output.clear();
-  Log() << Verbose(0) << "Saving of config file ";
+  DoLog(0) && (Log() << Verbose(0) << "Saving of config file ");
   if (configuration->Save(filename, periode, mol))
-    Log() << Verbose(0) << "successful." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "successful." << endl);
   else
-    Log() << Verbose(0) << "failed." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
 
   // and save to xyz file
@@ -1300,15 +1433,15 @@
     output.open(filename, ios::trunc);
   }
-  Log() << Verbose(0) << "Saving of XYZ file ";
+  DoLog(0) && (Log() << Verbose(0) << "Saving of XYZ file ");
   if (mol->MDSteps <= 1) {
     if (mol->OutputXYZ(&output))
-      Log() << Verbose(0) << "successful." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "successful." << endl);
     else
-      Log() << Verbose(0) << "failed." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
   } else {
     if (mol->OutputTrajectoriesXYZ(&output))
-      Log() << Verbose(0) << "successful." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "successful." << endl);
     else
-      Log() << Verbose(0) << "failed." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "failed." << endl);
   }
   output.close();
@@ -1320,13 +1453,14 @@
   if (output == NULL)
     strcpy(filename,"main_pcp_linux");
-  Log() << Verbose(0) << "Saving as mpqc input ";
+  DoLog(0) && (Log() << Verbose(0) << "Saving as mpqc input ");
   if (configuration->SaveMPQC(filename, mol))
-    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);
 
   if (!strcmp(configuration->configpath, configuration->GetDefaultPath())) {
-    eLog() << Verbose(0) << "WARNING: config is found under different path then stated in config file::defaultpath!" << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "config is found under different path then stated in config file::defaultpath!" << endl);
   }
+
   delete(mol);
 };
@@ -1356,7 +1490,9 @@
   enum ConfigStatus configPresent = absent;
   clock_t start,end;
+  double MaxDistance = -1;
   int argptr;
   molecule *mol = NULL;
-  string BondGraphFileName("");
+  string BondGraphFileName("\n");
+  int verbosity = 0;
   strncpy(configuration.databasepath, LocalPath, MAXSTRINGSIZE-1);
 
@@ -1366,5 +1502,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]) {
@@ -1372,51 +1508,82 @@
           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\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/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-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-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/-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;
           case 'v':
+            while (argv[argptr-1][verbosity+1] == 'v') {
+              verbosity++;
+            }
+            setVerbosity(verbosity);
+            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::get()->cell_size;
+              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;
@@ -1425,14 +1592,25 @@
           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':
+            {
+              char **name = &(World::get()->DefaultName);
+              delete[](*name);
+              const int length = strlen(argv[argptr]);
+              *name = new char[length+2];
+              strncpy(*name, argv[argptr], length);
+              DoLog(0) && (Log() << Verbose(0) << "Default name of new molecules set to " << *name << "." << endl);
+            }
             break;
           default:   // no match? Step on
@@ -1446,8 +1624,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;
     }
@@ -1455,5 +1633,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) {
@@ -1461,8 +1639,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;
@@ -1472,18 +1650,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;
        }
@@ -1502,5 +1680,15 @@
        mol = new molecule(periode);
        mol->ActiveFlag = true;
+       if (ConfigFileName != NULL)
+         mol->SetNameFromFilename(ConfigFileName);
        molecules->insert(mol);
+     }
+     if (configuration.BG == NULL) {
+       configuration.BG = new BondGraph(configuration.GetIsAngstroem());
+       if ((!BondGraphFileName.empty()) && (configuration.BG->LoadBondLengthTable(BondGraphFileName))) {
+         DoLog(0) && (Log() << Verbose(0) << "Bond length table loaded successfully." << endl);
+       } else {
+         DoeLog(1) && (eLog()<< Verbose(1) << "Bond length table loading failed." << endl);
+       }
      }
 
@@ -1508,5 +1696,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++;
@@ -1517,12 +1705,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;
                 }
@@ -1533,12 +1722,13 @@
               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] << "), ";
+                DoLog(1) && (Log() << Verbose(1) << "Adding new atom with element " << argv[argptr] << " at (" << argv[argptr+1] << "," << argv[argptr+2] << "," << argv[argptr+3] << "), ");
                 first = new atom;
                 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]);
@@ -1548,5 +1738,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;
               }
@@ -1561,8 +1751,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;
               }
@@ -1571,5 +1762,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];
@@ -1601,22 +1792,287 @@
               //argptr+=1;
               break;
+            case 'I':
+              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);
+              mol = NULL;
+              if (molecules->ListOfMolecules.size() != 0) {
+                for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+                  if ((*ListRunner)->ActiveFlag) {
+                    mol = *ListRunner;
+                    break;
+                  }
+              }
+              if ((mol == NULL) && (!molecules->ListOfMolecules.empty())) {
+                mol = *(molecules->ListOfMolecules.begin());
+                if (mol != NULL)
+                  mol->ActiveFlag = true;
+              }
+              break;
             case 'C':
+              {
+                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]);
+
+                          element *elemental = periode->FindElement((const int) atoi(argv[argptr+1]));
+                          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]);
+
+                          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);
+                          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;
+                  }
+                }
+                break;
+              }
+            case 'E':
               if (ExitFlag == 0) ExitFlag = 1;
-              if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (argv[argptr][0] == '-') || (argv[argptr+1][0] == '-') || (argv[argptr+2][0] == '-')) {
+              if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (argv[argptr+1][0] == '-')) {
                 ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for pair correlation analysis: -C <Z> <output> <bin output>" << endl;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for changing element: -E <atom nr.> <element>" << endl);
+                performCriticalExit();
               } else {
-                SaveFlag = false;
-                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;
+                SaveFlag = true;
+                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]));
+                argptr+=2;
+              }
+              break;
+            case 'F':
+              if (ExitFlag == 0) ExitFlag = 1;
+              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;
+                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;
+                DoLog(1) && (Log() << Verbose(1) << "Filling Box with water molecules." << endl);
+                // construct water molecule
+                molecule *filler = new molecule(periode);
+                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;
+                // call routine
+                double distance[NDIM];
+                for (int i=0;i<NDIM;i++)
+                  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);
+                argptr+=6;
+              }
+              break;
+            case 'A':
+              if (ExitFlag == 0) ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+                ExitFlag =255;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Missing source file for bonds in molecule: -A <bond sourcefile>" << endl);
+                performCriticalExit();
+              } else {
+                DoLog(0) && (Log() << Verbose(0) << "Parsing bonds from " << argv[argptr] << "." << endl);
+                ifstream *input = new ifstream(argv[argptr]);
+                mol->CreateAdjacencyListFromDbondFile(input);
+                input->close();
+                argptr+=1;
+              }
+              break;
+
+            case 'J':
+              if (ExitFlag == 0) ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+                ExitFlag =255;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Missing path of adjacency file: -j <path>" << endl);
+                performCriticalExit();
+              } else {
+                DoLog(0) && (Log() << Verbose(0) << "Storing adjacency to path " << argv[argptr] << "." << endl);
+                configuration.BG->ConstructBondGraph(mol);
+                mol->StoreAdjacencyToFile(NULL, argv[argptr]);
+                argptr+=1;
+              }
+              break;
+
+            case 'j':
+              if (ExitFlag == 0) ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+                ExitFlag =255;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Missing path of bonds file: -j <path>" << endl);
+                performCriticalExit();
+              } else {
+                DoLog(0) && (Log() << Verbose(0) << "Storing bonds to path " << argv[argptr] << "." << endl);
+                configuration.BG->ConstructBondGraph(mol);
+                mol->StoreBondsToFile(NULL, argv[argptr]);
+                argptr+=1;
+              }
+              break;
+
+            case 'N':
+              if (ExitFlag == 0) ExitFlag = 1;
+              if ((argptr+1 >= argc) || (argv[argptr+1][0] == '-')){
+                ExitFlag = 255;
+                DoeLog(0) && (eLog()<< Verbose(0) << "Not enough or invalid arguments given for non-convex envelope: -o <radius> <tecplot output file>" << endl);
+                performCriticalExit();
+              } else {
+                class Tesselation *T = NULL;
                 const LinkedCell *LCList = NULL;
+                molecule * Boundary = NULL;
+                //string filename(argv[argptr+1]);
+                //filename.append(".csv");
+                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;
                 for (MoleculeList::iterator BigFinder = molecules->ListOfMolecules.begin(); BigFinder != molecules->ListOfMolecules.end(); BigFinder++) {
+                  (*BigFinder)->CountAtoms();
                   if ((Boundary == NULL) || (Boundary->AtomCount < (*BigFinder)->AtomCount)) {
                     Boundary = *BigFinder;
@@ -1624,110 +2080,14 @@
                   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 );
-                BinPairMap *binmap = BinData( surfacemap, 0.5, 0., 0. );
-                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;
-            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;
-              } else {
-                SaveFlag = true;
-                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]));
-                argptr+=2;
-              }
-              break;
-            case 'F':
-              if (ExitFlag == 0) ExitFlag = 1;
-              if (argptr+5 >=argc) {
-                ExitFlag = 255;
-                eLog() << Verbose(0) << "Not enough or invalid arguments given for filling box with water: -F <dist_x> <dist_y> <dist_z> <randatom> <randmol> <DoRotate>" << endl;
-              } else {
-                SaveFlag = true;
-                Log() << Verbose(1) << "Filling Box with water molecules." << endl;
-                // construct water molecule
-                molecule *filler = new molecule(periode);;
-                molecule *Filling = NULL;
-                atom *second = NULL, *third = NULL;
-                first = new atom();
-                first->type = periode->FindElement(1);
-                first->x.Init(0.441, -0.143, 0.);
-                filler->AddAtom(first);
-                second = new atom();
-                second->type = periode->FindElement(1);
-                second->x.Init(-0.464, 1.137, 0.0);
-                filler->AddAtom(second);
-                third = new atom();
-                third->type = periode->FindElement(8);
-                third->x.Init(-0.464, 0.177, 0.);
-                filler->AddAtom(third);
-                filler->AddBond(first, third, 1);
-                filler->AddBond(second, third, 1);
-                // call routine
-                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]), atoi(argv[argptr+5]));
-                if (Filling != NULL) {
-                  molecules->insert(Filling);
-                }
-                delete(filler);
-                argptr+=6;
-              }
-              break;
-            case 'A':
-              if (ExitFlag == 0) ExitFlag = 1;
-              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-                ExitFlag =255;
-                eLog() << Verbose(0) << "Missing source file for bonds in molecule: -A <bond sourcefile>" << endl;
-              } else {
-                Log() << Verbose(0) << "Parsing bonds from " << argv[argptr] << "." << endl;
-                ifstream *input = new ifstream(argv[argptr]);
-                mol->CreateAdjacencyListFromDbondFile(input);
-                input->close();
-                argptr+=1;
-              }
-              break;
-            case 'N':
-              if (ExitFlag == 0) ExitFlag = 1;
-              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;
-              } else {
-                class Tesselation *T = NULL;
-                const LinkedCell *LCList = NULL;
-                string filename(argv[argptr+1]);
-                filename.append(".csv");
-                Log() << Verbose(0) << "Evaluating non-convex envelope.";
-                Log() << Verbose(1) << "Using rolling ball of radius " << atof(argv[argptr]) << " and storing tecplot data in " << argv[argptr+1] << "." << endl;
+                DoLog(1) && (Log() << Verbose(1) << "Biggest molecule has " << Boundary->AtomCount << " atoms." << endl);
                 start = clock();
-                LCList = new LinkedCell(mol, atof(argv[argptr])*2.);
-                FindNonConvexBorder(mol, T, LCList, atof(argv[argptr]), argv[argptr+1]);
+                LCList = new LinkedCell(Boundary, atof(argv[argptr])*2.);
+                if (!FindNonConvexBorder(Boundary, T, LCList, atof(argv[argptr]), argv[argptr+1]))
+                  ExitFlag = 255;
                 //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);
                 argptr+=2;
               }
@@ -1737,12 +2097,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);
@@ -1754,14 +2115,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;
               }
@@ -1771,12 +2133,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;
               }
@@ -1786,8 +2149,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]));
@@ -1802,5 +2166,5 @@
                   }
                 } else {
-                  eLog() << Verbose(0) << "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;
@@ -1811,9 +2175,10 @@
               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]);
@@ -1826,9 +2191,10 @@
               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]);
@@ -1841,9 +2207,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]);
@@ -1851,8 +2218,9 @@
                 factor[2] = atof(argv[argptr+2]);
                 mol->Scale((const double ** const)&factor);
+                double * const cell_size = World::get()->cell_size;
                 for (int i=0;i<NDIM;i++) {
                   j += i+1;
                   x.x[i] = atof(argv[NDIM+i]);
-                  mol->cell_size[j]*=factor[i];
+                  cell_size[j]*=factor[i];
                 }
                 delete[](factor);
@@ -1864,11 +2232,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::get()->cell_size;
                 for (int i=0;i<6;i++) {
-                  mol->cell_size[i] = atof(argv[argptr+i]);
+                  cell_size[i] = atof(argv[argptr+i]);
                 }
                 // center
@@ -1881,11 +2251,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::get()->cell_size;
                 for (int i=0;i<6;i++) {
-                  mol->cell_size[i] = atof(argv[argptr+i]);
+                  cell_size[i] = atof(argv[argptr+i]);
                 }
                 // center
@@ -1898,9 +2270,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);
@@ -1908,9 +2281,10 @@
                 mol->SetBoxDimension(&x);
                 // translate each coordinate by boundary
+                double * const cell_size = World::get()->cell_size;
                 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.;
+                  cell_size[j] += x.x[i]*2.;
                 }
                 mol->Translate((const Vector *)&x);
@@ -1921,5 +2295,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);
@@ -1931,8 +2305,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);
@@ -1944,16 +2319,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;
+                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);
                 }
                 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;
               }
@@ -1963,12 +2339,12 @@
               j = atoi(argv[argptr++]);
               if ((j<0) || (j>1)) {
-                eLog() << Verbose(1) << "ERROR: 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;
@@ -1977,11 +2353,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]);
@@ -1990,6 +2367,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);
@@ -2001,9 +2378,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;
-                volume = -1; // for case 'u': don't print error again
+                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':
@@ -2012,12 +2389,13 @@
                 if (volume != -1)
                   ExitFlag = 255;
-                  eLog() << Verbose(0) << "Not enough 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(0) << "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;
                 }
@@ -2025,5 +2403,5 @@
 //                  repetition[i] = atoi(argv[argptr++]);
 //                  if (repetition[i] < 1)
-//                    eLog() << Verbose(0) << "ERROR: repetition value must be greater 1!" << endl;
+//                    DoeLog(1) && (eLog()<< Verbose(1) << "repetition value must be greater 1!" << endl);
 //                  repetition[i] = 1;
 //                }
@@ -2035,7 +2413,9 @@
               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::get()->cell_size;
                 for (int axis = 1; axis <= NDIM; axis++) {
                   int faktor = atoi(argv[argptr++]);
@@ -2044,5 +2424,5 @@
                   Vector ** vectors;
                   if (faktor < 1) {
-                    eLog() << Verbose(0) << "ERROR: Repetition faktor mus be greater than 1!" << endl;
+                    DoeLog(1) && (eLog()<< Verbose(1) << "Repetition factor mus be greater than 1!" << endl);
                     faktor = 1;
                   }
@@ -2061,8 +2441,8 @@
                     }
                     if (count != j)
-                      Log() << Verbose(0) << "ERROR: 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] = 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
@@ -2085,5 +2465,5 @@
                       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;
                   }
                 }
@@ -2102,7 +2482,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");
   }
@@ -2126,5 +2506,10 @@
   int j;
 
-  setVerbosity(2);
+  cout << ESPACKVersion << endl;
+
+  DoLog(1) && (Log() << Verbose(1) << "test" << endl);
+  DoLog(3) && (Log() << Verbose(1) << "test");
+
+  setVerbosity(0);
 
   // =========================== PARSE COMMAND LINE OPTIONS ====================================
@@ -2152,9 +2537,10 @@
   if (molecules->ListOfMolecules.size() == 0) {
     mol = new molecule(periode);
-    if (mol->cell_size[0] == 0.) {
-      Log() << Verbose(0) << "enter lower tridiagonal form of basis matrix" << endl << endl;
+    double * const cell_size = World::get()->cell_size;
+    if (cell_size[0] == 0.) {
+      DoLog(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];
+        DoLog(1) && (Log() << Verbose(1) << "Cell size" << i << ": ");
+        cin >> cell_size[i];
       }
     }
@@ -2166,23 +2552,23 @@
 
   // now the main construction loop
-  Log() << Verbose(0) << endl << "Now comes the real construction..." << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl << "Now comes the real construction..." << endl);
   do {
-    Log() << Verbose(0) << endl << endl;
-    Log() << Verbose(0) << "============Molecule list=======================" << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl << endl);
+    DoLog(0) && (Log() << Verbose(0) << "============Molecule list=======================" << endl);
     molecules->Enumerate((ofstream *)&cout);
-    Log() << Verbose(0) << "============Menu===============================" << endl;
-    Log() << Verbose(0) << "a - set molecule (in)active" << endl;
-    Log() << Verbose(0) << "e - edit molecules (load, parse, save)" << endl;
-    Log() << Verbose(0) << "g - globally manipulate atoms in molecule" << endl;
-    Log() << Verbose(0) << "M - Merge molecules" << endl;
-    Log() << Verbose(0) << "m - manipulate atoms" << endl;
-    Log() << Verbose(0) << "-----------------------------------------------" << endl;
-    Log() << Verbose(0) << "c - edit the current configuration" << endl;
-    Log() << Verbose(0) << "-----------------------------------------------" << endl;
-    Log() << Verbose(0) << "s - save current setup to config file" << endl;
-    Log() << Verbose(0) << "T - call the current test routine" << endl;
-    Log() << Verbose(0) << "q - quit" << endl;
-    Log() << Verbose(0) << "===============================================" << endl;
-    Log() << Verbose(0) << "Input: ";
+    DoLog(0) && (Log() << Verbose(0) << "============Menu===============================" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "a - set molecule (in)active" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "e - edit molecules (load, parse, save)" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "g - globally manipulate atoms in molecule" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "M - Merge molecules" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "m - manipulate atoms" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "-----------------------------------------------" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "c - edit the current configuration" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "-----------------------------------------------" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "s - save current setup to config file" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "T - call the current test routine" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "q - quit" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "===============================================" << endl);
+    DoLog(0) && (Log() << Verbose(0) << "Input: ");
     cin >> choice;
 
@@ -2190,5 +2576,5 @@
       case 'a':  // (in)activate molecule
         {
-          Log() << Verbose(0) << "Enter index of molecule: ";
+          DoLog(0) && (Log() << Verbose(0) << "Enter index of molecule: ");
           cin >> j;
           for(MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
@@ -2236,7 +2622,7 @@
   // save element data base
   if (periode->StorePeriodentafel(configuration->databasepath)) //ElementsFileName
-    Log() << Verbose(0) << "Saving of elements.db successful." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Saving of elements.db successful." << endl);
   else
-    Log() << Verbose(0) << "Saving of elements.db failed." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Saving of elements.db failed." << endl);
 
   delete(molecules); // also free's all molecules contained
Index: src/config.cpp
===================================================================
--- src/config.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/config.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -5,5 +5,9 @@
  */
 
+#include <stdio.h>
+#include <cstring>
+
 #include "atom.hpp"
+#include "bond.hpp"
 #include "config.hpp"
 #include "element.hpp"
@@ -15,4 +19,5 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
+#include "World.hpp"
 
 /******************************** Functions for class ConfigFileBuffer **********************/
@@ -24,5 +29,5 @@
     char number1[8];
     char number2[8];
-    char *dummy1, *dummy2;
+    const char *dummy1, *dummy2;
     //Log() << Verbose(0) << s1 << "  " << s2 << endl;
     dummy1 = strchr(s1, '_')+sizeof(char)*5;  // go just after "Ion_Type"
@@ -69,5 +74,5 @@
   file= new ifstream(filename);
   if (file == NULL) {
-    eLog() << Verbose(0) << "ERROR: config file " << filename << " missing!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "config file " << filename << " missing!" << endl);
     return;
   }
@@ -80,9 +85,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(0) << "ERROR: FileBuffer->buffer is not NULL!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "FileBuffer->buffer is not NULL!" << endl);
     return;
   } else
@@ -100,5 +105,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
@@ -137,7 +142,8 @@
 void ConfigFileBuffer::MapIonTypesInBuffer(const int NoAtoms)
 {
-  map<const char *, int, IonTypeCompare> LineList;
+  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;
   }
@@ -145,14 +151,16 @@
   // put all into hashed map
   for (int i=0; i<NoAtoms; ++i) {
-    LineList.insert(pair<const char *, int> (buffer[CurrentLine+i], CurrentLine+i));
+    IonTypeLineMap.insert(pair<const char *, int> (buffer[CurrentLine+i], CurrentLine+i));
   }
 
   // fill map
   int nr=0;
-  for (map<const char *, int, IonTypeCompare>::iterator runner = LineList.begin(); runner != LineList.end(); ++runner) {
+  for (map<const char *, int, IonTypeCompare>::iterator runner = IonTypeLineMap.begin(); runner != IonTypeLineMap.end(); ++runner) {
     if (CurrentLine+nr < NoLines)
       LineMapping[CurrentLine+(nr++)] = runner->second;
-    else
-      eLog() << Verbose(0) << "config::MapIonTypesInBuffer - NoAtoms is wrong: We are past the end of the file!" << endl;
+    else {
+      DoeLog(0) && (eLog()<< Verbose(0) << "config::MapIonTypesInBuffer - NoAtoms is wrong: We are past the end of the file!" << endl);
+      performCriticalExit();
+    }
   }
 }
@@ -200,4 +208,7 @@
     Free(&ThermostatNames[j]);
   Free(&ThermostatNames);
+
+  if (BG != NULL)
+    delete(BG);
 };
 
@@ -239,5 +250,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;
       }
@@ -247,5 +258,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;
       }
@@ -255,5 +266,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;
       }
@@ -263,10 +274,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;
       }
@@ -276,5 +287,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;
       }
@@ -285,14 +296,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;
   }
@@ -310,178 +321,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;
@@ -489,73 +500,74 @@
 //        case 'j': // BoxLength
 //          Log() << Verbose(0) << "enter lower triadiagonalo form of basis matrix" << endl << endl;
+//          double * const cell_size = World::get()->cell_size;
 //          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;
@@ -636,5 +648,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);
 };
@@ -647,5 +659,5 @@
 {
   if (FileBuffer != NULL) {
-    eLog() << Verbose(1) << "WARNING: deleting present FileBuffer in PrepareFileBuffer()." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "deleting present FileBuffer in PrepareFileBuffer()." << endl);
     delete(FileBuffer);
   }
@@ -673,5 +685,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();
   }
@@ -679,8 +691,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;
+    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++) {
@@ -689,5 +702,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];
     }
@@ -697,5 +710,6 @@
     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;
     }
@@ -714,5 +728,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);
@@ -780,5 +794,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;
@@ -792,5 +806,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++) {
@@ -841,5 +855,5 @@
   ifstream *file = new ifstream(filename);
   if (file == NULL) {
-    eLog() << Verbose(0) << "ERROR: config file " << filename << " missing!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "config file " << filename << " missing!" << endl);
     return;
   }
@@ -953,10 +967,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::get()->cell_size;
+  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");
 
@@ -1045,18 +1060,23 @@
 
   // 2. parse the bond graph file if given
-  BG = new BondGraph(IsAngstroem);
-  if (BG->LoadBondLengthTable(BondGraphFileName)) {
-    Log() << Verbose(0) << "Bond length table loaded successfully." << endl;
-  } else {
-    Log() << Verbose(0) << "Bond length table loading failed." << endl;
+  if (BG == NULL) {
+    BG = new BondGraph(IsAngstroem);
+    if (BG->LoadBondLengthTable(BondGraphFileName)) {
+      DoLog(0) && (Log() << Verbose(0) << "Bond length table loaded successfully." << endl);
+    } else {
+      DoeLog(1) && (eLog()<< Verbose(1) << "Bond length table loading failed." << endl);
+    }
   }
 
   // 3. parse the molecule in
   LoadMolecule(mol, FileBuffer, periode, FastParsing);
+  mol->SetNameFromFilename(filename);
   mol->ActiveFlag = true;
   MolList->insert(mol);
 
   // 4. dissect the molecule into connected subgraphs
-  BG->ConstructBondGraph(mol);
+  // don't do this here ...
+  //MolList->DissectMoleculeIntoConnectedSubgraphs(mol,this);
+  //delete(mol);
 
   delete(FileBuffer);
@@ -1074,5 +1094,5 @@
   ifstream *file = new ifstream(filename);
   if (file == NULL) {
-    eLog() << Verbose(0) << "ERROR: config file " << filename << " missing!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "config file " << filename << " missing!" << endl);
     return;
   }
@@ -1152,10 +1172,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::get()->cell_size;
+  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;
@@ -1233,7 +1254,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);
   }
 
@@ -1242,10 +1263,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 ++;
     }
@@ -1261,8 +1282,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 {
@@ -1295,4 +1316,5 @@
   // bring MaxTypes up to date
   mol->CountElements();
+  const double * const cell_size = World::get()->cell_size;
   ofstream * const output = new ofstream(filename, ios::out);
   if (output != NULL) {
@@ -1365,7 +1387,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;
@@ -1410,6 +1432,8 @@
     delete(output);
     return result;
-  } else
+  } else {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open output file:" << filename << endl);
     return false;
+  }
 };
 
@@ -1430,4 +1454,9 @@
     *fname << filename << ".in";
     output = new ofstream(fname->str().c_str(), ios::out);
+    if (output == NULL) {
+      DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open mpqc output file:" << fname << endl);
+      delete(fname);
+      return false;
+    }
     *output << "% Created by MoleCuilder" << endl;
     *output << "mpqc: (" << endl;
@@ -1468,4 +1497,9 @@
     *fname << filename << ".hess.in";
     output = new ofstream(fname->str().c_str(), ios::out);
+    if (output == NULL) {
+      DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open mpqc hessian output file:" << fname << endl);
+      delete(fname);
+      return false;
+    }
     *output << "% Created by MoleCuilder" << endl;
     *output << "mpqc: (" << endl;
@@ -1499,4 +1533,251 @@
     delete(fname);
   }
+
+  return true;
+};
+
+/** Stores all atoms from all molecules in a PDB input file.
+ * Note that this format cannot be parsed again.
+ * \param *filename name of file (without ".in" suffix!)
+ * \param *MolList pointer to MoleculeListClass containing all atoms
+ */
+bool config::SavePDB(const char * const filename, const MoleculeListClass * const MolList) const
+{
+  int AtomNo = -1;
+  int MolNo = 0;
+  atom *Walker = NULL;
+  FILE *f = NULL;
+
+  char name[MAXSTRINGSIZE];
+  strncpy(name, filename, MAXSTRINGSIZE-1);
+  strncat(name, ".pdb", MAXSTRINGSIZE-(strlen(name)+1));
+  f = fopen(name, "w" );
+  if (f == NULL) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open pdb output file:" << name << endl);
+    return false;
+  }
+  fprintf(f, "# Created by MoleCuilder\n");
+
+  for (MoleculeList::const_iterator Runner = MolList->ListOfMolecules.begin(); Runner != MolList->ListOfMolecules.end(); Runner++) {
+    Walker = (*Runner)->start;
+    int *elementNo = Calloc<int>(MAX_ELEMENTS, "config::SavePDB - elementNo");
+    AtomNo = 0;
+    while (Walker->next != (*Runner)->end) {
+      Walker = Walker->next;
+      sprintf(name, "%2s%2d",Walker->type->symbol, elementNo[Walker->type->Z]);
+      elementNo[Walker->type->Z] = (elementNo[Walker->type->Z]+1) % 100;   // confine to two digits
+      fprintf(f,
+             "ATOM %6u %-4s %4s%c%4u    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s%2s\n",
+             Walker->nr,                /* atom serial number */
+             name,         /* atom name */
+             (*Runner)->name,      /* residue name */
+             '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 */
+             (double)Walker->type->Valence,         /* occupancy */
+             (double)Walker->type->NoValenceOrbitals,          /* temperature factor */
+             "0",            /* segment identifier */
+             Walker->type->symbol,    /* element symbol */
+             "0");           /* charge */
+      AtomNo++;
+    }
+    Free(&elementNo);
+    MolNo++;
+  }
+  fclose(f);
+
+  return true;
+};
+
+/** Stores all atoms in a PDB input file.
+ * Note that this format cannot be parsed again.
+ * \param *filename name of file (without ".in" suffix!)
+ * \param *mol pointer to molecule
+ */
+bool config::SavePDB(const char * const filename, const molecule * const mol) const
+{
+  int AtomNo = -1;
+  atom *Walker = NULL;
+  FILE *f = NULL;
+
+  int *elementNo = Calloc<int>(MAX_ELEMENTS, "config::SavePDB - elementNo");
+  char name[MAXSTRINGSIZE];
+  strncpy(name, filename, MAXSTRINGSIZE-1);
+  strncat(name, ".pdb", MAXSTRINGSIZE-(strlen(name)+1));
+  f = fopen(name, "w" );
+  if (f == NULL) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open pdb output file:" << name << endl);
+    Free(&elementNo);
+    return false;
+  }
+  fprintf(f, "# Created by MoleCuilder\n");
+
+  Walker = mol->start;
+  AtomNo = 0;
+  while (Walker->next != mol->end) {
+    Walker = Walker->next;
+    sprintf(name, "%2s%2d",Walker->type->symbol, elementNo[Walker->type->Z]);
+    elementNo[Walker->type->Z] = (elementNo[Walker->type->Z]+1) % 100;   // confine to two digits
+    fprintf(f,
+           "ATOM %6u %-4s %4s%c%4u    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s%2s\n",
+           Walker->nr,                /* atom serial number */
+           name,         /* atom name */
+           mol->name,      /* residue name */
+           '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 */
+           (double)Walker->type->Valence,         /* occupancy */
+           (double)Walker->type->NoValenceOrbitals,          /* temperature factor */
+           "0",            /* segment identifier */
+           Walker->type->symbol,    /* element symbol */
+           "0");           /* charge */
+    AtomNo++;
+  }
+  fclose(f);
+  Free(&elementNo);
+
+  return true;
+};
+
+/** 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
+ */
+bool config::SaveTREMOLO(const char * const filename, const molecule * const mol) const
+{
+  atom *Walker = NULL;
+  ofstream *output = NULL;
+  stringstream * const fname = new stringstream;
+
+  *fname << filename << ".data";
+  output = new ofstream(fname->str().c_str(), ios::out);
+  if (output == NULL) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open tremolo output file:" << fname << endl);
+    delete(fname);
+    return false;
+  }
+
+  // scan maximum number of neighbours
+  Walker = mol->start;
+  int MaxNeighbours = 0;
+  while (Walker->next != mol->end) {
+    Walker = Walker->next;
+    const int count = Walker->ListOfBonds.size();
+    if (MaxNeighbours < count)
+      MaxNeighbours = count;
+  }
+  *output << "# ATOMDATA Id name resName resSeq x=3 charge type neighbors=" << MaxNeighbours << endl;
+
+  Walker = mol->start;
+  while (Walker->next != mol->end) {
+    Walker = Walker->next;
+    *output << Walker->nr << "\t";
+    *output << Walker->Name << "\t";
+    *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->type->symbol << "\t";
+    for (BondList::iterator runner = Walker->ListOfBonds.begin(); runner != Walker->ListOfBonds.end(); runner++)
+      *output << (*runner)->GetOtherAtom(Walker)->nr << "\t";
+    for(int i=Walker->ListOfBonds.size(); i < MaxNeighbours; i++)
+      *output << "-\t";
+    *output << endl;
+  }
+  output->flush();
+  output->close();
+  delete(output);
+  delete(fname);
+
+  return true;
+};
+
+/** 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
+ */
+bool config::SaveTREMOLO(const char * const filename, const MoleculeListClass * const MolList) const
+{
+  atom *Walker = NULL;
+  ofstream *output = NULL;
+  stringstream * const fname = new stringstream;
+
+  *fname << filename << ".data";
+  output = new ofstream(fname->str().c_str(), ios::out);
+  if (output == NULL) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open tremolo output file:" << fname << endl);
+    delete(fname);
+    return false;
+  }
+
+  // scan maximum number of neighbours
+  int MaxNeighbours = 0;
+  for (MoleculeList::const_iterator MolWalker = MolList->ListOfMolecules.begin(); MolWalker != MolList->ListOfMolecules.end(); MolWalker++) {
+    Walker = (*MolWalker)->start;
+    while (Walker->next != (*MolWalker)->end) {
+      Walker = Walker->next;
+      const int count = Walker->ListOfBonds.size();
+      if (MaxNeighbours < count)
+        MaxNeighbours = count;
+    }
+  }
+  *output << "# ATOMDATA Id name resName resSeq x=3 charge type neighbors=" << MaxNeighbours << endl;
+
+  // create global to local id map
+  int **LocalNotoGlobalNoMap = Calloc<int *>(MolList->ListOfMolecules.size(), "config::SaveTREMOLO - **LocalNotoGlobalNoMap");
+  {
+    int MolCounter = 0;
+    int AtomNo = 0;
+    for (MoleculeList::const_iterator MolWalker = MolList->ListOfMolecules.begin(); MolWalker != MolList->ListOfMolecules.end(); MolWalker++) {
+      LocalNotoGlobalNoMap[MolCounter] = Calloc<int>(MolList->CountAllAtoms(), "config::SaveTREMOLO - *LocalNotoGlobalNoMap[]");
+
+      (*MolWalker)->SetIndexedArrayForEachAtomTo( LocalNotoGlobalNoMap[MolCounter], &atom::nr, IncrementalAbsoluteValue, &AtomNo);
+
+      MolCounter++;
+    }
+  }
+
+  // write the file
+  {
+    int MolCounter = 0;
+    int AtomNo = 0;
+    for (MoleculeList::const_iterator MolWalker = MolList->ListOfMolecules.begin(); MolWalker != MolList->ListOfMolecules.end(); MolWalker++) {
+      Walker = (*MolWalker)->start;
+      while (Walker->next != (*MolWalker)->end) {
+        Walker = Walker->next;
+        *output << AtomNo+1 << "\t";
+        *output << Walker->Name << "\t";
+        *output << (*MolWalker)->name << "\t";
+        *output << MolCounter+1 << "\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->type->symbol << "\t";
+        for (BondList::iterator runner = Walker->ListOfBonds.begin(); runner != Walker->ListOfBonds.end(); runner++)
+          *output << LocalNotoGlobalNoMap[MolCounter][ (*runner)->GetOtherAtom(Walker)->nr ]+1 << "\t";
+        for(int i=Walker->ListOfBonds.size(); i < MaxNeighbours; i++)
+          *output << "-\t";
+        *output << endl;
+        AtomNo++;
+      }
+      MolCounter++;
+    }
+  }
+
+  // store & free
+  output->flush();
+  output->close();
+  delete(output);
+  delete(fname);
+  for(size_t i=0;i<MolList->ListOfMolecules.size(); i++)
+    Free(&LocalNotoGlobalNoMap[i]);
+  Free(&LocalNotoGlobalNoMap);
 
   return true;
@@ -1850,5 +2131,5 @@
               }
               line++;
-            } while (dummy1 != NULL && (dummy1[0] == '#') || (dummy1[0] == '\n'));
+            } while ((dummy1 != NULL) && ((dummy1[0] == '#') || (dummy1[0] == '\n')));
             dummy = dummy1;
           } else { // simple int, strings or doubles start in the same line
Index: src/config.hpp
===================================================================
--- src/config.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/config.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -10,6 +10,4 @@
 
 using namespace std;
-
-class MoleculeListClass;
 
 /*********************************************** includes ***********************************/
@@ -27,4 +25,5 @@
 
 class molecule;
+class MoleculeListClass;
 class periodentafel;
 
@@ -142,4 +141,9 @@
   bool Save(const char * const filename, const periodentafel * const periode, molecule * const mol) const;
   bool SaveMPQC(const char * const filename, const molecule * const mol) const;
+  bool SavePDB(const char * const filename, const MoleculeListClass * const MolList) const;
+  bool SavePDB(const char * const filename, const molecule * const mol) const;
+  bool SaveTREMOLO(const char * const filename, const molecule * const mol) const;
+  bool SaveTREMOLO(const char * const filename, const MoleculeListClass * const MolList) const;
+
   void Edit();
   bool GetIsAngstroem() const;
Index: src/datacreator.cpp
===================================================================
--- src/datacreator.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/datacreator.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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;
Index: src/defs.hpp
===================================================================
--- src/defs.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/defs.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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)
Index: src/ellipsoid.cpp
===================================================================
--- src/ellipsoid.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/ellipsoid.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -146,5 +146,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;
@@ -199,5 +199,5 @@
           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 +209,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 +235,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 +241,5 @@
     x = new Vector[PointsToPick];
   } else {
-    eLog() << Verbose(2) << "WARNING: 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 +247,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 +268,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 +293,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,8 +300,8 @@
 //            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;
+                DoLog(2) && (Log() << Verbose(2) << "Current picked node is " << **Runner << " with index " << index << "." << endl);
                 x[PointsPicked++].CopyVector(Candidate->node);    // we have one more atom picked
                 current++;    // next pre-picked atom
@@ -313,12 +313,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 +335,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 +341,5 @@
     x = new Vector[PointsToPick];
   } else {
-    eLog() << Verbose(2) << "WARNING: Given pointer to vector array seems already allocated." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "Given pointer to vector array seems already allocated." << endl);
   }
 
@@ -358,9 +358,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,5 +382,5 @@
   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
@@ -389,5 +389,5 @@
     Center.AddVector(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 +397,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;
@@ -423,5 +423,5 @@
     // 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";
@@ -434,5 +434,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 +442,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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/errorlogger.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -81,7 +81,21 @@
   int verbosityLevel = l.verbosity;
   l.nix->clear();
-  if (v.DoOutput(verbosityLevel))
+  if (v.DoErrorOutput(verbosityLevel)) {
+    switch(v.Verbosity) {
+      case 0:
+        cerr << "CRITICAL: ";
+        break;
+      case 1:
+        cerr << "ERROR: ";
+        break;
+      case 2:
+        cerr << "WARNING: ";
+        break;
+      default:
+        break;
+    }
+    v.print(cerr);
     return cerr;
-  else
+  } else
     return *l.nix;
 };
@@ -90,7 +104,20 @@
   int verbosityLevel = l->verbosity;
   l->nix->clear();
-  if (v.DoOutput(verbosityLevel))
+  if (v.DoErrorOutput(verbosityLevel)) {
+    switch(v.Verbosity) {
+      case 0:
+        cerr << "CRITICAL: ";
+        break;
+      case 1:
+        cerr << "ERROR: ";
+        break;
+      case 2:
+      default:
+        cerr << "WARNING: ";
+        break;
+    }
+    v.print(cerr);
     return cerr;
-  else
+  } else
     return *l->nix;
 };
Index: src/graph.cpp
===================================================================
--- src/graph.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/graph.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/gslmatrix.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,245 @@
+/*
+ * gslmatrix.cpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+using namespace std;
+
+#include "gslmatrix.hpp"
+#include "helpers.hpp"
+
+#include <cassert>
+#include <gsl/gsl_linalg.h>
+
+/** Constructor of class GSLMatrix.
+ * Allocates GSL structures
+ * \param m dimension of matrix
+ */
+GSLMatrix::GSLMatrix(size_t m, size_t n) : rows(m), columns(n)
+{
+  matrix = gsl_matrix_calloc(rows, columns);
+};
+
+/** Copy constructor of class GSLMatrix.
+ * Allocates GSL structures and copies components from \a *src.
+ * \param *src source matrix
+ */
+GSLMatrix::GSLMatrix(const GSLMatrix * const src) : rows(src->rows), columns(src->columns)
+{
+  matrix = gsl_matrix_alloc(rows, columns);
+  gsl_matrix_memcpy (matrix, src->matrix);
+};
+
+/** Destructor of class GSLMatrix.
+ * Frees GSL structures
+ */
+GSLMatrix::~GSLMatrix()
+{
+  gsl_matrix_free(matrix);
+  rows = 0;
+  columns = 0;
+};
+
+/** Assignment operator.
+ * \param &rhs right hand side
+ * \return object itself
+ */
+GSLMatrix& GSLMatrix::operator=(const GSLMatrix& rhs)
+{
+  if (this == &rhs)   // not necessary here, but identity assignment check is generally a good idea
+    return *this;
+  assert(rows == rhs.rows && columns == rhs.columns && "Number of rows and columns do not match!");
+
+  gsl_matrix_memcpy (matrix, rhs.matrix);
+
+  return *this;
+};
+
+/* ============================ Accessing =============================== */
+/** This function sets the matrix from a double array.
+ * Creates a matrix view of the array and performs a memcopy.
+ * \param *x array of values (no dimension check is performed)
+ */
+void GSLMatrix::SetFromDoubleArray(double * x)
+{
+  gsl_matrix_view m = gsl_matrix_view_array (x, rows, columns);
+  gsl_matrix_memcpy (matrix, &m.matrix);
+};
+
+/** This function returns the i-th element of a matrix.
+ * If \a m or \a n lies outside the allowed range of 0 to GSLMatrix::dimension-1 then the error handler is invoked and 0 is returned.
+ * \param m row index
+ * \param n colum index
+ * \return (m,n)-th element of matrix
+ */
+double GSLMatrix::Get(size_t m, size_t n)
+{
+  return gsl_matrix_get (matrix, m, n);
+};
+
+/** This function sets the value of the \a m -th element of a matrix to \a x.
+ *  If \a m or \a n lies outside the allowed range of 0 to GSLMatrix::dimension-1 then the error handler is invoked.
+ * \param m row index
+ * \param m column index
+ * \param x value to set element (m,n) to
+ */
+void GSLMatrix::Set(size_t m, size_t n, double x)
+{
+  gsl_matrix_set (matrix, m, n, x);
+};
+
+/** These functions return a pointer to the \a m-th element of a matrix.
+ *  If \a m or \a n lies outside the allowed range of 0 to GSLMatrix::dimension-1 then the error handler is invoked and a null pointer is returned.
+ * \param m index
+ * \return pointer to \a m-th element
+ */
+double *GSLMatrix::Pointer(size_t m, size_t n)
+{
+  return gsl_matrix_ptr (matrix, m, n);
+};
+
+/** These functions return a constant pointer to the \a m-th element of a matrix.
+ *  If \a m or \a n lies outside the allowed range of 0 to GSLMatrix::dimension-1 then the error handler is invoked and a null pointer is returned.
+ * \param m index
+ * \return const pointer to \a m-th element
+ */
+const double *GSLMatrix::const_Pointer(size_t m, size_t n)
+{
+  return gsl_matrix_const_ptr (matrix, m, n);
+};
+
+/* ========================== Initializing =============================== */
+/** This function sets all the elements of the matrix to the value \a x.
+ * \param *x
+ */
+void GSLMatrix::SetAll(double x)
+{
+  gsl_matrix_set_all (matrix, x);
+};
+
+/** This function sets all the elements of the matrix to zero.
+ */
+void GSLMatrix::SetZero()
+{
+  gsl_matrix_set_zero (matrix);
+};
+
+/** This function sets the elements of the matrix to the corresponding elements of the identity matrix, \f$m(i,j) = \delta(i,j)\f$, i.e. a unit diagonal with all off-diagonal elements zero.
+ * This applies to both square and rectangular matrices.
+ */
+void GSLMatrix::SetIdentity()
+{
+  gsl_matrix_set_identity (matrix);
+};
+
+/* ====================== Exchanging elements ============================ */
+/** This function exchanges the \a i-th and \a j-th row of the matrix in-place.
+ * \param i i-th row to swap with ...
+ * \param j ... j-th row to swap against
+ */
+bool GSLMatrix::SwapRows(size_t i, size_t j)
+{
+  return (gsl_matrix_swap_rows (matrix, i, j) == GSL_SUCCESS);
+};
+
+/** This function exchanges the \a i-th and \a j-th column of the matrix in-place.
+ * \param i i-th column to swap with ...
+ * \param j ... j-th column to swap against
+ */
+bool GSLMatrix::SwapColumns(size_t i, size_t j)
+{
+  return (gsl_matrix_swap_columns (matrix, i, j) == GSL_SUCCESS);
+};
+
+/** This function exchanges the \a i-th row and \a j-th column of the matrix in-place.
+ * The matrix must be square for this operation to be possible.
+ * \param i i-th row to swap with ...
+ * \param j ... j-th column to swap against
+ */
+bool GSLMatrix::SwapRowColumn(size_t i, size_t j)
+{
+  assert (rows == columns && "The matrix must be square for swapping row against column to be possible.");
+  return (gsl_matrix_swap_rowcol (matrix, i, j) == GSL_SUCCESS);
+};
+
+/** This function transposes the matrix.
+ * Note that the function is extended to the non-square case, where the matrix is re-allocated and copied.
+ */
+bool GSLMatrix::Transpose()
+{
+  if (rows == columns)// if square, use GSL
+    return (gsl_matrix_transpose (matrix) == GSL_SUCCESS);
+  else { // otherwise we have to copy a bit
+    gsl_matrix *dest = gsl_matrix_alloc(columns, rows);
+    for (size_t i=0;i<rows; i++)
+      for (size_t j=0;j<columns;j++) {
+        gsl_matrix_set(dest, j,i, gsl_matrix_get(matrix, i,j) );
+      }
+    delete(matrix);
+    matrix = dest;
+    flip(rows, columns);
+    return true;
+  }
+};
+
+/* ============================ Properties ============================== */
+/** Checks whether matrix' elements are strictly null.
+ * \return true - is null, false - else
+ */
+bool GSLMatrix::IsNull()
+{
+  return gsl_matrix_isnull (matrix);
+};
+
+/** Checks whether matrix' elements are strictly positive.
+ * \return true - is positive, false - else
+ */
+bool GSLMatrix::IsPositive()
+{
+  return gsl_matrix_ispos (matrix);
+};
+
+/** Checks whether matrix' elements are strictly negative.
+ * \return true - is negative, false - else
+ */
+bool GSLMatrix::IsNegative()
+{
+  return gsl_matrix_isneg (matrix);
+};
+
+/** Checks whether matrix' elements are strictly non-negative.
+ * \return true - is non-negative, false - else
+ */
+bool GSLMatrix::IsNonNegative()
+{
+  return gsl_matrix_isnonneg (matrix);
+};
+
+/** This function performs a Cholesky decomposition to determine whether matrix is positive definite.
+ * We check whether GSL returns GSL_EDOM as error, indicating that decomposition failed due to matrix not being positive-definite.
+ * \return true - matrix is positive-definite, false - else
+ */
+bool GSLMatrix::IsPositiveDefinite()
+{
+  if (rows != columns)  // only possible for square matrices.
+    return false;
+  else
+    return (gsl_linalg_cholesky_decomp (matrix) != GSL_EDOM);
+};
+
+
+/** Calculates the determinant of the matrix.
+ * if matrix is square, uses LU decomposition.
+ */
+double GSLMatrix::Determinant()
+{
+  int signum = 0;
+  assert (rows == columns && "Determinant can only be calculated for square matrices.");
+  gsl_permutation *p = gsl_permutation_alloc(rows);
+  gsl_linalg_LU_decomp(matrix, p, &signum);
+  gsl_permutation_free(p);
+  return gsl_linalg_LU_det(matrix, signum); 
+};
+
Index: src/gslmatrix.hpp
===================================================================
--- src/gslmatrix.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/gslmatrix.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,70 @@
+/*
+ * gslmatrix.hpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+#ifndef GSLMATRIX_HPP_
+#define GSLMATRIX_HPP_
+
+using namespace std;
+
+/*********************************************** includes ***********************************/
+
+// include config.h
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <gsl/gsl_matrix.h>
+
+/****************************************** forward declarations *****************************/
+
+class GSLMatrix;
+
+/********************************************** declarations *******************************/
+
+class GSLMatrix {
+  friend class LinearSystemOfEquations;
+
+public:
+  GSLMatrix(size_t m, size_t n);
+  GSLMatrix(const GSLMatrix * const src);
+  ~GSLMatrix();
+
+  // Accessing
+  void SetFromDoubleArray(double * x);
+  double Get(size_t m, size_t n);
+  void Set(size_t m, size_t n, double x);
+  double *Pointer(size_t m, size_t n);
+  const double *const_Pointer(size_t m, size_t n);
+
+  // Initializing
+  void SetAll(double x);
+  void SetZero();
+  void SetIdentity();
+
+  // Exchanging elements
+  bool SwapRows(size_t i, size_t j);
+  bool SwapColumns(size_t i, size_t j);
+  bool SwapRowColumn(size_t i, size_t j);
+  bool Transpose();
+  bool IsNull();
+  bool IsPositive();
+  bool IsNegative();
+  bool IsNonNegative();
+  bool IsPositiveDefinite();
+  double Determinant();
+
+  GSLMatrix& operator=(const GSLMatrix& rhs);
+
+private:
+  gsl_matrix *matrix;
+
+  size_t rows;
+  size_t columns;
+};
+
+
+#endif /* GSLMATRIX_HPP_ */
Index: src/gslvector.cpp
===================================================================
--- src/gslvector.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/gslvector.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,293 @@
+/*
+ * gslvector.cpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+#include <cassert>
+#include <cmath>
+
+#include "gslvector.hpp"
+#include "defs.hpp"
+
+/** Constructor of class GSLVector.
+ * Allocates GSL structures
+ * \param m dimension of vector
+ */
+GSLVector::GSLVector(size_t m) : dimension(m)
+{
+  vector = gsl_vector_calloc(dimension);
+};
+
+/** Copy constructor of class GSLVector.
+ * Allocates GSL structures and copies components from \a *src.
+ * \param *src source vector
+ */
+GSLVector::GSLVector(const GSLVector * const src) : dimension(src->dimension)
+{
+  vector = gsl_vector_alloc(dimension);
+  gsl_vector_memcpy (vector, src->vector);
+};
+
+/** 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
+ */
+GSLVector::~GSLVector()
+{
+  gsl_vector_free(vector);
+};
+
+/* ============================ Accessing =============================== */
+/** This function sets the vector from a double array.
+ * Creates a vector view of the array and performs a memcopy.
+ * \param *x array of values (no dimension check is performed)
+ */
+void GSLVector::SetFromDoubleArray(double * x)
+{
+  gsl_vector_view m = gsl_vector_view_array (x, dimension);
+  gsl_vector_memcpy (vector, &m.vector);
+};
+
+/** This function returns the i-th element of a vector.
+ * If \a m lies outside the allowed range of 0 to GSLVector::dimension-1 then the error handler is invoked and 0 is returned.
+ * \param m m-th element
+ * \return  m-th element of vector
+ */
+double GSLVector::Get(size_t m) const
+{
+  return gsl_vector_get (vector, m);
+};
+
+/** This function sets the value of the \a m -th element of a vector to \a x.
+ *  If \a m lies outside the allowed range of 0 to GSLVector::dimension-1 then the error handler is invoked.
+ * \param m-th element to set
+ * \param x value to set to
+ */
+void GSLVector::Set(size_t m, double x)
+{
+  gsl_vector_set (vector, m, x);
+};
+
+/** These functions return a pointer to the \a m-th element of a vector.
+ *  If \a m lies outside the allowed range of 0 to GSLVector::dimension-1 then the error handler is invoked and a null pointer is returned.
+ * \param m m-th element
+ * \return pointer to \a m-th element
+ */
+double *GSLVector::Pointer(size_t m) const
+{
+  return gsl_vector_ptr (vector, m);
+};
+
+/** These functions return a constant pointer to the \a m-th element of a vector.
+ *  If \a m lies outside the allowed range of 0 to GSLVector::dimension-1 then the error handler is invoked and a null pointer is returned.
+ * \param m m-th element
+ * \return const pointer to \a m-th element
+ */
+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;
+};
+
+/* ========================== Initializing =============================== */
+/** This function sets all the elements of the vector to the value \a x.
+ * \param *x
+ */
+void GSLVector::SetAll(double x)
+{
+  gsl_vector_set_all (vector, x);
+};
+
+/** This function sets all the elements of the vector to zero.
+ */
+void GSLVector::SetZero()
+{
+  gsl_vector_set_zero (vector);
+};
+
+/** This function makes a basis vector by setting all the elements of the vector to zero except for the i-th element which is set to one.
+ * \param i i-th component to set to unity (all other to zero)
+ * \return vector set
+ */
+int GSLVector::SetBasis(size_t i)
+{
+  return gsl_vector_set_basis (vector, i);
+};
+
+/* ====================== Exchanging elements ============================ */
+/** This function exchanges the \a i-th and \a j-th elements of the vector in-place.
+ * \param i i-th element to swap with ...
+ * \param j ... j-th element to swap against
+ */
+int GSLVector::SwapElements(size_t i, size_t j)
+{
+  return gsl_vector_swap_elements (vector, i, j);
+};
+
+/** This function reverses the order of the elements of the vector.
+ */
+int GSLVector::Reverse()
+{
+  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 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/gslvector.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,78 @@
+/*
+ * gslvector.hpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+#ifndef GSLVECTOR_HPP_
+#define GSLVECTOR_HPP_
+
+using namespace std;
+
+/*********************************************** includes ***********************************/
+
+// include config.h
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <iostream>
+#include <gsl/gsl_vector.h>
+
+/****************************************** forward declarations *****************************/
+
+class GSLVector;
+
+/********************************************** declarations *******************************/
+
+class GSLVector {
+  friend class LinearSystemOfEquations;
+
+public:
+  GSLVector(size_t m);
+  GSLVector(const GSLVector * const src);
+  GSLVector(const GSLVector & src);
+  ~GSLVector();
+
+  // Accessing
+  void SetFromDoubleArray(double *x);
+  double Get(size_t m) const;
+  void Set(size_t m, double x);
+  double *Pointer(size_t m) const;
+  const double *const_Pointer(size_t m) const;
+  size_t GetDimension() const;
+
+  // Initializing
+  void SetAll(double x);
+  void SetZero();
+  int SetBasis(size_t m);
+
+  // Exchanging elements
+  int SwapElements(size_t i, size_t j);
+  int Reverse();
+
+  // checking state
+  bool IsZero() const;
+  bool IsOne() const;
+
+private:
+  gsl_vector *vector;
+
+  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);
+
+
+
+
+#endif /* GSLVECTOR_HPP_ */
Index: src/helpers.cpp
===================================================================
--- src/helpers.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/helpers.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -19,5 +19,5 @@
   double test = 0.1439851348959832147598734598273456723948652983045928346598365;
   do {
-    Log() << Verbose(0) << text;
+    DoLog(0) && (Log() << Verbose(0) << text);
     cin >> test;
   } while (test == 0.1439851348959832147598734598273456723948652983045928346598365);
Index: src/helpers.hpp
===================================================================
--- src/helpers.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/helpers.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -76,4 +76,28 @@
 };
 
+/** returns greater of the two values.
+ * \param x first value
+ * \param y second value
+ * \return greater of the two (by operator>())
+ */
+template <typename T> T Max(T x, T y)
+{
+  if (x > y)
+    return x;
+  else return y;
+};
+
+/** returns smaller of the two values.
+ * \param x first value
+ * \param y second value
+ * \return smaller of the two (by operator<())
+ */
+template <typename T> T Min(T x, T y)
+{
+  if (x < y)
+    return x;
+  else return y;
+};
+
 /** Creates a lookup table for true father's Atom::Nr -> atom ptr.
  * \param *start begin of chain list
@@ -90,5 +114,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;
   }
@@ -103,5 +127,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;
   }
@@ -110,5 +134,6 @@
   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;
   } else {
@@ -121,5 +146,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;
Index: src/info.cpp
===================================================================
--- src/info.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/info.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,41 @@
+/*
+ * Info.cpp
+ *
+ *  Created on: Nov 25, 2009
+ *      Author: heber
+ */
+
+#include "info.hpp"
+#include "log.hpp"
+#include "verbose.hpp"
+
+int Info::verbosity = 0;
+
+/**
+ * Constructor. Do not use this function. Use getInstance() instead.
+ *
+ * \return Info instance
+ */
+Info::Info(const char *msg)
+{
+  verbosity++;
+  FunctionName = msg;
+  DoLog(0) && (Log() << Verbose(0) << "Begin of " << FunctionName << endl);
+};
+
+/**
+ * Destructor. Better use purgeInstance().
+ */
+Info::~Info() {
+  DoLog(0) && (Log() << Verbose(0) << "End of " << FunctionName << endl);
+  verbosity--;
+}
+
+/**
+ * Sets the verbosity.
+ *
+ * \param verbosityLevel verbosity
+ */
+void Info::setVerbosity(int verbosityLevel) {
+  verbosity = verbosityLevel;
+}
Index: src/info.hpp
===================================================================
--- src/info.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/info.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,30 @@
+/*
+ * Info.hpp
+ *
+ *  Created on: Nov 25, 2009
+ *      Author: heber
+ */
+
+#ifndef INFO_HPP_
+#define INFO_HPP_
+
+using namespace std;
+
+/*********************************************** includes ***********************************/
+
+/****************************************** forward declarations *****************************/
+
+/********************************************** definitions *********************************/
+
+class Info {
+public :
+  static int verbosity;
+  const char *FunctionName;
+
+  Info(const char *msg);
+  ~Info();
+  static void setVerbosity(int verbosityLevel);
+
+};
+
+#endif /* INFO_HPP_ */
Index: src/joiner.cpp
===================================================================
--- src/joiner.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/joiner.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -7,4 +7,6 @@
 
 //============================ INCLUDES ===========================
+
+#include <cstring>
 
 #include "datacreator.hpp"
@@ -45,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 {
@@ -75,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
@@ -144,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) { 
@@ -153,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;
@@ -177,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;
@@ -242,5 +244,5 @@
   delete(periode);
   Free(&dir);
-  Log() << Verbose(0) << "done." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done." << endl);
   return 0;
 };
Index: src/linearsystemofequations.cpp
===================================================================
--- src/linearsystemofequations.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/linearsystemofequations.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,129 @@
+/*
+ * linearsystemofequations.cpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+#include "defs.hpp"
+#include "gslmatrix.hpp"
+#include "gslvector.hpp"
+#include "linearsystemofequations.hpp"
+#include "logger.hpp"
+#include "vector.hpp"
+
+#include <cassert>
+#include <gsl/gsl_permutation.h>
+
+/** Constructor for class LinearSystemOfEquations.
+ * Allocates Vector and Matrix classes.
+ * \param m column dimension
+ * \param n row dimension
+ */
+LinearSystemOfEquations::LinearSystemOfEquations(int m, int n) : rows(m), columns(n), IsSymmetric(false)
+{
+  A = new GSLMatrix(m, n);
+  b = new GSLVector(m);
+  x = new GSLVector(n);
+};
+
+/** Destructor for class LinearSystemOfEquations.
+ * Destructs Vector and Matrix classes.
+ */
+LinearSystemOfEquations::~LinearSystemOfEquations()
+{
+  delete(A);
+  delete(b);
+  delete(x);
+};
+
+/** Sets whether matrix is to be regarded as symmetric.
+ * Note that we do not check whether it really is, just take upper diagonal.
+ * \param symmetric true or false
+ */
+bool LinearSystemOfEquations::SetSymmetric(bool symmetric)
+{
+  assert (rows == columns && "Rows and columns don't have equal size! Setting symmetric not possible.");
+  return (IsSymmetric = symmetric);
+};
+
+/** Initializes vector b to the components of the given vector.
+ * \param *x Vector with equal dimension (no check!)
+ */
+void LinearSystemOfEquations::Setb(Vector *x)
+{
+  assert ( columns == NDIM && "Vector class is always three-dimensional, unlike this LEqS!");
+  b->SetFromDoubleArray(x->x);
+};
+
+/** Initializes vector b to the components of the given vector.
+ * \param *x array with equal dimension (no check!)
+ */
+void LinearSystemOfEquations::Setb(double *x)
+{
+  b->SetFromDoubleArray(x);
+};
+
+/** Initializes matrix a to the components of the given array.
+ * note that sort order should be
+ * \param *x array with equal dimension (no check!)
+ */
+void LinearSystemOfEquations::SetA(double *x)
+{
+  A->SetFromDoubleArray(x);
+};
+
+/** Returns the solution vector x \f$A \cdot x = b\f$ as an array of doubles.
+ * \param *array pointer allocated array for solution on return (no bounds check, dimension must match)
+ * \return true - solving possible, false - some error occured.
+ */
+bool LinearSystemOfEquations::GetSolutionAsArray(double *&array)
+{
+  bool status = Solve();
+
+  // copy solution
+  for (size_t i=0;i<x->dimension;i++) {
+    array[i] = x->Get(i);
+  }
+  return status;
+};
+
+/** Returns the solution vector x \f$A \cdot x = b\f$ as an array of doubles.
+ * \param &x solution vector on return (must be 3-dimensional)
+ * \return true - solving possible, false - some error occured.
+ */
+bool LinearSystemOfEquations::GetSolutionAsVector(Vector &v)
+{
+  assert(rows == NDIM && "Solution can only be returned as vector if number of columns is NDIM.");
+  bool status = Solve();
+
+  // copy solution
+  for (size_t i=0;i<x->dimension;i++)
+    v.x[i] = x->Get(i);
+  return status;
+};
+
+/** Solves the given system of \f$A \cdot x = b\f$.
+ * Use either LU or Householder decomposition.
+ * Solution is stored in LinearSystemOfEquations::x
+ * \return true - solving possible, false - some error occured.
+ */
+bool LinearSystemOfEquations::Solve()
+{
+  // calculate solution
+  int s;
+  if (IsSymmetric) { // use LU
+    gsl_permutation * p = gsl_permutation_alloc (x->dimension);
+    gsl_linalg_LU_decomp (A->matrix, p, &s);
+    gsl_linalg_LU_solve (A->matrix, p, b->vector, x->vector);
+    gsl_permutation_free (p);
+  } else {  // use Householder
+    //GSLMatrix *backup = new GSLMatrix(rows,columns);
+    //*backup = *A;
+    gsl_linalg_HH_solve (A->matrix, b->vector, x->vector);
+    //*A = *backup;
+    //delete(backup);
+  }
+  return true;
+};
+
Index: src/linearsystemofequations.hpp
===================================================================
--- src/linearsystemofequations.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/linearsystemofequations.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,56 @@
+/*
+ * linearsystemofequations.hpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+using namespace std;
+
+/*********************************************** includes ***********************************/
+
+// include config.h
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <gsl/gsl_linalg.h>
+
+/****************************************** forward declarations *****************************/
+
+class Vector;
+class GSLMatrix;
+class GSLVector;
+
+/********************************************** declarations *******************************/
+
+/** Solver class for a linear system of equations in the form \f$A \cdot x = b\F$.
+ *
+ */
+class LinearSystemOfEquations {
+public:
+  LinearSystemOfEquations(int n, int m);
+  ~LinearSystemOfEquations();
+
+  // setting
+  void Setb(Vector *x);
+  void Setb(double *x);
+  void SetA(double *x);
+  bool SetSymmetric(bool symmetric);
+
+  // solving
+  bool GetSolutionAsArray(double *&array);
+  bool GetSolutionAsVector(Vector &v);
+
+  GSLVector *b;
+  GSLVector *x;
+  GSLMatrix *A;
+
+private:
+  bool Solve();
+
+  int rows;
+  int columns;
+
+  bool IsSymmetric;
+};
Index: src/linkedcell.cpp
===================================================================
--- src/linkedcell.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/linkedcell.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -45,7 +45,7 @@
   max.Zero();
   min.Zero();
-  Log() << Verbose(1) << "Begin of LinkedCell" << endl;
-  if (set->IsEmpty()) {
-    eLog() << Verbose(0) << "ERROR: 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;
   }
@@ -68,5 +68,5 @@
     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
@@ -74,10 +74,10 @@
     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;
+  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) {
-    Log() << Verbose(1) << "ERROR: 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,8 +86,8 @@
     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()) {
@@ -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(0) << "ERROR: set contains no linked cell nodes!" << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "set contains no linked cell nodes!" << endl);
     return;
   }
@@ -140,5 +140,5 @@
     }
   }
-  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
@@ -146,10 +146,10 @@
     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;
+  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) {
-    Log() << Verbose(1) << "ERROR: 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,8 +158,8 @@
     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;
@@ -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(0) << "ERROR: 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)) {
@@ -242,4 +242,16 @@
     return NULL;
   }
+};
+
+/** 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->x[i] - min.x[i])/RADIUS);
+
+  return CheckBounds();
 };
 
@@ -260,5 +272,5 @@
     return status;
   } else {
-    eLog() << Verbose(1) << "ERROR: 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,139 @@
  * \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->x[i] - min.x[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.x[i] = min.x[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.x[i] = min.x[i]+RADIUS*((double)n[i]+c[i]);
+        // set up distance vector
+        Distance.CopyVector(x);
+        Distance.SubtractVector(&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.CopyVector(&center);
+        tester.SubtractVector(&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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/linkedcell.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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/log.cpp
===================================================================
--- src/log.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/log.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -16,5 +16,4 @@
 void setVerbosity(int verbosityLevel) {
   logger::getInstance()->setVerbosity(verbosityLevel);
-  errorLogger::getInstance()->setVerbosity(verbosityLevel);
 }
 
@@ -28,4 +27,26 @@
 }
 
+/** 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);
+}
+
 /**
  * Prints an error log entry.
Index: src/log.hpp
===================================================================
--- src/log.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/log.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/logger.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -81,7 +81,8 @@
   int verbosityLevel = l.verbosity;
   l.nix->clear();
-  if (v.DoOutput(verbosityLevel))
+  if (v.DoOutput(verbosityLevel)) {
+    v.print(cout);
     return cout;
-  else
+  } else
     return *l.nix;
 };
@@ -90,7 +91,8 @@
   int verbosityLevel = l->verbosity;
   l->nix->clear();
-  if (v.DoOutput(verbosityLevel))
+  if (v.DoOutput(verbosityLevel)) {
+    v.print(cout);
     return cout;
-  else
+  } else
     return *l->nix;
 };
Index: src/memoryallocator.hpp
===================================================================
--- src/memoryallocator.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/memoryallocator.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -16,4 +16,5 @@
 #endif
 
+#include <cstdlib>
 #include <iostream>
 #include <iomanip>
Index: src/memoryusageobserver.cpp
===================================================================
--- src/memoryusageobserver.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/memoryusageobserver.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -4,4 +4,6 @@
  * This class represents a Singleton for observing memory usage.
  */
+
+#include <cstdlib>
 
 #include "log.hpp"
@@ -88,9 +90,9 @@
 
   if (current == memoryUsers.end()) {
-    Log() << Verbose(0) << "WARNING: There is non-tracked memory to be freed. Pointer "
+    eLog() << Verbose(2) << "There is non-tracked memory to be freed. Pointer "
       << 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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/molecule.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -4,4 +4,6 @@
  *
  */
+
+#include <cstring>
 
 #include "atom.hpp"
@@ -21,4 +23,5 @@
 #include "tesselation.hpp"
 #include "vector.hpp"
+#include "World.hpp"
 
 /************************************* Functions for class molecule *********************************/
@@ -43,7 +46,5 @@
   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::get()->DefaultName);
 };
 
@@ -157,4 +158,5 @@
   double *matrix = NULL;
   bond *Binder = NULL;
+  double * const cell_size = World::get()->cell_size;
 
 //  Log() << Verbose(3) << "Begin of AddHydrogenReplacementAtom." << endl;
@@ -192,5 +194,5 @@
   BondRescale = TopOrigin->type->HBondDistance[TopBond->BondDegree-1];
   if (BondRescale == -1) {
-    eLog() << Verbose(3) << "ERROR: 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;
@@ -235,5 +237,5 @@
             SecondOtherAtom = (*Runner)->GetOtherAtom(TopOrigin);
           } else {
-            Log() << Verbose(3) << "WARNING: Detected more than four bonds for atom " << TopOrigin->Name;
+            DoeLog(2) && (eLog()<< Verbose(2) << "Detected more than four bonds for atom " << TopOrigin->Name);
           }
         }
@@ -272,5 +274,5 @@
       bondangle = TopOrigin->type->HBondAngle[1];
       if (bondangle == -1) {
-        Log() << Verbose(3) << "ERROR: 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;
@@ -394,5 +396,5 @@
       break;
     default:
-      eLog() << Verbose(0) << "ERROR: 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;
@@ -427,7 +429,7 @@
   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
@@ -445,5 +447,5 @@
     Walker->type = elemente->FindElement(shorthand);
     if (Walker->type == NULL) {
-      eLog() << Verbose(0) << "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);
     }
@@ -541,5 +543,5 @@
     add(Binder, last);
   } else {
-    eLog() << Verbose(1) << "ERROR: 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;
@@ -553,5 +555,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);
@@ -567,5 +569,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()) {
@@ -587,5 +589,5 @@
   else
     molname = filename; // contains no slashes
-  char *endname = strchr(molname, '.');
+  const char *endname = strchr(molname, '.');
   if ((endname == NULL) || (endname < molname))
     length = strlen(molname);
@@ -601,4 +603,5 @@
 void molecule::SetBoxDimension(Vector *dim)
 {
+  double * const cell_size = World::get()->cell_size;
   cell_size[0] = dim->x[0];
   cell_size[1] = 0.;
@@ -619,5 +622,5 @@
     AtomCount--;
   } else
-    eLog() << Verbose(0) << "ERROR: 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--;
@@ -637,5 +640,5 @@
     ElementsInMolecule[pointer->type->Z]--; // decrease number of atom of this element
   else
-    eLog() << Verbose(0) << "ERROR: 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--;
@@ -662,5 +665,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;
   }
@@ -678,5 +681,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);
@@ -691,4 +694,5 @@
 bool molecule::CheckBounds(const Vector *x) const
 {
+  double * const cell_size = World::get()->cell_size;
   bool result = true;
   int j =-1;
@@ -766,7 +770,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);
 };
 
@@ -825,5 +829,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;
 
@@ -841,9 +845,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);
   }
 };
@@ -905,5 +909,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;
@@ -917,5 +921,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;
@@ -924,5 +928,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;
@@ -936,5 +940,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;
@@ -942,14 +946,14 @@
   /// 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: ";
+    DoLog(5) && (Log() << Verbose(5) << "Center of Gravity: ");
     CenterOfGravity.Output();
-    Log() << Verbose(0) << endl << Verbose(5) << "Other Center of Gravity: ";
+    DoLog(0) && (Log() << Verbose(0) << endl << Verbose(5) << "Other Center of Gravity: ");
     OtherCenterOfGravity.Output();
-    Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl);
     if (CenterOfGravity.DistanceSquared(&OtherCenterOfGravity) > threshold*threshold) {
-      Log() << Verbose(4) << "Centers of gravity don't match." << endl;
+      DoLog(4) && (Log() << Verbose(4) << "Centers of gravity don't match." << endl);
       result = false;
     }
@@ -958,5 +962,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");
@@ -965,5 +969,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");
@@ -971,13 +975,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;
@@ -995,10 +999,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;
   }
@@ -1015,5 +1019,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--;)
@@ -1022,7 +1026,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) {
@@ -1041,9 +1045,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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/molecule.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -82,5 +82,4 @@
 class molecule : public PointCloud {
   public:
-    double cell_size[6];//!< cell size
     const periodentafel * const elemente; //!< periodic table with each element
     atom *start;        //!< start of atom list
@@ -106,7 +105,9 @@
 
   // re-definition of virtual functions from PointCloud
+  const char * const GetName() const;
   Vector *GetCenter() const ;
   TesselPoint *GetPoint() const ;
   TesselPoint *GetTerminalPoint() const ;
+  int GetMaxId() const;
   void GoToNext() const ;
   void GoToPrevious() const ;
@@ -267,5 +268,6 @@
   int FragmentMolecule(int Order, config *configuration);
   bool CheckOrderAtSite(bool *AtomMask, Graph *GlobalKeySetList, int Order, int *MinimumRingSize, char *path = NULL);
-  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,5 +323,6 @@
   void Enumerate(ofstream *out);
   void Output(ofstream *out);
-  void DissectMoleculeIntoConnectedSubgraphs(molecule * const mol, config * const configuration);
+  void DissectMoleculeIntoConnectedSubgraphs(const periodentafel * const periode, config * const configuration);
+  int CountAllAtoms() const;
 
   // merging of molecules
Index: src/molecule_dynamics.cpp
===================================================================
--- src/molecule_dynamics.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/molecule_dynamics.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -207,5 +207,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;
@@ -249,5 +249,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 +277,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 +306,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;
-      exit(1);
-    }
-  Log() << Verbose(1) << "done." << endl;
+      DoeLog(0) && (eLog()<< Verbose(0) << "Failed to create an injective PermutationMap!" << endl);
+      performCriticalExit();
+    }
+  DoLog(1) && (Log() << Verbose(1) << "done." << endl);
 };
 
@@ -358,5 +358,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 +365,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, at current potential " << OldPotential << " ... " << endl;
+  DoLog(1) && (Log() << Verbose(1) << "Argument minimising the PermutationMap." << endl);
   OldPotential = 1e+10;
   round = 0;
   do {
-    Log() << Verbose(2) << "Starting round " << ++round << " ... " << endl;
+    DoLog(2) && (Log() << Verbose(2) << "Starting round " << ++round << ", at current potential " << OldPotential << " ... " << endl);
     OlderPotential = OldPotential;
     do {
@@ -424,14 +424,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(0) << "ERROR: 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(0) << "ERROR: " << *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 +443,5 @@
     } while (Walker->next != end);
   } while ((OlderPotential - OldPotential) > 1e-3);
-  Log() << Verbose(1) << "done." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "done." << endl);
 
 
@@ -466,7 +466,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);
 };
 
@@ -503,5 +503,5 @@
 
   // 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);
@@ -568,9 +568,11 @@
     // 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;
     }
@@ -650,22 +652,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();
@@ -677,10 +679,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.;
@@ -688,9 +690,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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/molecule_fragmentation.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -5,4 +5,6 @@
  *      Author: heber
  */
+
+#include <cstring>
 
 #include "atom.hpp"
@@ -16,4 +18,5 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
+#include "World.hpp"
 
 /************************************* Functions for class molecule *********************************/
@@ -41,5 +44,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;
 };
@@ -65,9 +68,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);
 };
@@ -97,5 +100,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);
@@ -110,5 +113,6 @@
         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();
         }
       }
@@ -118,7 +122,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;
   }
@@ -150,5 +154,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);
@@ -160,5 +164,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;
@@ -168,7 +172,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;
   }
@@ -198,5 +202,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++) {
@@ -208,7 +212,8 @@
       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;
   }
@@ -238,11 +243,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;
   }
@@ -288,13 +293,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);
   }
 };
@@ -355,5 +360,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);
@@ -361,11 +366,12 @@
       //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();
     }
   }
@@ -391,5 +397,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;
@@ -407,12 +413,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);
 };
 
@@ -441,5 +447,5 @@
     // transmorph graph keyset list into indexed KeySetList
     if (GlobalKeySetList == NULL) {
-      Log() << Verbose(1) << "ERROR: 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;
     }
@@ -449,5 +455,5 @@
     map<int, pair<double,int> > *AdaptiveCriteriaList = ScanAdaptiveFileIntoMap(path, *IndexKeySetList); // (Root No., (Value, Order)) !
     if (AdaptiveCriteriaList->empty()) {
-      eLog() << Verbose(0) << "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;
@@ -487,7 +493,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);
     }
   }
@@ -506,5 +512,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;
   }
@@ -557,9 +563,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
 
@@ -587,5 +593,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
@@ -596,9 +602,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);
   }
@@ -631,17 +637,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(0) << "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);
@@ -674,9 +680,9 @@
   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 ===
@@ -685,9 +691,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
@@ -698,5 +704,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
@@ -710,12 +720,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)
@@ -736,12 +746,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;
   }
@@ -764,5 +774,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());
@@ -785,8 +795,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;
   }
@@ -794,5 +804,5 @@
   Free(&MaxArray);
 
-  Log() << Verbose(1) << "End of ParseOrderAtSiteFromFile" << endl;
+  DoLog(1) && (Log() << Verbose(1) << "End of ParseOrderAtSiteFromFile" << endl);
   return status;
 };
@@ -811,5 +821,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;
@@ -838,6 +848,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
@@ -898,8 +906,8 @@
       }
     } else {
-      Log() << Verbose(0) << "ERROR: 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
@@ -1048,8 +1056,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
 };
@@ -1128,10 +1136,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))
-          //Log() << Verbose(0) << "ERROR: 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);
       }
@@ -1213,7 +1221,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]) {
@@ -1226,5 +1234,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);
   }
 };
@@ -1256,12 +1264,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];
@@ -1273,8 +1281,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);
@@ -1284,19 +1292,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;
@@ -1314,11 +1322,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);
     }
   }
@@ -1364,6 +1372,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);
@@ -1377,10 +1385,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
@@ -1392,10 +1400,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);
 
@@ -1404,5 +1412,5 @@
 
   // return list
-  Log() << Verbose(0) << "End of PowerSetGenerator." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "End of PowerSetGenerator." << endl);
   return (FragmentSearch.FragmentCounter - Counter);
 };
@@ -1450,5 +1458,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;
@@ -1483,5 +1491,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;
@@ -1536,5 +1544,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)
@@ -1586,6 +1594,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})
@@ -1597,5 +1605,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;
@@ -1614,7 +1622,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
@@ -1634,5 +1642,5 @@
   Free(&NumMoleculesOfOrder);
 
-  Log() << Verbose(0) << "End of FragmentBOSSANOVA." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "End of FragmentBOSSANOVA." << endl);
 };
 
@@ -1649,4 +1657,5 @@
   atom *Walker = NULL;
   atom *OtherWalker = NULL;
+  double * const cell_size = World::get()->cell_size;
   double *matrix = ReturnFullMatrixforSymmetric(cell_size);
   enum Shading *ColorList = NULL;
@@ -1657,5 +1666,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");
@@ -1675,5 +1684,5 @@
           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;
@@ -1691,5 +1700,5 @@
       //Log() << Verbose(3) << "Translation vector is ";
       Translationvector.Output();
-      Log() << Verbose(0) << endl;
+      DoLog(0) && (Log() << Verbose(0) << endl);
       // apply to all atoms of first component via BFS
       for (int i=AtomCount;i--;)
@@ -1713,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);
@@ -1722,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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/molecule_geometry.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -15,4 +15,5 @@
 #include "memoryallocator.hpp"
 #include "molecule.hpp"
+#include "World.hpp"
 
 /************************************* Functions for class molecule *********************************/
@@ -26,4 +27,5 @@
   bool status = true;
   const Vector *Center = DetermineCenterOfAll();
+  double * const cell_size = World::get()->cell_size;
   double *M = ReturnFullMatrixforSymmetric(cell_size);
   double *Minv = InverseMatrix(M);
@@ -46,4 +48,5 @@
 {
   bool status = true;
+  double * const cell_size = World::get()->cell_size;
   double *M = ReturnFullMatrixforSymmetric(cell_size);
   double *Minv = InverseMatrix(M);
@@ -101,9 +104,9 @@
 {
   int Num = 0;
-  atom *ptr = start->next;  // start at first in list
+  atom *ptr = start;  // start at first in list
 
   Center.Zero();
 
-  if (ptr != end) {   //list not empty?
+  if (ptr->next != end) {   //list not empty?
     while (ptr->next != end) {  // continue with second if present
       ptr = ptr->next;
@@ -226,4 +229,5 @@
 void molecule::TranslatePeriodically(const Vector *trans)
 {
+  double * const cell_size = World::get()->cell_size;
   double *M = ReturnFullMatrixforSymmetric(cell_size);
   double *Minv = InverseMatrix(M);
@@ -252,4 +256,5 @@
 {
   atom *Walker = start;
+  double * const cell_size = World::get()->cell_size;
   double *matrix = ReturnFullMatrixforSymmetric(cell_size);
   double *inversematrix = InverseMatrix(cell_size);
@@ -275,5 +280,5 @@
               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.;
@@ -286,7 +291,7 @@
         Testvector.MatrixMultiplication(matrix);
         Center.AddVector(&Testvector);
-        Log() << Verbose(1) << "vector is: ";
+        DoLog(1) && (Log() << Verbose(1) << "vector is: ");
         Testvector.Output();
-        Log() << Verbose(0) << endl;
+        DoLog(0) && (Log() << Verbose(0) << endl);
 #ifdef ADDHYDROGEN
         // now also change all hydrogens
@@ -298,7 +303,7 @@
             Testvector.MatrixMultiplication(matrix);
             Center.AddVector(&Testvector);
-            Log() << Verbose(1) << "Hydrogen vector is: ";
+            DoLog(1) && (Log() << Verbose(1) << "Hydrogen vector is: ");
             Testvector.Output();
-            Log() << Verbose(0) << endl;
+            DoLog(0) && (Log() << Verbose(0) << endl);
           }
         }
@@ -347,11 +352,11 @@
   }
   // 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 +370,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!)
@@ -399,11 +404,11 @@
     }
     // 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);
   }
 
@@ -428,7 +433,7 @@
 
   // rotate on z-x plane
-  Log() << Verbose(0) << "Begin of Aligning all atoms." << endl;
+  DoLog(0) && (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(1) && (Log() << Verbose(1) << "Z-X-angle: " << alpha << " ... ");
   while (ptr->next != end) {
     ptr = ptr->next;
@@ -446,12 +451,12 @@
   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: ";
+  DoLog(1) && (Log() << Verbose(1) << "alignment vector after first rotation: ");
   n->Output();
-  Log() << Verbose(0) << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
 
   // rotate on z-y plane
   ptr = start;
   alpha = atan(-n->x[1]/n->x[2]);
-  Log() << Verbose(1) << "Z-Y-angle: " << alpha << " ... ";
+  DoLog(1) && (Log() << Verbose(1) << "Z-Y-angle: " << alpha << " ... ");
   while (ptr->next != end) {
     ptr = ptr->next;
@@ -470,8 +475,8 @@
   n->x[2] = -sin(alpha) * tmp +  cos(alpha) * n->x[2];
 
-  Log() << Verbose(1) << "alignment vector after second rotation: ";
+  DoLog(1) && (Log() << Verbose(1) << "alignment vector after second rotation: ");
   n->Output();
-  Log() << Verbose(1) << endl;
-  Log() << Verbose(0) << "End of Aligning all atoms." << endl;
+  DoLog(1) && (Log() << Verbose(1) << endl);
+  DoLog(0) && (Log() << Verbose(0) << "End of Aligning all atoms." << endl);
 };
 
Index: src/molecule_graph.cpp
===================================================================
--- src/molecule_graph.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/molecule_graph.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -17,4 +17,5 @@
 #include "memoryallocator.hpp"
 #include "molecule.hpp"
+#include "World.hpp"
 
 struct BFSAccounting
@@ -58,10 +59,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 +107,5 @@
   LinkedCell *LC = NULL;
   bool free_BG = false;
+  double * const cell_size = World::get()->cell_size;
 
   if (BG == NULL) {
@@ -113,5 +115,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 +128,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 +144,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 +189,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 +198,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 +210,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 +233,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 +261,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 +316,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 +343,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 +353,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 +359,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 +381,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 +388,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 +430,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 +444,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 +501,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);
 
@@ -515,5 +525,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 +542,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 +562,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 +588,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 +598,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 +684,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 +691,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 +697,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 +709,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 +728,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 +766,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 +786,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 +864,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 +896,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 +907,5 @@
     ResetBFSAccounting(Walker, BFS);
 
-    Log() << Verbose(1) << "---------------------------------------------------------------------------------------------------------" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "---------------------------------------------------------------------------------------------------------" << endl);
     OtherAtom = NULL;
     CyclicStructureAnalysis_CyclicBFSFromRootToRoot(BackEdge, BFS);
@@ -926,8 +936,12 @@
         break; // breaking here will not cause error!
     }
-    if (i == vertex->ListOfBonds.size())
-      eLog() << Verbose(0) << "Error: All Component entries are already occupied!" << endl;
-  } else
-    eLog() << Verbose(0) << "Error: Given vertex is NULL!" << endl;
+    if (i == vertex->ListOfBonds.size()) {
+      DoeLog(0) && (eLog()<< Verbose(0) << "Error: All Component entries are already occupied!" << endl);
+      performCriticalExit();
+    }
+  } else {
+    DoeLog(0) && (eLog()<< Verbose(0) << "Error: Given vertex is NULL!" << endl);
+    performCriticalExit();
+  }
 }
 ;
@@ -965,8 +979,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);
 }
 ;
@@ -974,9 +988,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;
@@ -984,13 +998,49 @@
   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;
+  }
+
+  return status;
+}
+;
+
+/** 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 *path path to file
+ * \param *filename name of file
+ * \return true - file written successfully, false - writing failed
+ */
+bool molecule::StoreBondsToFile(char *path, char *filename)
+{
+  ofstream BondFile;
+  stringstream line;
+  bool status = true;
+
+  if (path != NULL)
+    line << path << "/" << filename;
+  else
+    line << filename;
+  BondFile.open(line.str().c_str(), ios::out);
+  DoLog(1) && (Log() << Verbose(1) << "Saving adjacency list ... ");
+  if (BondFile != NULL) {
+    BondFile << "m\tn" << endl;
+    ActOnAllAtoms(&atom::OutputBonds, &BondFile);
+    BondFile.close();
+    DoLog(1) && (Log() << Verbose(1) << "done." << endl);
+  } else {
+    DoLog(1) && (Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl);
     status = false;
   }
@@ -1005,5 +1055,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;
@@ -1046,5 +1096,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;
   }
@@ -1069,5 +1119,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;
   }
@@ -1095,7 +1145,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;
 }
@@ -1113,5 +1163,5 @@
   bool status = true;
   if (ReferenceStack->IsEmpty()) {
-    eLog() << Verbose(0) << "ReferenceStack is empty!" << endl;
+    DoLog(1) && (Log() << Verbose(1) << "ReferenceStack is empty!" << endl);
     return false;
   }
@@ -1128,10 +1178,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);
@@ -1182,21 +1232,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
@@ -1204,9 +1254,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
@@ -1225,5 +1275,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) {
@@ -1271,10 +1321,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);
@@ -1285,5 +1335,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);
@@ -1310,5 +1360,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);
 }
 ;
@@ -1317,5 +1367,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) {
@@ -1323,5 +1373,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);
   }
 
@@ -1341,5 +1391,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) {
@@ -1352,5 +1402,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);
           }
@@ -1377,10 +1427,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;
 }
@@ -1399,6 +1449,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
@@ -1422,15 +1472,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_pointcloud.cpp
===================================================================
--- src/molecule_pointcloud.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/molecule_pointcloud.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -13,4 +13,11 @@
 /************************************* Functions for class molecule *********************************/
 
+/** Returns a name for this point cloud, here the molecule's name.
+ * \return name of point cloud
+ */
+const char * const molecule::GetName() const
+{
+  return name;
+};
 
 /** Determine center of all atoms.
@@ -41,4 +48,12 @@
 {
   return end;
+};
+
+/** Return the greatest index of all atoms in the list.
+ * \return greatest index
+ */
+int molecule::GetMaxId() const
+{
+  return last_atom;
 };
 
Index: src/moleculelist.cpp
===================================================================
--- src/moleculelist.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/moleculelist.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -4,4 +4,6 @@
  *
  */
+
+#include <cstring>
 
 #include "atom.hpp"
@@ -17,4 +19,5 @@
 #include "memoryallocator.hpp"
 #include "periodentafel.hpp"
+#include "World.hpp"
 
 /*********************************** Functions for class MoleculeListClass *************************/
@@ -33,10 +36,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;
+    DoLog(4) && (Log() << Verbose(4) << "ListOfMolecules: Freeing " << *ListRunner << "." << endl);
     delete (*ListRunner);
   }
-  Log() << Verbose(4) << "Freeing ListOfMolecules." << endl;
+  DoLog(4) && (Log() << Verbose(4) << "Freeing ListOfMolecules." << endl);
   ListOfMolecules.clear(); // empty list
 };
@@ -142,8 +145,8 @@
 
   // header
-  Log() << Verbose(0) << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl;
-  Log() << Verbose(0) << "-----------------------------------------------" << endl;
+  DoLog(0) && (Log() << Verbose(0) << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl);
+  DoLog(0) && (Log() << Verbose(0) << "-----------------------------------------------" << endl);
   if (ListOfMolecules.size() == 0)
-    Log() << Verbose(0) << "\tNone" << endl;
+    DoLog(0) && (Log() << Verbose(0) << "\tNone" << endl);
   else {
     Origin.Zero();
@@ -162,13 +165,13 @@
       }
       // output Index, Name, number of atoms, chemical formula
-      Log() << Verbose(0) << ((*ListRunner)->ActiveFlag ? "*" : " ") << (*ListRunner)->IndexNr << "\t" << (*ListRunner)->name << "\t\t" << (*ListRunner)->AtomCount << "\t";
+      DoLog(0) && (Log() << Verbose(0) << ((*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)
-          Log() << Verbose(0) << Elemental->symbol << Counts[Elemental->Z];
+          DoLog(0) && (Log() << Verbose(0) << Elemental->symbol << Counts[Elemental->Z]);
       }
       // Center and size
-      Log() << Verbose(0) << "\t" << (*ListRunner)->Center << "\t" << sqrt(size) << endl;
+      DoLog(0) && (Log() << Verbose(0) << "\t" << (*ListRunner)->Center << "\t" << sqrt(size) << endl);
     }
   }
@@ -311,5 +314,5 @@
   Tesselation *TesselStruct = NULL;
   if ((srcmol == NULL) || (mol == NULL)) {
-    Log() << Verbose(1) << "ERROR: 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;
   }
@@ -319,5 +322,5 @@
   FindNonConvexBorder(mol, TesselStruct, (const LinkedCell *&)LCList, 4., NULL);
   if (TesselStruct == NULL) {
-    Log() << Verbose(1) << "ERROR: Could not tesselate the fixed molecule." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Could not tesselate the fixed molecule." << endl);
     return false;
   }
@@ -336,5 +339,5 @@
   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);
@@ -345,5 +348,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
@@ -351,5 +354,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);
   }
@@ -363,8 +366,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);
 };
 
@@ -392,5 +395,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
@@ -402,6 +405,5 @@
   input.open(line.c_str());
   if (input == NULL) {
-    eLog() << Verbose(0) << 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;
   }
@@ -420,5 +422,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();
 
@@ -441,5 +443,6 @@
     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;
     }
@@ -462,12 +465,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);
   }
 
@@ -557,5 +560,5 @@
   }
   Free(&FitConstant);
-  Log() << Verbose(0) << "done." << endl;
+  DoLog(0) && (Log() << Verbose(0) << "done." << endl);
   return true;
 };
@@ -577,5 +580,5 @@
 
   // 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);
@@ -605,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();
@@ -636,5 +639,10 @@
   int FragmentCounter = 0;
   ofstream output;
-
+  double cell_size_backup[6];
+  double * const cell_size = World::get()->cell_size;
+
+  // 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++) {
@@ -643,6 +651,8 @@
     if (path != NULL)
       strcpy(PathBackup, path);
-    else
-      eLog() << Verbose(0) << "OutputConfigForListOfFragments: NULL default path obtained from config!" << endl;
+    else {
+      DoeLog(0) && (eLog()<< Verbose(0) << "OutputConfigForListOfFragments: NULL default path obtained from config!" << endl);
+      performCriticalExit();
+    }
 
     // correct periodic
@@ -653,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();
@@ -663,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
@@ -678,5 +688,5 @@
       j += k + 1;
       BoxDimension.x[k] = 2.5 * (configuration->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
-      (*ListRunner)->cell_size[j] += BoxDimension.x[k] * 2.;
+      cell_size[j] = BoxDimension.x[k] * 2.;
     }
     (*ListRunner)->Translate(&BoxDimension);
@@ -693,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;
 
@@ -705,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;
@@ -716,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;
@@ -737,11 +751,44 @@
 /** Dissects given \a *mol into connected subgraphs and inserts them as new molecules but with old atoms into \a this.
  * \param *out output stream for debugging
- * \param *mol molecule with atoms to dissect
+ * \param *periode periodentafel
  * \param *configuration config with BondGraph
  */
-void MoleculeListClass::DissectMoleculeIntoConnectedSubgraphs(molecule * const mol, config * const configuration)
-{
+void MoleculeListClass::DissectMoleculeIntoConnectedSubgraphs(const periodentafel * const periode, config * const configuration)
+{
+  molecule *mol = new molecule(periode);
+  atom *Walker = NULL;
+  atom *Advancer = NULL;
+  bond *Binder = NULL;
+  bond *Stepper = NULL;
+  // 0. gather all atoms into single molecule
+  for (MoleculeList::iterator MolRunner = ListOfMolecules.begin(); !ListOfMolecules.empty(); MolRunner = ListOfMolecules.begin()) {
+    // shift all atoms to new molecule
+    Advancer = (*MolRunner)->start->next;
+    while (Advancer != (*MolRunner)->end) {
+      Walker = Advancer;
+      Advancer = Advancer->next;
+      DoLog(3) && (Log() << Verbose(3) << "Re-linking " << *Walker << "..." << endl);
+      unlink(Walker);
+      Walker->father = Walker;
+      mol->AddAtom(Walker);    // counting starts at 1
+    }
+    // remove all bonds
+    Stepper = (*MolRunner)->first->next;
+    while (Stepper != (*MolRunner)->last) {
+      Binder = Stepper;
+      Stepper = Stepper->next;
+      delete(Binder);
+    }
+    // remove the molecule
+    delete(*MolRunner);
+    ListOfMolecules.erase(MolRunner);
+  }
+
   // 1. dissect the molecule into connected subgraphs
-  configuration ->BG->ConstructBondGraph(mol);
+  if (!configuration->BG->ConstructBondGraph(mol)) {
+    delete (mol);
+    DoeLog(1) && (eLog()<< Verbose(1) << "There are no bonds." << endl);
+    return;
+  }
 
   // 2. scan for connected subgraphs
@@ -750,4 +797,9 @@
   Subgraphs = mol->DepthFirstSearchAnalysis(BackEdgeStack);
   delete(BackEdgeStack);
+  if ((Subgraphs == NULL) || (Subgraphs->next == NULL)) {
+    delete (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
@@ -757,8 +809,15 @@
   // 4a. create array of molecules to fill
   const int MolCount = Subgraphs->next->Count();
+  char number[MAXSTRINGSIZE];
   molecule **molecules = Malloc<molecule *>(MolCount, "config::Load() - **molecules");
   for (int i=0;i<MolCount;i++) {
     molecules[i] = (molecule*) new molecule(mol->elemente);
     molecules[i]->ActiveFlag = true;
+    strncpy(molecules[i]->name, mol->name, MAXSTRINGSIZE);
+    if (MolCount > 1) {
+      sprintf(number, "-%d", i+1);
+      strncat(molecules[i]->name, number, MAXSTRINGSIZE - strlen(mol->name) - 1);
+    }
+    DoLog(1) && (Log() << Verbose(1) << "MolName is " << molecules[i]->name << endl);
     insert(molecules[i]);
   }
@@ -768,5 +827,5 @@
   int *MolMap = Calloc<int>(mol->AtomCount, "config::Load() - *MolMap");
   MoleculeLeafClass *MolecularWalker = Subgraphs;
-  atom *Walker = NULL;
+  Walker = NULL;
   while (MolecularWalker->next != NULL) {
     MolecularWalker = MolecularWalker->next;
@@ -780,22 +839,29 @@
 
   // 4c. relocate atoms to new molecules and remove from Leafs
-  Walker = mol->start;
+  Walker = NULL;
   while (mol->start->next != mol->end) {
     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();
     }
   }
-  // 4d. we don't need to redo bonds, as they are connected subgraphs and still maintained their ListOfBonds
+  // 4d. we don't need to redo bonds, as they are connected subgraphs and still maintain their ListOfBonds, but we have to remove them from first..last list
+  Binder = mol->first;
+  while (mol->first->next != mol->last) {
+    Binder = mol->first->next;
+    Walker = Binder->leftatom;
+    unlink(Binder);
+    link(Binder,molecules[MolMap[Walker->nr]-1]->last);   // counting starts at 1
+  }
   // 4e. free Leafs
   MolecularWalker = Subgraphs;
@@ -807,6 +873,25 @@
   Free(&MolMap);
   Free(&molecules);
-  Log() << Verbose(1) << "I scanned " << FragmentCounter << " molecules." << endl;
-};
+  DoLog(1) && (Log() << Verbose(1) << "I scanned " << FragmentCounter << " molecules." << endl);
+};
+
+/** Count all atoms in each molecule.
+ * \return number of atoms in the MoleculeListClass.
+ * TODO: the inner loop should be done by some (double molecule::CountAtom()) function
+ */
+int MoleculeListClass::CountAllAtoms() const
+{
+  atom *Walker = NULL;
+  int AtomNo = 0;
+  for (MoleculeList::const_iterator MolWalker = ListOfMolecules.begin(); MolWalker != ListOfMolecules.end(); MolWalker++) {
+    Walker = (*MolWalker)->start;
+    while (Walker->next != (*MolWalker)->end) {
+      Walker = Walker->next;
+      AtomNo++;
+    }
+  }
+  return AtomNo;
+}
+
 
 /******************************************* Class MoleculeLeafClass ************************************************/
@@ -897,13 +982,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;
@@ -926,5 +1011,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;
         }
@@ -939,5 +1024,5 @@
       Free(&ListOfLocalAtoms);
   }
-  Log() << Verbose(1) << "End of FillBondStructureFromReference." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "End of FillBondStructureFromReference." << endl);
   return status;
 };
@@ -972,5 +1057,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;
     }
@@ -978,5 +1063,5 @@
     return true;
   } else {
-    Log() << Verbose(1) << "Rootstack is NULL." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "Rootstack is NULL." << endl);
     return false;
   }
@@ -1028,8 +1113,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;
   }
@@ -1059,8 +1144,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)
@@ -1068,5 +1153,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)) {
@@ -1076,5 +1161,5 @@
       Free(&ListOfLocalAtoms);
   }
-  Log() << Verbose(1) << "End of AssignKeySetsToFragment." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "End of AssignKeySetsToFragment." << endl);
   return status;
 };
@@ -1089,5 +1174,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) {
@@ -1100,10 +1185,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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/parser.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -7,4 +7,6 @@
 // ======================================= INCLUDES ==========================================
 
+#include <cstring>
+
 #include "helpers.hpp"
 #include "memoryallocator.hpp"
@@ -30,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;
   }
@@ -107,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--;) {
@@ -117,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;
@@ -156,7 +158,8 @@
 
   input.open(name, ios::in);
-  //Log() << Verbose(0) << "Opening " << name << " ... "  << input << endl;
+  //Log() << Verbose(1) << "Opening " << name << " ... "  << input << endl;
   if (input == NULL) {
-    eLog() << Verbose(0) << 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;
   }
@@ -178,7 +181,9 @@
   }
   //Log() << Verbose(0) << line.str() << endl;
-  //Log() << Verbose(0) << "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;
+  //Log() << Verbose(1) << "ColumnCounter[" << MatrixNr << "]: " << ColumnCounter[MatrixNr] << "." << endl;
+  if (ColumnCounter[MatrixNr] == 0) {
+    DoeLog(0) && (eLog()<< Verbose(0) << "ColumnCounter[" << MatrixNr << "]: " << ColumnCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl);
+    performCriticalExit();
+  }
   
   // scan rest for number of rows/lines
@@ -192,7 +197,9 @@
     }
   }
-  //Log() << Verbose(0) << "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;
+  //Log() << Verbose(1) << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << "." << endl;
+  if (RowCounter[MatrixNr] == 0) {
+    DoeLog(0) && (eLog()<< Verbose(0) << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl);
+    performCriticalExit();
+  }
 
   // allocate matrix if it's not zero dimension in one direction
@@ -213,12 +220,11 @@
       input.getline(filename, 1023);
       stringstream lines(filename);
-      //Log() << Verbose(0) << "Matrix at level " << j << ":";// << filename << endl;
+      //Log() << Verbose(2) << "Matrix at level " << j << ":";// << filename << endl;
       for(int k=skipcolumns;k--;)
         lines >> filename;
       for(int k=0;(k<ColumnCounter[MatrixNr]) && (!lines.eof());k++) {
         lines >> Matrix[MatrixNr][j][k];
-        //Log() << Verbose(0) << " " << setprecision(2) << Matrix[MatrixNr][j][k];;
+        //Log() << Verbose(1) << " " << setprecision(2) << Matrix[MatrixNr][j][k] << endl;
       }
-      //Log() << Verbose(0) << endl;
       Matrix[MatrixNr][ RowCounter[MatrixNr] ] = Malloc<double>(ColumnCounter[MatrixNr], "MatrixContainer::ParseMatrix: *Matrix[RowCounter[MatrixNr]][]");
       for(int j=ColumnCounter[MatrixNr];j--;)
@@ -226,5 +232,5 @@
     }
   } else {
-    eLog() << Verbose(0) << "ERROR: 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();
@@ -263,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;
   }
@@ -272,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
@@ -427,5 +433,6 @@
               //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;
               }
@@ -462,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;
@@ -470,5 +477,6 @@
     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;
     }
@@ -495,9 +503,10 @@
   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;
   }
@@ -520,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--;) {
@@ -579,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++)
@@ -606,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;
@@ -612,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;
   }
@@ -655,5 +664,6 @@
       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;
       }
@@ -690,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;
     }
@@ -714,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++)
@@ -743,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;
@@ -749,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;
   }
@@ -792,5 +802,6 @@
       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;
       }
@@ -799,5 +810,6 @@
           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;
           }
@@ -851,5 +863,6 @@
               //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;
               }
@@ -868,5 +881,6 @@
                   //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;
                   }
@@ -916,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;
     }
@@ -938,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++)
@@ -993,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--;)
@@ -1000,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;
   }
@@ -1034,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;
@@ -1045,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
@@ -1059,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
@@ -1075,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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/periodentafel.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -9,4 +9,5 @@
 #include <iomanip>
 #include <fstream>
+#include <cstring>
 
 #include "element.hpp"
@@ -48,5 +49,5 @@
   pointer->sort = &pointer->Z;
   if (pointer->Z < 1 && pointer->Z >= MAX_ELEMENTS)
-    Log() << Verbose(0) << "Invalid Z number!\n";
+    DoLog(0) && (Log() << Verbose(0) << "Invalid Z number!\n");
   return add(pointer, end);
 };
@@ -103,5 +104,5 @@
   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
@@ -117,16 +118,16 @@
   element *walker = NULL;
   int Z = -1;
-  Log() << Verbose(0) << "Atomic number: " << Z << endl;
+  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;
+    DoLog(0) && (Log() << Verbose(0) << "Element not found in database, please enter." << endl);
     walker = new element;
     walker->Z = Z;
-    Log() << Verbose(0) << "Mass: " << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Mass: " << endl);
     cin >> walker->mass;
-    Log() << Verbose(0) << "Name [max 64 chars]: " << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Name [max 64 chars]: " << endl);
     cin >> walker->name;
-    Log() << Verbose(0) << "Short form [max 3 chars]: " << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Short form [max 3 chars]: " << endl);
     cin >> walker->symbol;
     periodentafel::AddElement(walker);
@@ -197,5 +198,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;
@@ -219,15 +220,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);
       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();
@@ -313,5 +314,5 @@
 
   if (!otherstatus)
-    eLog() << Verbose(0) << "WARNING: Something went wrong while parsing the other databases!" << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "Something went wrong while parsing the other databases!" << endl);
 
   return status;
Index: src/stackclass.hpp
===================================================================
--- src/stackclass.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/stackclass.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -72,5 +72,5 @@
     return true;
   } else {
-    eLog() << Verbose(0) << "ERROR: 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(0) << "ERROR: 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(0) << "ERROR: 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(0) << "ERROR: 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(0) << "ERROR: 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(0) << "ERROR: 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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/tesselation.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -7,10 +7,13 @@
 
 #include <fstream>
+#include <assert.h>
 
 #include "helpers.hpp"
+#include "info.hpp"
 #include "linkedcell.hpp"
 #include "log.hpp"
 #include "tesselation.hpp"
 #include "tesselationhelpers.hpp"
+#include "triangleintersectionlist.hpp"
 #include "vector.hpp"
 #include "verbose.hpp"
@@ -22,21 +25,22 @@
 /** Constructor of BoundaryPointSet.
  */
-BoundaryPointSet::BoundaryPointSet()
-{
-  LinesCount = 0;
-  Nr = -1;
-  value = 0.;
-};
+BoundaryPointSet::BoundaryPointSet() :
+  LinesCount(0), value(0.), Nr(-1)
+{
+  Info FunctionInfo(__func__);
+  DoLog(1) && (Log() << Verbose(1) << "Adding noname." << endl);
+}
+;
 
 /** Constructor of BoundaryPointSet with Tesselpoint.
  * \param *Walker TesselPoint this boundary point represents
  */
-BoundaryPointSet::BoundaryPointSet(TesselPoint * Walker)
-{
-  node = Walker;
-  LinesCount = 0;
-  Nr = Walker->nr;
-  value = 0.;
-};
+BoundaryPointSet::BoundaryPointSet(TesselPoint * const Walker) :
+  LinesCount(0), node(Walker), value(0.), Nr(Walker->nr)
+{
+  Info FunctionInfo(__func__);
+  DoLog(1) && (Log() << Verbose(1) << "Adding Node " << *Walker << endl);
+}
+;
 
 /** Destructor of BoundaryPointSet.
@@ -46,27 +50,27 @@
 BoundaryPointSet::~BoundaryPointSet()
 {
-  //Log() << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
+  Info FunctionInfo(__func__);
+  //Log() << Verbose(0) << "Erasing point nr. " << Nr << "." << endl;
   if (!lines.empty())
-    eLog() << Verbose(0) << "WARNING: 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.
  * \param *line line to add
  */
-void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
-{
-  Log() << Verbose(6) << "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));
-    }
+void BoundaryPointSet::AddLine(BoundaryLineSet * const 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.
@@ -85,10 +89,12 @@
 /** Constructor of BoundaryLineSet.
  */
-BoundaryLineSet::BoundaryLineSet()
-{
+BoundaryLineSet::BoundaryLineSet() :
+  Nr(-1)
+{
+  Info FunctionInfo(__func__);
   for (int i = 0; i < 2; i++)
     endpoints[i] = NULL;
-  Nr = -1;
-};
+}
+;
 
 /** Constructor of BoundaryLineSet with two endpoints.
@@ -97,6 +103,7 @@
  * \param number number of the list
  */
-BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], const int number)
-{
+BoundaryLineSet::BoundaryLineSet(BoundaryPointSet * const Point[2], const int number)
+{
+  Info FunctionInfo(__func__);
   // set number
   Nr = number;
@@ -106,7 +113,33 @@
   Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
   Point[1]->AddLine(this); //
+  // set skipped to false
+  skipped = false;
   // clear triangles list
-  Log() << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
-};
+  DoLog(0) && (Log() << Verbose(0) << "New Line with endpoints " << *this << "." << endl);
+}
+;
+
+/** Constructor of BoundaryLineSet with two endpoints.
+ * Adds line automatically to each endpoints' LineMap
+ * \param *Point1 first boundary point
+ * \param *Point2 second boundary point
+ * \param number number of the list
+ */
+BoundaryLineSet::BoundaryLineSet(BoundaryPointSet * const Point1, BoundaryPointSet * const Point2, const int number)
+{
+  Info FunctionInfo(__func__);
+  // set number
+  Nr = number;
+  // set endpoints in ascending order
+  SetEndpointsOrdered(endpoints, Point1, Point2);
+  // add this line to the hash maps of both endpoints
+  Point1->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
+  Point2->AddLine(this); //
+  // set skipped to false
+  skipped = false;
+  // clear triangles list
+  DoLog(0) && (Log() << Verbose(0) << "New Line with endpoints " << *this << "." << endl);
+}
+;
 
 /** Destructor for BoundaryLineSet.
@@ -116,4 +149,5 @@
 BoundaryLineSet::~BoundaryLineSet()
 {
+  Info FunctionInfo(__func__);
   int Numbers[2];
 
@@ -134,5 +168,5 @@
         for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
           if ((*Runner).second == this) {
-            //Log() << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
+            //Log() << Verbose(0) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
             endpoints[i]->lines.erase(Runner);
             break;
@@ -140,11 +174,11 @@
       } else { // there's just a single line left
         if (endpoints[i]->lines.erase(Nr)) {
-          //Log() << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
+          //Log() << Verbose(0) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
         }
       }
       if (endpoints[i]->lines.empty()) {
-        //Log() << Verbose(5) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
+        //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;
         }
@@ -153,15 +187,18 @@
   }
   if (!triangles.empty())
-    eLog() << Verbose(0) << "WARNING: 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.
  * \param *triangle to add
  */
-void BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
-{
-  Log() << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "." << endl;
+void BoundaryLineSet::AddTriangle(BoundaryTriangleSet * const triangle)
+{
+  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.
@@ -169,11 +206,13 @@
  * \return true - common endpoint present, false - not connected
  */
-bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
-{
+bool BoundaryLineSet::IsConnectedTo(const BoundaryLineSet * const line) const
+{
+  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.
@@ -183,54 +222,54 @@
  * \return true - triangles are convex, false - concave or less than two triangles connected
  */
-bool BoundaryLineSet::CheckConvexityCriterion()
-{
+bool BoundaryLineSet::CheckConvexityCriterion() const
+{
+  Info FunctionInfo(__func__);
   Vector BaseLineCenter, BaseLineNormal, BaseLine, helper[2], NormalCheck;
   // get the two triangles
   if (triangles.size() != 2) {
-    Log() << Verbose(1) << "ERROR: 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;
   }
   // check normal vectors
   // have a normal vector on the base line pointing outwards
-  //Log() << Verbose(3) << "INFO: " << *this << " has vectors at " << *(endpoints[0]->node->node) << " and at " << *(endpoints[1]->node->node) << "." << endl;
+  //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.);
+  BaseLineCenter.Scale(1. / 2.);
   BaseLine.CopyVector(endpoints[0]->node->node);
   BaseLine.SubtractVector(endpoints[1]->node->node);
-  //Log() << Verbose(3) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
+  //Log() << Verbose(0) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
 
   BaseLineNormal.Zero();
   NormalCheck.Zero();
   double sign = -1.;
-  int i=0;
+  int i = 0;
   class BoundaryPointSet *node = NULL;
-  for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
-    //Log() << Verbose(3) << "INFO: NormalVector of " << *(runner->second) << " is " << runner->second->NormalVector << "." << endl;
+  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);
     sign = -sign;
     if (runner->second->NormalVector.NormSquared() > MYEPSILON)
-      BaseLineNormal.CopyVector(&runner->second->NormalVector);   // yes, copy second on top of first
+      BaseLineNormal.CopyVector(&runner->second->NormalVector); // yes, copy second on top of first
     else {
-      Log() << Verbose(1) << "CRITICAL: Triangle " << *runner->second << " has zero normal vector!" << endl;
-      exit(255);
+      DoeLog(0) && (eLog() << Verbose(0) << "Triangle " << *runner->second << " has zero normal vector!" << endl);
     }
     node = runner->second->GetThirdEndpoint(this);
     if (node != NULL) {
-      //Log() << Verbose(3) << "INFO: Third node for triangle " << *(runner->second) << " is " << *node << " at " << *(node->node->node) << "." << endl;
+      //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!
-      //Log() << Verbose(4) << "INFO: Height vector with respect to baseline is " << helper[i] << "." << endl;
+      helper[i].MakeNormalVector(&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 {
-      //Log() << Verbose(2) << "ERROR: 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;
     }
   }
-  //Log() << Verbose(3) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
+  //Log() << Verbose(0) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
   if (NormalCheck.NormSquared() < MYEPSILON) {
-    Log() << Verbose(3) << "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;
   }
@@ -238,8 +277,8 @@
   double angle = GetAngle(helper[0], helper[1], BaseLineNormal);
   if ((angle - M_PI) > -MYEPSILON) {
-    Log() << Verbose(3) << "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(3) << "REJECT: Angle is less than pi: concave." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "REJECT: Angle is less than pi: concave." << endl);
     return false;
   }
@@ -250,11 +289,13 @@
  * \return true - point is of the line, false - is not
  */
-bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
-{
-  for(int i=0;i<2;i++)
+bool BoundaryLineSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
+{
+  Info FunctionInfo(__func__);
+  for (int i = 0; i < 2; i++)
     if (point == endpoints[i])
       return true;
   return false;
-};
+}
+;
 
 /** Returns other endpoint of the line.
@@ -262,6 +303,7 @@
  * \return NULL - if endpoint not contained in BoundaryLineSet, or pointer to BoundaryPointSet otherwise
  */
-class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(class BoundaryPointSet *point)
-{
+class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(const BoundaryPointSet * const point) const
+{
+  Info FunctionInfo(__func__);
   if (endpoints[0] == point)
     return endpoints[1];
@@ -270,5 +312,6 @@
   else
     return NULL;
-};
+}
+;
 
 /** output operator for BoundaryLineSet.
@@ -276,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 =================================
@@ -286,13 +330,14 @@
 /** Constructor for BoundaryTriangleSet.
  */
-BoundaryTriangleSet::BoundaryTriangleSet()
-{
-  for (int i = 0; i < 3; i++)
-    {
-      endpoints[i] = NULL;
-      lines[i] = NULL;
-    }
-  Nr = -1;
-};
+BoundaryTriangleSet::BoundaryTriangleSet() :
+  Nr(-1)
+{
+  Info FunctionInfo(__func__);
+  for (int i = 0; i < 3; i++) {
+    endpoints[i] = NULL;
+    lines[i] = NULL;
+  }
+}
+;
 
 /** Constructor for BoundaryTriangleSet with three lines.
@@ -300,43 +345,36 @@
  * \param number number of triangle
  */
-BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number)
-{
+BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet * const line[3], const int number) :
+  Nr(number)
+{
+  Info FunctionInfo(__func__);
   // set number
-  Nr = number;
   // set lines
-  Log() << Verbose(5) << "New triangle " << Nr << ":" << endl;
-  for (int i = 0; i < 3; i++)
-    {
-      lines[i] = line[i];
-      lines[i]->AddTriangle(this);
-    }
+  for (int i = 0; i < 3; i++) {
+    lines[i] = line[i];
+    lines[i]->AddTriangle(this);
+  }
   // get ascending order of endpoints
-  map<int, class BoundaryPointSet *> OrderMap;
+  PointMap OrderMap;
   for (int i = 0; i < 3; i++)
     // 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]));
-        // and we don't care whether insertion fails
-      }
+    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]));
+      // and we don't care whether insertion fails
+    }
   // set endpoints
   int Counter = 0;
-  Log() << Verbose(6) << " with end points ";
-  for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
-      != OrderMap.end(); runner++)
-    {
-      endpoints[Counter] = runner->second;
-      Log() << Verbose(0) << " " << *endpoints[Counter];
-      Counter++;
-    }
-  if (Counter < 3)
-    {
-      eLog() << Verbose(0) << "ERROR! We have a triangle with only two distinct endpoints!"
-          << endl;
-      //exit(1);
-    }
-  Log() << Verbose(0) << "." << 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;
+    DoLog(0) && (Log() << Verbose(0) << " " << *endpoints[Counter] << endl);
+    Counter++;
+  }
+  if (Counter < 3) {
+    DoeLog(0) && (eLog() << Verbose(0) << "We have a triangle with only two distinct endpoints!" << endl);
+    performCriticalExit();
+  }
+}
+;
 
 /** Destructor of BoundaryTriangleSet.
@@ -346,18 +384,20 @@
 BoundaryTriangleSet::~BoundaryTriangleSet()
 {
+  Info FunctionInfo(__func__);
   for (int i = 0; i < 3; i++) {
     if (lines[i] != NULL) {
       if (lines[i]->triangles.erase(Nr)) {
-        //Log() << Verbose(5) << "Triangle Nr." << Nr << " erased in line " << *lines[i] << "." << endl;
+        //Log() << Verbose(0) << "Triangle Nr." << Nr << " erased in line " << *lines[i] << "." << endl;
       }
       if (lines[i]->triangles.empty()) {
-          //Log() << Verbose(5) << *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(5) << "Erasing triangle Nr." << Nr << " itself." << endl;
-};
+  //Log() << Verbose(0) << "Erasing triangle Nr." << Nr << " itself." << endl;
+}
+;
 
 /** Calculates the normal vector for this triangle.
@@ -365,6 +405,7 @@
  * \param &OtherVector direction vector to make normal vector unique.
  */
-void BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
-{
+void BoundaryTriangleSet::GetNormalVector(const Vector &OtherVector)
+{
+  Info FunctionInfo(__func__);
   // get normal vector
   NormalVector.MakeNormalVector(endpoints[0]->node->node, endpoints[1]->node->node, endpoints[2]->node->node);
@@ -373,9 +414,11 @@
   if (NormalVector.ScalarProduct(&OtherVector) > 0.)
     NormalVector.Scale(-1.);
-};
-
-/** Finds the point on the triangle \a *BTS the line defined by \a *MolCenter and \a *x crosses through.
+  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.
  * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
- * This we test if it's really on the plane and whether it's inside the triangle on the plane or not.
+ * 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
  * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
@@ -387,39 +430,144 @@
  * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
  */
-bool BoundaryTriangleSet::GetIntersectionInsideTriangle(Vector *MolCenter, Vector *x, Vector *Intersection)
-{
+bool BoundaryTriangleSet::GetIntersectionInsideTriangle(const Vector * const MolCenter, const Vector * const x, Vector * const Intersection) const
+{
+  Info FunctionInfo(__func__);
   Vector CrossPoint;
   Vector helper;
 
   if (!Intersection->GetIntersectionWithPlane(&NormalVector, endpoints[0]->node->node, MolCenter, x)) {
-    Log() << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl);
     return false;
   }
 
+  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) {
+    DoLog(1) && (Log() << Verbose(1) << "Intersection coindices with second endpoint." << endl);
+    return true;
+  } 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);
-    } else 
+    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();
+      DoLog(1) && (Log() << Verbose(1) << "INFO: Factor s is " << s << "." << endl);
+      if ((s < -MYEPSILON) || ((s - 1.) > MYEPSILON)) {
+        DoLog(1) && (Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << "outside of triangle." << endl);
+        i = 4;
+        break;
+      }
       i++;
-    if (i>2)
+    } else
       break;
-  } while (CrossPoint.NormSquared() < MYEPSILON);
-  if (i==3) {
-    Log() << Verbose(1) << "ERROR: Could not find any cross points, something's utterly wrong here!" << endl;
-    exit(255);
-  }
-  CrossPoint.SubtractVector(endpoints[i%3]->node->node);  // cross point was returned as absolute vector
-
-  // check whether intersection is inside or not by comparing length of intersection and length of cross point
-  if ((CrossPoint.NormSquared() - helper.NormSquared()) < MYEPSILON) { // inside
+  } while (i < 3);
+  if (i == 3) {
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " inside of triangle." << endl);
     return true;
-  } else { // outside!
-    Intersection->Zero();
+  } else {
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " outside of triangle." << endl);
     return false;
   }
-};
+}
+;
+
+/** 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
+ * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
+ * the first two basepoints) or not.
+ * \param *x point
+ * \param *ClosestPoint desired closest point inside triangle to \a *x, is absolute vector
+ * \return Distance squared between \a *x and closest point inside triangle
+ */
+double BoundaryTriangleSet::GetClosestPointInsideTriangle(const Vector * const x, Vector * const ClosestPoint) const
+{
+  Info FunctionInfo(__func__);
+  Vector Direction;
+
+  // 1. get intersection with plane
+  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);
+  }
+
+  // 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);
+
+  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
+  double ShortestDistance = -1.;
+  bool InsideFlag = false;
+  Vector CrossDirection[3];
+  Vector CrossPoint[3];
+  Vector helper;
+  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);
+    // 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();
+    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
+      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]);
+      }
+    } else
+      CrossPoint[i].Zero();
+  }
+  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
+      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);
+      if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
+        ShortestDistance = distance;
+        ClosestPoint->CopyVector(endpoints[i]->node->node);
+      }
+    }
+  }
+  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.
@@ -427,11 +575,13 @@
  * \return true - line is of the triangle, false - is not
  */
-bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
-{
-  for(int i=0;i<3;i++)
+bool BoundaryTriangleSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
+{
+  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.
@@ -439,11 +589,13 @@
  * \return true - point is of the triangle, false - is not
  */
-bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
-{
-  for(int i=0;i<3;i++)
+bool BoundaryTriangleSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
+{
+  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.
@@ -451,11 +603,13 @@
  * \return true - point is of the triangle, false - is not
  */
-bool BoundaryTriangleSet::ContainsBoundaryPoint(class TesselPoint *point)
-{
-  for(int i=0;i<3;i++)
+bool BoundaryTriangleSet::ContainsBoundaryPoint(const TesselPoint * const point) const
+{
+  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.
@@ -463,20 +617,13 @@
  * \return true - is the very triangle, false - is not
  */
-bool BoundaryTriangleSet::IsPresentTupel(class BoundaryPointSet *Points[3])
-{
-  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])
-
-          ));
-};
+bool BoundaryTriangleSet::IsPresentTupel(const BoundaryPointSet * const Points[3]) const
+{
+  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.
@@ -484,20 +631,12 @@
  * \return true - is the very triangle, false - is not
  */
-bool BoundaryTriangleSet::IsPresentTupel(class BoundaryTriangleSet *T)
-{
-  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])
-
-          ));
-};
+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])
+
+  ));
+}
+;
 
 /** Returns the endpoint which is not contained in the given \a *line.
@@ -505,15 +644,17 @@
  * \return pointer third endpoint or NULL if line does not belong to triangle.
  */
-class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(class BoundaryLineSet *line)
-{
+class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(const BoundaryLineSet * const line) const
+{
+  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.
@@ -521,10 +662,12 @@
  * \param *center central point on return.
  */
-void BoundaryTriangleSet::GetCenter(Vector *center)
-{
+void BoundaryTriangleSet::GetCenter(Vector * const center) const
+{
+  Info FunctionInfo(__func__);
   center->Zero();
-  for(int i=0;i<3;i++)
+  for (int i = 0; i < 3; i++)
     center->AddVector(endpoints[i]->node->node);
-  center->Scale(1./3.);
+  center->Scale(1. / 3.);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Center is at " << *center << "." << endl);
 }
 
@@ -535,8 +678,271 @@
 ostream &operator <<(ostream &ost, const BoundaryTriangleSet &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 << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
+  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 << "]";
   return ost;
-};
+}
+;
+
+// ======================================== Polygons on Boundary =================================
+
+/** Constructor for BoundaryPolygonSet.
+ */
+BoundaryPolygonSet::BoundaryPolygonSet() :
+  Nr(-1)
+{
+  Info FunctionInfo(__func__);
+}
+;
+
+/** Destructor of BoundaryPolygonSet.
+ * Just clears endpoints.
+ * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
+ */
+BoundaryPolygonSet::~BoundaryPolygonSet()
+{
+  Info FunctionInfo(__func__);
+  endpoints.clear();
+  DoLog(1) && (Log() << Verbose(1) << "Erasing polygon Nr." << Nr << " itself." << endl);
+}
+;
+
+/** Calculates the normal vector for this triangle.
+ * Is made unique by comparison with \a OtherVector to point in the other direction.
+ * \param &OtherVector direction vector to make normal vector unique.
+ * \return allocated vector in normal direction
+ */
+Vector * BoundaryPolygonSet::GetNormalVector(const Vector &OtherVector) const
+{
+  Info FunctionInfo(__func__);
+  // get normal vector
+  Vector TemporaryNormal;
+  Vector *TotalNormal = new Vector;
+  PointSet::const_iterator Runner[3];
+  for (int i = 0; i < 3; i++) {
+    Runner[i] = endpoints.begin();
+    for (int j = 0; j < i; j++) { // go as much further
+      Runner[i]++;
+      if (Runner[i] == endpoints.end()) {
+        DoeLog(0) && (eLog() << Verbose(0) << "There are less than three endpoints in the polygon!" << endl);
+        performCriticalExit();
+      }
+    }
+  }
+  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
+      Runner[i]++;
+    TotalNormal->AddVector(&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.)
+    TotalNormal->Scale(-1.);
+  DoLog(1) && (Log() << Verbose(1) << "Normal Vector is " << *TotalNormal << "." << endl);
+
+  return TotalNormal;
+}
+;
+
+/** Calculates the center point of the triangle.
+ * Is third of the sum of all endpoints.
+ * \param *center central point on return.
+ */
+void BoundaryPolygonSet::GetCenter(Vector * const center) const
+{
+  Info FunctionInfo(__func__);
+  center->Zero();
+  int counter = 0;
+  for (PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
+    center->AddVector((*Runner)->node->node);
+    counter++;
+  }
+  center->Scale(1. / (double) counter);
+  DoLog(1) && (Log() << Verbose(1) << "Center is at " << *center << "." << endl);
+}
+
+/** Checks whether the polygons contains all three endpoints of the triangle.
+ * \param *triangle triangle to test
+ * \return true - triangle is contained polygon, false - is not
+ */
+bool BoundaryPolygonSet::ContainsBoundaryTriangle(const BoundaryTriangleSet * const triangle) const
+{
+  Info FunctionInfo(__func__);
+  return ContainsPresentTupel(triangle->endpoints, 3);
+}
+;
+
+/** Checks whether the polygons contains both endpoints of the line.
+ * \param *line line to test
+ * \return true - line is of the triangle, false - is not
+ */
+bool BoundaryPolygonSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
+{
+  Info FunctionInfo(__func__);
+  return ContainsPresentTupel(line->endpoints, 2);
+}
+;
+
+/** Checks whether point is any of the three endpoints this triangle contains.
+ * \param *point point to test
+ * \return true - point is of the triangle, false - is not
+ */
+bool BoundaryPolygonSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
+{
+  Info FunctionInfo(__func__);
+  for (PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
+    DoLog(0) && (Log() << Verbose(0) << "Checking against " << **Runner << endl);
+    if (point == (*Runner)) {
+      DoLog(0) && (Log() << Verbose(0) << " Contained." << endl);
+      return true;
+    }
+  }
+  DoLog(0) && (Log() << Verbose(0) << " Not contained." << endl);
+  return false;
+}
+;
+
+/** Checks whether point is any of the three endpoints this triangle contains.
+ * \param *point TesselPoint to test
+ * \return true - point is of the triangle, false - is not
+ */
+bool BoundaryPolygonSet::ContainsBoundaryPoint(const TesselPoint * const point) const
+{
+  Info FunctionInfo(__func__);
+  for (PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
+    if (point == (*Runner)->node) {
+      DoLog(0) && (Log() << Verbose(0) << " Contained." << endl);
+      return true;
+    }
+  DoLog(0) && (Log() << Verbose(0) << " Not contained." << endl);
+  return false;
+}
+;
+
+/** Checks whether given array of \a *Points coincide with polygons's endpoints.
+ * \param **Points pointer to an array of BoundaryPointSet
+ * \param dim dimension of array
+ * \return true - set of points is contained in polygon, false - is not
+ */
+bool BoundaryPolygonSet::ContainsPresentTupel(const BoundaryPointSet * const * Points, const int dim) const
+{
+  Info FunctionInfo(__func__);
+  int counter = 0;
+  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++;
+    }
+  }
+
+  if (counter == dim)
+    return true;
+  else
+    return false;
+}
+;
+
+/** Checks whether given PointList coincide with polygons's endpoints.
+ * \param &endpoints PointList
+ * \return true - set of points is contained in polygon, false - is not
+ */
+bool BoundaryPolygonSet::ContainsPresentTupel(const PointSet &endpoints) const
+{
+  Info FunctionInfo(__func__);
+  size_t counter = 0;
+  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++;
+  }
+
+  if (counter == endpoints.size())
+    return true;
+  else
+    return false;
+}
+;
+
+/** Checks whether given set of \a *Points coincide with polygons's endpoints.
+ * \param *P pointer to BoundaryPolygonSet
+ * \return true - is the very triangle, false - is not
+ */
+bool BoundaryPolygonSet::ContainsPresentTupel(const BoundaryPolygonSet * const P) const
+{
+  return ContainsPresentTupel((const PointSet) P->endpoints);
+}
+;
+
+/** Gathers all the endpoints' triangles in a unique set.
+ * \return set of all triangles
+ */
+TriangleSet * BoundaryPolygonSet::GetAllContainedTrianglesFromEndpoints() const
+{
+  Info FunctionInfo(__func__);
+  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++) {
+        //Log() << Verbose(0) << " Testing triangle " << *(Sprinter->second) << endl;
+        if (ContainsBoundaryTriangle(Sprinter->second)) {
+          Tester = triangles->insert(Sprinter->second);
+          if (Tester.second)
+            DoLog(0) && (Log() << Verbose(0) << "Adding triangle " << *(Sprinter->second) << 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.
+ * \param *line lines with triangles attached
+ * \return true - polygon contains endpoints, false - line was NULL
+ */
+bool BoundaryPolygonSet::FillPolygonFromTrianglesOfLine(const BoundaryLineSet * const line)
+{
+  Info FunctionInfo(__func__);
+  pair<PointSet::iterator, bool> Tester;
+  if (line == NULL)
+    return false;
+  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)
+        DoLog(1) && (Log() << Verbose(1) << "  Inserting endpoint " << *((Runner->second)->endpoints[i]) << endl);
+    }
+  }
+
+  return true;
+}
+;
+
+/** output operator for BoundaryPolygonSet.
+ * \param &ost output stream
+ * \param &a boundary polygon
+ */
+ostream &operator <<(ostream &ost, const BoundaryPolygonSet &a)
+{
+  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 << "]";
+  return ost;
+}
+;
 
 // =========================================================== class TESSELPOINT ===========================================
@@ -546,8 +952,10 @@
 TesselPoint::TesselPoint()
 {
+  //Info FunctionInfo(__func__);
   node = NULL;
   nr = -1;
-  Name =  NULL;
-};
+  Name = NULL;
+}
+;
 
 /** Destructor for class TesselPoint.
@@ -555,22 +963,26 @@
 TesselPoint::~TesselPoint()
 {
-};
+  //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)
-{
-  ost << "[" << (Name) << "|" << this << "]";
+ostream & TesselPoint::operator <<(ostream &ost)
+{
+  Info FunctionInfo(__func__);
+  ost << "[" << (nr) << "|" << this << "]";
   return ost;
-};
-
+}
+;
 
 // =========================================================== class POINTCLOUD ============================================
@@ -580,6 +992,7 @@
 PointCloud::PointCloud()
 {
-
-};
+  //Info FunctionInfo(__func__);
+}
+;
 
 /** Destructor for class PointCloud.
@@ -587,6 +1000,7 @@
 PointCloud::~PointCloud()
 {
-
-};
+  //Info FunctionInfo(__func__);
+}
+;
 
 // ============================ CandidateForTesselation =============================
@@ -594,17 +1008,136 @@
 /** Constructor of class CandidateForTesselation.
  */
-CandidateForTesselation::CandidateForTesselation(TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) {
-  point = candidate;
-  BaseLine = line;
+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.CopyVector(&OptCandidateCenter);
   OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
-};
+}
+;
 
 /** Destructor for class CandidateForTesselation.
  */
-CandidateForTesselation::~CandidateForTesselation() {
-  point = NULL;
-  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.x[0] << " " << OldCenter.x[1] << " " << OldCenter.x[2] << " " << (*VRunner)->x[0] << " " << (*VRunner)->x[1] << " " << (*VRunner)->x[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.x[0] << " " << OldCenter.x[1] << " " << OldCenter.x[2] << " " << (*VRunner)->x[0] << " " << (*VRunner)->x[1] << " " << (*VRunner)->x[2] << endl);
+    }
+  }
+  return flag;
+}
+;
+
+/** output operator for CandidateForTesselation.
+ * \param &ost output stream
+ * \param &a boundary line
+ */
+ostream & operator <<(ostream &ost, const CandidateForTesselation &a)
+{
+  ost << "[" << a.BaseLine->Nr << "|" << a.BaseLine->endpoints[0]->node->Name << "," << a.BaseLine->endpoints[1]->node->Name << "] with ";
+  if (a.pointlist.empty())
+    ost << "no candidate.";
+  else {
+    ost << "candidate";
+    if (a.pointlist.size() != 1)
+      ost << "s ";
+    else
+      ost << " ";
+    for (TesselPointList::const_iterator Runner = a.pointlist.begin(); Runner != a.pointlist.end(); Runner++)
+      ost << *(*Runner) << " ";
+    ost << " at angle " << (a.ShortestAngle) << ".";
+  }
+
+  return ost;
+}
+;
 
 // =========================================================== class TESSELATION ===========================================
@@ -612,12 +1145,8 @@
 /** Constructor of class Tesselation.
  */
-Tesselation::Tesselation()
-{
-  PointsOnBoundaryCount = 0;
-  LinesOnBoundaryCount = 0;
-  TrianglesOnBoundaryCount = 0;
-  InternalPointer = PointsOnBoundary.begin();
-  LastTriangle = NULL;
-  TriangleFilesWritten = 0;
+Tesselation::Tesselation() :
+  PointsOnBoundaryCount(0), LinesOnBoundaryCount(0), TrianglesOnBoundaryCount(0), LastTriangle(NULL), TriangleFilesWritten(0), InternalPointer(PointsOnBoundary.begin())
+{
+  Info FunctionInfo(__func__);
 }
 ;
@@ -628,5 +1157,6 @@
 Tesselation::~Tesselation()
 {
-  Log() << Verbose(1) << "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) {
@@ -634,7 +1164,7 @@
       runner->second = NULL;
     } else
-      eLog() << Verbose(1) << "ERROR: The triangle " << runner->first << " has already been free'd." << endl;
-  }
-  Log() << Verbose(1) << "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);
 }
 ;
@@ -642,60 +1172,72 @@
 /** PointCloud implementation of GetCenter
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 Vector * Tesselation::GetCenter(ofstream *out) const
 {
-  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);
     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__);
   return (InternalPointer->second->node);
-};
+}
+;
 
 /** PointCloud implementation of GetTerminalPoint.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 TesselPoint * Tesselation::GetTerminalPoint() const
 {
+  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__);
   if (InternalPointer != PointsOnBoundary.end())
     InternalPointer++;
-};
+}
+;
 
 /** PointCloud implementation of GoToPrevious.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 void Tesselation::GoToPrevious() const
 {
+  Info FunctionInfo(__func__);
   if (InternalPointer != PointsOnBoundary.begin())
     InternalPointer--;
-};
+}
+;
 
 /** PointCloud implementation of GoToFirst.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 void Tesselation::GoToFirst() const
 {
+  Info FunctionInfo(__func__);
   InternalPointer = PointsOnBoundary.begin();
-};
+}
+;
 
 /** PointCloud implementation of GoToLast.
@@ -704,24 +1246,29 @@
 void Tesselation::GoToLast() const
 {
+  Info FunctionInfo(__func__);
   InternalPointer = PointsOnBoundary.end();
   InternalPointer--;
-};
+}
+;
 
 /** PointCloud implementation of IsEmpty.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 bool Tesselation::IsEmpty() const
 {
+  Info FunctionInfo(__func__);
   return (PointsOnBoundary.empty());
-};
+}
+;
 
 /** PointCloud implementation of IsLast.
  * Uses PointsOnBoundary and STL stuff.
- */   
+ */
 bool Tesselation::IsEnd() const
 {
+  Info FunctionInfo(__func__);
   return (InternalPointer == PointsOnBoundary.end());
-};
-
+}
+;
 
 /** Gueses first starting triangle of the convex envelope.
@@ -730,7 +1277,7 @@
  * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
  */
-void
-Tesselation::GuessStartingTriangle()
-{
+void Tesselation::GuessStartingTriangle()
+{
+  Info FunctionInfo(__func__);
   // 4b. create a starting triangle
   // 4b1. create all distances
@@ -742,24 +1289,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:";
@@ -771,117 +1315,79 @@
   // 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.Output();
-      Log() << Verbose(0) << 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(3) << "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(0) << "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
-    {
-      Log() << Verbose(1) << "No starting triangle found." << endl;
-      exit(255);
-    }
+  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);
+    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.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;
+      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);
+  }
 }
 ;
@@ -902,4 +1408,5 @@
 void Tesselation::TesselateOnBoundary(const PointCloud * const cloud)
 {
+  Info FunctionInfo(__func__);
   bool flag;
   PointMap::iterator winner;
@@ -920,9 +1427,9 @@
         // 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(2) << "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(3) << " and has peak " << *peak << "." << endl;
+        DoLog(1) && (Log() << Verbose(1) << " and has peak " << *peak << "." << endl);
 
         // prepare some auxiliary vectors
@@ -939,5 +1446,5 @@
           CenterVector.AddVector(BTS->endpoints[i]->node->node);
         CenterVector.Scale(1. / 3.);
-        Log() << Verbose(4) << "CenterVector of base triangle is " << CenterVector << endl;
+        DoLog(2) && (Log() << Verbose(2) << "CenterVector of base triangle is " << CenterVector << endl);
 
         // normal vector of triangle
@@ -946,5 +1453,5 @@
         BTS->GetNormalVector(NormalVector);
         NormalVector.CopyVector(&BTS->NormalVector);
-        Log() << Verbose(4) << "NormalVector of base triangle is " << NormalVector << endl;
+        DoLog(2) && (Log() << Verbose(2) << "NormalVector of base triangle is " << NormalVector << endl);
 
         // vector in propagation direction (out of triangle)
@@ -953,8 +1460,8 @@
         TempVector.CopyVector(&CenterVector);
         TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
-        //Log() << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
+        //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
           PropagationVector.Scale(-1.);
-        Log() << Verbose(4) << "PropagationVector of base triangle is " << PropagationVector << endl;
+        DoLog(2) && (Log() << Verbose(2) << "PropagationVector of base triangle is " << PropagationVector << endl);
         winner = PointsOnBoundary.end();
 
@@ -962,5 +1469,5 @@
         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(3) << "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
@@ -969,10 +1476,10 @@
             VirtualNormalVector.ProjectOntoPlane(&NormalVector);
             TempAngle = VirtualNormalVector.Angle(&PropagationVector);
-            Log() << Verbose(4) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
-            if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
-              Log() << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
+            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(4) << "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)
@@ -980,9 +1487,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(4) << *(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(4) << *(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;
             }
@@ -990,5 +1497,5 @@
             // 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;
             }
@@ -1001,5 +1508,5 @@
             helper.ProjectOntoPlane(&TempVector);
             if (fabs(helper.NormSquared()) < MYEPSILON) {
-              Log() << Verbose(4) << "Chosen set of vectors is linear dependent." << endl;
+              DoLog(2) && (Log() << Verbose(2) << "Chosen set of vectors is linear dependent." << endl);
               continue;
             }
@@ -1011,5 +1518,5 @@
             TempVector.AddVector(baseline->second->endpoints[1]->node->node);
             TempVector.AddVector(target->second->node->node);
-            TempVector.Scale(1./3.);
+            TempVector.Scale(1. / 3.);
             TempVector.SubtractVector(Center);
             // make it always point outward
@@ -1018,9 +1525,9 @@
             // calculate angle
             TempAngle = NormalVector.Angle(&VirtualNormalVector);
-            Log() << Verbose(4) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
+            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(4) << "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...
@@ -1040,9 +1547,9 @@
                 SmallestAngle = TempAngle;
                 winner = target;
-                Log() << Verbose(4) << "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(4) << "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(4) << "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
@@ -1050,5 +1557,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(2) << "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;
@@ -1080,15 +1587,16 @@
           TrianglesOnBoundaryCount++;
         } else {
-          Log() << Verbose(1) << "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(2) << "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.
@@ -1100,47 +1608,46 @@
 bool Tesselation::InsertStraddlingPoints(const PointCloud *cloud, const LinkedCell *LC)
 {
+  Info FunctionInfo(__func__);
   Vector Intersection, Normal;
   TesselPoint *Walker = NULL;
   Vector *Center = cloud->GetCenter();
-  list<BoundaryTriangleSet*> *triangles = NULL;
+  TriangleList *triangles = NULL;
   bool AddFlag = false;
   LinkedCell *BoundaryPoints = NULL;
 
-  Log() << Verbose(1) << "Begin of InsertStraddlingPoints" << endl;
-
   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(2) << "Current point is " << *Walker << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Current point is " << *Walker << "." << endl);
     // get the next triangle
-    triangles = FindClosestTrianglesToPoint(Walker->node, BoundaryPoints);
+    triangles = FindClosestTrianglesToVector(Walker->node, BoundaryPoints);
     BTS = triangles->front();
     if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
-      Log() << Verbose(2) << "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(2) << "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(2) << "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) {
         // inside, next!
-        Log() << Verbose(2) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
+        DoLog(0) && (Log() << Verbose(0) << *Walker << " is inside wrt triangle " << *BTS << "." << endl);
       } else {
         // outside!
-        Log() << Verbose(2) << *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];
@@ -1148,31 +1655,31 @@
         Normal.CopyVector(&BTS->NormalVector);
         // add Walker to boundary points
-        Log() << Verbose(2) << "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(2) << "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(3) << "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) {
-                Log() << Verbose(1) << "ERROR: " << 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
@@ -1185,5 +1692,5 @@
           BTS->GetNormalVector(Normal);
           Normal.Scale(-1.);
-          Log() << Verbose(2) << "Created new triangle " << *BTS << "." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "Created new triangle " << *BTS << "." << endl);
           TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
           TrianglesOnBoundaryCount++;
@@ -1191,5 +1698,5 @@
       }
     } else { // something is wrong with FindClosestTriangleToPoint!
-      Log() << Verbose(1) << "ERROR: 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;
     }
@@ -1198,8 +1705,8 @@
 
   // exit
-  delete(Center);
-  Log() << Verbose(1) << "End of InsertStraddlingPoints" << endl;
+  delete (Center);
   return true;
-};
+}
+;
 
 /** Adds a point to the tesselation::PointsOnBoundary list.
@@ -1210,4 +1717,5 @@
 bool Tesselation::AddBoundaryPoint(TesselPoint * Walker, const int n)
 {
+  Info FunctionInfo(__func__);
   PointTestPair InsertUnique;
   BPS[n] = new class BoundaryPointSet(Walker);
@@ -1217,5 +1725,5 @@
     return true;
   } else {
-    delete(BPS[n]);
+    delete (BPS[n]);
     BPS[n] = InsertUnique.first->second;
     return false;
@@ -1231,4 +1739,5 @@
 void Tesselation::AddTesselationPoint(TesselPoint* Candidate, const int n)
 {
+  Info FunctionInfo(__func__);
   PointTestPair InsertUnique;
   TPS[n] = new class BoundaryPointSet(Candidate);
@@ -1238,7 +1747,23 @@
   } else {
     delete TPS[n];
-    Log() << Verbose(4) << "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;
   }
+}
+;
+
+/** Sets point to a present Tesselation::PointsOnBoundary.
+ * Tesselation::TPS is set to the existing one or NULL if not found.
+ * @param Candidate point to set to
+ * @param n index for this point in Tesselation::TPS array
+ */
+void Tesselation::SetTesselationPoint(TesselPoint* Candidate, const int n) const
+{
+  Info FunctionInfo(__func__);
+  PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidate->nr);
+  if (FindPoint != PointsOnBoundary.end())
+    TPS[n] = FindPoint->second;
+  else
+    TPS[n] = NULL;
 }
 ;
@@ -1247,28 +1772,41 @@
  * 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;
-
-  if (a->lines.find(b->node->nr) != a->lines.end()) {
-    LineMap::iterator FindLine = a->lines.find(b->node->nr);
-    pair<LineMap::iterator,LineMap::iterator> FindPair;
+  LineMap::iterator FindLine = a->lines.find(b->node->nr);
+  BoundaryLineSet *WinningLine = NULL;
+  if (FindLine != a->lines.end()) {
+    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);
-    Log() << Verbose(5) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
-
-    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(4) << "Using existing line " << *FindLine->second << endl;
-
-        BPS[0] = FindLine->second->endpoints[0];
-        BPS[1] = FindLine->second->endpoints[1];
-        BLS[n] = FindLine->second;
-
-        break;
+      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);
+          }
+        }
       }
     }
@@ -1276,5 +1814,7 @@
 
   if (insertNewLine) {
-    AlwaysAddTesselationTriangleLine(a, b, n);
+    AddNewTesselationTriangleLine(a, b, n);
+  } else {
+    AddExistingTesselationTriangleLine(WinningLine, n);
   }
 }
@@ -1289,15 +1829,46 @@
  * @param n index of Tesselation::BLS giving the line with both endpoints
  */
-void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
-{
-  Log() << Verbose(4) << "Adding 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]));
   // increase counter
   LinesOnBoundaryCount++;
-};
+  // also add to open lines
+  CandidateForTesselation *CFT = new CandidateForTesselation(BLS[n]);
+  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.
@@ -1306,5 +1877,6 @@
 void Tesselation::AddTesselationTriangle()
 {
-  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
@@ -1316,5 +1888,6 @@
 
   // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
-};
+}
+;
 
 /** Function adds triangle to global list.
@@ -1324,5 +1897,6 @@
 void Tesselation::AddTesselationTriangle(const int nr)
 {
-  Log() << Verbose(1) << "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
@@ -1333,5 +1907,6 @@
 
   // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
-};
+}
+;
 
 /** Removes a triangle from the tesselation.
@@ -1342,34 +1917,37 @@
 void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
 {
+  Info FunctionInfo(__func__);
   if (triangle == NULL)
     return;
   for (int i = 0; i < 3; i++) {
     if (triangle->lines[i] != NULL) {
-      Log() << Verbose(5) << "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(5) << *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(5) << *triangle->lines[i] << " is still attached to another triangle: ";
-        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(5) << "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(0) << "ERROR: 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(5) << "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.
@@ -1379,4 +1957,5 @@
 void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
 {
+  Info FunctionInfo(__func__);
   int Numbers[2];
 
@@ -1399,5 +1978,5 @@
         for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
           if ((*Runner).second == line) {
-            Log() << Verbose(5) << "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;
@@ -1405,26 +1984,27 @@
       } else { // there's just a single line left
         if (line->endpoints[i]->lines.erase(line->Nr))
-          Log() << Verbose(5) << "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(5) << *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(5) << *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(0) << "ERROR: 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(0) << "WARNING: 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(5) << "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.
@@ -1435,10 +2015,57 @@
 void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
 {
+  Info FunctionInfo(__func__);
   if (point == NULL)
     return;
   if (PointsOnBoundary.erase(point->Nr))
-    Log() << Verbose(5) << "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.x[0] << " " << CandidateLine.OtherOptCenter.x[1] << " " << CandidateLine.OtherOptCenter.x[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.
@@ -1451,12 +2078,13 @@
  *                 triangles exist which is the maximum for three points
  */
-int Tesselation::CheckPresenceOfTriangle(TesselPoint *Candidates[3]) {
+int Tesselation::CheckPresenceOfTriangle(TesselPoint *Candidates[3]) const
+{
+  Info FunctionInfo(__func__);
   int adjacentTriangleCount = 0;
   class BoundaryPointSet *Points[3];
 
-  Log() << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
   // builds a triangle point set (Points) of the end points
   for (int i = 0; i < 3; i++) {
-    PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
+    PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
     if (FindPoint != PointsOnBoundary.end()) {
       Points[i] = FindPoint->second;
@@ -1471,17 +2099,17 @@
       for (int j = i; j < 3; j++) {
         if (Points[j] != NULL) {
-          LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
+          LineMap::const_iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
           for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
             TriangleMap *triangles = &FindLine->second->triangles;
-            Log() << Verbose(3) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
-            for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
+            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)) {
                 adjacentTriangleCount++;
               }
             }
-            Log() << Verbose(3) << "end." << endl;
+            DoLog(1) && (Log() << Verbose(1) << "end." << endl);
           }
           // Only one of the triangle lines must be considered for the triangle count.
-          //Log() << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
+          //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
           //return adjacentTriangleCount;
         }
@@ -1490,8 +2118,8 @@
   }
 
-  Log() << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
-  Log() << Verbose(2) << "End of CheckPresenceOfTriangle" << 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.
@@ -1505,4 +2133,5 @@
 class BoundaryTriangleSet * Tesselation::GetPresentTriangle(TesselPoint *Candidates[3])
 {
+  Info FunctionInfo(__func__);
   class BoundaryTriangleSet *triangle = NULL;
   class BoundaryPointSet *Points[3];
@@ -1534,5 +2163,5 @@
           }
           // Only one of the triangle lines must be considered for the triangle count.
-          //Log() << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
+          //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
           //return adjacentTriangleCount;
         }
@@ -1542,6 +2171,6 @@
 
   return triangle;
-};
-
+}
+;
 
 /** Finds the starting triangle for FindNonConvexBorder().
@@ -1552,19 +2181,23 @@
  * \param RADIUS radius of virtual rolling sphere
  * \param *LC LinkedCell structure with neighbouring TesselPoint's
- */
-void Tesselation::FindStartingTriangle(const double RADIUS, const LinkedCell *LC)
-{
-  Log() << Verbose(1) << "Begin of FindStartingTriangle\n";
+ * \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* FirstPoint = NULL;
-  TesselPoint* SecondPoint = NULL;
   TesselPoint* MaxPoint[NDIM];
+  TesselPoint* Temporary;
   double maxCoordinate[NDIM];
-  Vector Oben;
+  BoundaryLineSet *BaseLine = NULL;
   Vector helper;
   Vector Chord;
   Vector SearchDirection;
-
-  Oben.Zero();
+  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 NormalVector;
+
+  NormalVector.Zero();
 
   for (i = 0; i < 3; i++) {
@@ -1574,14 +2207,14 @@
 
   // 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();
-        //Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
+  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++) {
+          for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
             if ((*Runner)->node->x[i] > maxCoordinate[i]) {
-              Log() << Verbose(2) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
+              DoLog(1) && (Log() << Verbose(1) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl);
               maxCoordinate[i] = (*Runner)->node->x[i];
               MaxPoint[i] = (*Runner);
@@ -1589,119 +2222,233 @@
           }
         } else {
-          eLog() << Verbose(0) << "ERROR: 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(2) << "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;
-  CandidateList *OptCandidates = new CandidateList();
-  for (int k=0;k<NDIM;k++) {
-    Oben.Zero();
-    Oben.x[k] = 1.;
-    FirstPoint = MaxPoint[k];
-    Log() << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
+  for (int k = 0; k < NDIM; k++) {
+    NormalVector.Zero();
+    NormalVector.x[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;
-    TesselPoint* OptCandidate = NULL;
     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(FirstPoint, Oben, OptCandidate, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
-    SecondPoint = OptCandidate;
-    if (SecondPoint == 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;
-
-    helper.CopyVector(FirstPoint->node);
-    helper.SubtractVector(SecondPoint->node);
-    helper.Normalize();
-    Oben.ProjectOntoPlane(&helper);
-    Oben.Normalize();
-    helper.VectorProduct(&Oben);
-    ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
-
-    Chord.CopyVector(FirstPoint->node); // bring into calling function
-    Chord.SubtractVector(SecondPoint->node);
-    double radius = Chord.ScalarProduct(&Chord);
-    double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
-    helper.CopyVector(&Oben);
-    helper.Scale(CircleRadius);
-    // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
+    }
+    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);
+
+    // construct normal vector of circle
+    CirclePlaneNormal.CopyVector(BaseLine->endpoints[0]->node->node);
+    CirclePlaneNormal.SubtractVector(BaseLine->endpoints[1]->node->node);
+
+    double radius = CirclePlaneNormal.NormSquared();
+    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);
+    // 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(&Chord, &Oben);  // whether we look "left" first or "right" first is not important ...
+    SearchDirection.MakeNormalVector(&CirclePlaneNormal, &NormalVector); // 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(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
-    AddTesselationPoint(FirstPoint, 0);
-    Log() << Verbose(1) << "Found second point is at " << *SecondPoint->node << ".\n";
-    AddTesselationPoint(SecondPoint, 1);
-    AddTesselationLine(TPS[0], TPS[1], 0);
-
-    //Log() << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
-    FindThirdPointForTesselation(Oben, SearchDirection, helper, BLS[0], NULL, *&OptCandidates, &ShortestAngle, RADIUS, LC);
-    Log() << Verbose(1) << "List of third Points is ";
-    for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
-        Log() << Verbose(0) << " " << *(*it)->point;
-    }
-    Log() << Verbose(0) << endl;
-
-    for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
-      // add third triangle point
-      AddTesselationPoint((*it)->point, 2);
-      // add the second and third line
-      AddTesselationLine(TPS[1], TPS[2], 1);
-      AddTesselationLine(TPS[0], TPS[2], 2);
-      // ... and triangles to the Maps of the Tesselation class
-      BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
-      AddTesselationTriangle();
-      // ... and calculate its normal vector (with correct orientation)
-      (*it)->OptCenter.Scale(-1.);
-      Log() << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
-      BTS->GetNormalVector((*it)->OptCenter);  // vector to compare with should point inwards
-      Log() << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
-      << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
-
-      // if we do not reach the end with the next step of iteration, we need to setup a new first line
-      if (it != OptCandidates->end()--) {
-        FirstPoint = (*it)->BaseLine->endpoints[0]->node;
-        SecondPoint = (*it)->point;
-        // adding point 1 and point 2 and the line between them
-        AddTesselationPoint(FirstPoint, 0);
-        AddTesselationPoint(SecondPoint, 1);
-        AddTesselationLine(TPS[0], TPS[1], 0);
-      }
-      Log() << Verbose(2) << "Projection is " << BTS->NormalVector.ScalarProduct(&Oben) << "." << endl;
-    }
-    if (BTS != NULL) // we have created one starting triangle
+    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);
+    FindThirdPointForTesselation(NormalVector, SearchDirection, SphereCenter, OptCandidates, NULL, RADIUS, LC);
+    DoLog(0) && (Log() << Verbose(0) << "List of third Points is:" << endl);
+    for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); it++) {
+      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
-      class CandidateForTesselation *remover = NULL;
-      for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
-        remover = *it;
-        delete(remover);
-      }
-      OptCandidates->clear();
-    }
-  }
-
-  // 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);
-  Log() << Verbose(1) << "End of FindStartingTriangle\n";
-};
-
+      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.
+ * This is supposed to prevent early closing of the tesselation.
+ * \param CandidateLine CandidateForTesselation with baseline and shortestangle , i.e. not \a *OptCandidate
+ * \param *ThirdNode third point in triangle, not in BoundaryLineSet::endpoints
+ * \param RADIUS radius of sphere
+ * \param *LC LinkedCell structure
+ * \return true - there is a better candidate (smaller angle than \a ShortestAngle), false - no better TesselPoint candidate found
+ */
+//bool Tesselation::HasOtherBaselineBetterCandidate(CandidateForTesselation &CandidateLine, const TesselPoint * const ThirdNode, double RADIUS, const LinkedCell * const LC) const
+//{
+//	Info FunctionInfo(__func__);
+//  bool result = false;
+//  Vector CircleCenter;
+//  Vector CirclePlaneNormal;
+//  Vector OldSphereCenter;
+//  Vector SearchDirection;
+//  Vector helper;
+//  TesselPoint *OtherOptCandidate = NULL;
+//  double OtherShortestAngle = 2.*M_PI; // This will indicate the quadrant.
+//  double radius, CircleRadius;
+//  BoundaryLineSet *Line = NULL;
+//  BoundaryTriangleSet *T = NULL;
+//
+//  // check both other lines
+//  PointMap::const_iterator FindPoint = PointsOnBoundary.find(ThirdNode->nr);
+//  if (FindPoint != PointsOnBoundary.end()) {
+//    for (int i=0;i<2;i++) {
+//      LineMap::const_iterator FindLine = (FindPoint->second)->lines.find(BaseRay->endpoints[0]->node->nr);
+//      if (FindLine != (FindPoint->second)->lines.end()) {
+//        Line = FindLine->second;
+//        Log() << Verbose(0) << "Found line " << *Line << "." << endl;
+//        if (Line->triangles.size() == 1) {
+//          T = Line->triangles.begin()->second;
+//          // construct center of circle
+//          CircleCenter.CopyVector(Line->endpoints[0]->node->node);
+//          CircleCenter.AddVector(Line->endpoints[1]->node->node);
+//          CircleCenter.Scale(0.5);
+//
+//          // construct normal vector of circle
+//          CirclePlaneNormal.CopyVector(Line->endpoints[0]->node->node);
+//          CirclePlaneNormal.SubtractVector(Line->endpoints[1]->node->node);
+//
+//          // calculate squared radius of circle
+//          radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
+//          if (radius/4. < RADIUS*RADIUS) {
+//            CircleRadius = RADIUS*RADIUS - radius/4.;
+//            CirclePlaneNormal.Normalize();
+//            //Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
+//
+//            // construct old center
+//            GetCenterofCircumcircle(&OldSphereCenter, *T->endpoints[0]->node->node, *T->endpoints[1]->node->node, *T->endpoints[2]->node->node);
+//            helper.CopyVector(&T->NormalVector);  // normal vector ensures that this is correct center of the two possible ones
+//            radius = Line->endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
+//            helper.Scale(sqrt(RADIUS*RADIUS - radius));
+//            OldSphereCenter.AddVector(&helper);
+//            OldSphereCenter.SubtractVector(&CircleCenter);
+//            //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
+//
+//            // construct SearchDirection
+//            SearchDirection.MakeNormalVector(&T->NormalVector, &CirclePlaneNormal);
+//            helper.CopyVector(Line->endpoints[0]->node->node);
+//            helper.SubtractVector(ThirdNode->node);
+//            if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
+//              SearchDirection.Scale(-1.);
+//            SearchDirection.ProjectOntoPlane(&OldSphereCenter);
+//            SearchDirection.Normalize();
+//            Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
+//            if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
+//              // rotated the wrong way!
+//              DoeLog(1) && (eLog()<< Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl);
+//            }
+//
+//            // add third point
+//            FindThirdPointForTesselation(T->NormalVector, SearchDirection, OldSphereCenter, OptCandidates, ThirdNode, RADIUS, LC);
+//            for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); ++it) {
+//              if (((*it) == BaseRay->endpoints[0]->node) || ((*it) == BaseRay->endpoints[1]->node)) // skip if it's the same triangle than suggested
+//                continue;
+//              Log() << Verbose(0) << " Third point candidate is " << (*it)
+//              << " 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);
+//              PointCandidates[1] = BaseRay->endpoints[0]->node;
+//              PointCandidates[2] = BaseRay->endpoints[1]->node;
+//              bool check=false;
+//              int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
+//              // If there is no triangle, add it regularly.
+//              if (existentTrianglesCount == 0) {
+//                SetTesselationPoint((*it), 0);
+//                SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
+//                SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
+//
+//                if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
+//                  OtherOptCandidate = (*it);
+//                  check = true;
+//                }
+//              } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
+//                SetTesselationPoint((*it), 0);
+//                SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
+//                SetTesselationPoint(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)) {
+//                  OtherOptCandidate = (*it);
+//                  check = true;
+//                }
+//              }
+//
+//              if (check) {
+//                if (ShortestAngle > OtherShortestAngle) {
+//                  Log() << Verbose(0) << "There is a better candidate than " << *ThirdNode << " with " << ShortestAngle << " from baseline " << *Line << ": " << *OtherOptCandidate << " with " << OtherShortestAngle << "." << endl;
+//                  result = true;
+//                  break;
+//                }
+//              }
+//            }
+//            delete(OptCandidates);
+//            if (result)
+//              break;
+//          } else {
+//            Log() << Verbose(0) << "Circumcircle for base line " << *Line << " and base triangle " << T << " is too big!" << endl;
+//          }
+//        } else {
+//          DoeLog(2) && (eLog()<< Verbose(2) << "Baseline is connected to two triangles already?" << endl);
+//        }
+//      } else {
+//        Log() << Verbose(1) << "No present baseline between " << BaseRay->endpoints[0] << " and candidate " << *ThirdNode << "." << endl;
+//      }
+//    }
+//  } else {
+//    DoeLog(1) && (eLog()<< Verbose(1) << "Could not find the TesselPoint " << *ThirdNode << "." << endl);
+//  }
+//
+//  return result;
+//};
 
 /** This function finds a triangle to a line, adjacent to an existing one.
  * @param out output stream for debugging
- * @param Line current baseline to search from
+ * @param CandidateLine current cadndiate baseline to search from
  * @param T current triangle which \a Line is edge of
  * @param RADIUS radius of the rolling ball
@@ -1709,181 +2456,316 @@
  * @param *LC LinkedCell structure with neighbouring points
  */
-bool Tesselation::FindNextSuitableTriangle(BoundaryLineSet &Line, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
-{
-  Log() << Verbose(0) << "Begin of FindNextSuitableTriangle\n";
-  bool result = true;
-  CandidateList *OptCandidates = new CandidateList();
-
+bool Tesselation::FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, const BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
+{
+  Info FunctionInfo(__func__);
   Vector CircleCenter;
   Vector CirclePlaneNormal;
-  Vector OldSphereCenter;
+  Vector RelativeSphereCenter;
   Vector SearchDirection;
   Vector helper;
-  TesselPoint *ThirdNode = NULL;
+  BoundaryPointSet *ThirdPoint = NULL;
   LineMap::iterator testline;
-  double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
   double radius, CircleRadius;
 
-  Log() << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
-  for (int i=0;i<3;i++)
-    if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.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;
+    }
+  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(Line.endpoints[0]->node->node);
-  CircleCenter.AddVector(Line.endpoints[1]->node->node);
+  CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
+  CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
   CircleCenter.Scale(0.5);
 
   // construct normal vector of circle
-  CirclePlaneNormal.CopyVector(Line.endpoints[0]->node->node);
-  CirclePlaneNormal.SubtractVector(Line.endpoints[1]->node->node);
+  CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
+  CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
 
   // calculate squared radius of circle
   radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
-  if (radius/4. < RADIUS*RADIUS) {
-    CircleRadius = RADIUS*RADIUS - radius/4.;
+  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.;
     CirclePlaneNormal.Normalize();
-    //Log() << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
-
-    // construct old center
-    GetCenterofCircumcircle(&OldSphereCenter, *T.endpoints[0]->node->node, *T.endpoints[1]->node->node, *T.endpoints[2]->node->node);
-    helper.CopyVector(&T.NormalVector);  // normal vector ensures that this is correct center of the two possible ones
-    radius = Line.endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
-    helper.Scale(sqrt(RADIUS*RADIUS - radius));
-    OldSphereCenter.AddVector(&helper);
-    OldSphereCenter.SubtractVector(&CircleCenter);
-    //Log() << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
-
-    // construct SearchDirection
-    SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
-    helper.CopyVector(Line.endpoints[0]->node->node);
-    helper.SubtractVector(ThirdNode->node);
+    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(ThirdPoint->node->node);
     if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
       SearchDirection.Scale(-1.);
-    SearchDirection.ProjectOntoPlane(&OldSphereCenter);
-    SearchDirection.Normalize();
-    Log() << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
-    if (fabs(OldSphereCenter.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(0) << "ERROR: 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, OldSphereCenter, &Line, ThirdNode, OptCandidates, &ShortestAngle, RADIUS, LC);
+    FindThirdPointForTesselation(T.NormalVector, SearchDirection, T.SphereCenter, CandidateLine, ThirdPoint, RADIUS, LC);
 
   } else {
-    Log() << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
-  }
-
-  if (OptCandidates->begin() == OptCandidates->end()) {
-    eLog() << Verbose(0) << "WARNING: Could not find a suitable candidate." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and base triangle " << T << " is too big!" << endl);
+  }
+
+  if (CandidateLine.pointlist.empty()) {
+    DoeLog(2) && (eLog() << Verbose(2) << "Could not find a suitable candidate." << endl);
     return false;
   }
-  Log() << Verbose(1) << "Third Points are ";
-  for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
-    Log() << Verbose(0) << " " << *(*it)->point;
-  }
-  Log() << Verbose(0) << endl;
-
-  BoundaryLineSet *BaseRay = &Line;
-  for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
-    Log() << Verbose(1) << " Third point candidate is " << *(*it)->point
-    << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
-    Log() << Verbose(1) << " 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;
-    // 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)) {
-        AddTesselationLine(TPS[0], TPS[1], 0);
-        AddTesselationLine(TPS[0], TPS[2], 1);
-        AddTesselationLine(TPS[1], TPS[2], 2);
-
-        BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
-        AddTesselationTriangle();
-        (*it)->OptCenter.Scale(-1.);
-        BTS->GetNormalVector((*it)->OptCenter);
-        (*it)->OptCenter.Scale(-1.);
-
-        Log() << Verbose(0) << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
-          << " for this triangle ... " << endl;
-      //Log() << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
-      } else {
-        Log() << Verbose(1) << "WARNING: 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 does not seem helpful!" << endl;
-        result = false;
+  DoLog(0) && (Log() << Verbose(0) << "Third Points are: " << endl);
+  for (TesselPointList::iterator it = CandidateLine.pointlist.begin(); it != CandidateLine.pointlist.end(); ++it) {
+    DoLog(0) && (Log() << Verbose(0) << " " << *(*it) << endl);
+  }
+
+  return true;
+}
+;
+
+/** 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
+ * \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
+  TesselPointSet SetOfNeighbours;
+  SetOfNeighbours.insert(CandidateLine.BaseLine->endpoints[1]->node);
+  for (TesselPointList::iterator Runner = CandidateLine.pointlist.begin(); Runner != CandidateLine.pointlist.end(); Runner++)
+    SetOfNeighbours.insert(*Runner);
+  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)
+  Runner = connectedClosestPoints->begin();
+  Sprinter = Runner;
+  Sprinter++;
+  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);
+
+    AddCandidateTriangle(CandidateLine, Opt);
+
+    Runner = Sprinter;
+    Sprinter++;
+    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);
       }
-    } 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)) {
-          AddTesselationLine(TPS[0], TPS[1], 0);
-          AddTesselationLine(TPS[0], TPS[2], 1);
-          AddTesselationLine(TPS[1], TPS[2], 2);
-
-          BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
-          AddTesselationTriangle();  // add to global map
-
-          (*it)->OtherOptCenter.Scale(-1.);
-          BTS->GetNormalVector((*it)->OtherOptCenter);
-          (*it)->OtherOptCenter.Scale(-1.);
-
-          Log() << Verbose(0) << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector
-          << " for this triangle ... " << endl;
-          Log() << Verbose(1) << "We have "<< BaseRay->triangles.size() << " for line " << BaseRay << "." << endl;
-        } else {
-          Log() << Verbose(1) << "WARNING: 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 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)) {
-      Log() << Verbose(1) << "CRITICAL: 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);
-  Log() << Verbose(0) << "End of FindNextSuitableTriangle\n";
-  return result;
+      // 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.CopyVector(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.SubtractVector(&CandidateLine.OptCenter);
+  BTS->SphereCenter.CopyVector(&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.CopyVector(&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.CopyVector(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.
@@ -1896,17 +2778,18 @@
 class BoundaryPointSet *Tesselation::IsConvexRectangle(class BoundaryLineSet *Base)
 {
+  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(3) << "INFO: Current base line is " << *Base << "." << endl;
-  Log() << Verbose(3) << "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
@@ -1914,5 +2797,5 @@
 
   // delete the temporary other base line
-  delete(OtherBase);
+  delete (OtherBase);
 
   // get the distance vector from Base line to OtherBase line
@@ -1921,12 +2804,12 @@
   BaseLine.CopyVector(Base->endpoints[1]->node->node);
   BaseLine.SubtractVector(Base->endpoints[0]->node->node);
-  for (int i=0;i<2;i++) {
+  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(3) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1]  << ". " << *Base << "' rectangle is concave." << endl;
+  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];
@@ -1935,34 +2818,41 @@
     }
     return Spot;
-  } else {  // different sign, i.e. we are in between
-    Log() << Verbose(3) << "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__);
   // print all lines
-  Log() << Verbose(1) << "Printing all boundary points for debugging:" << endl;
-  for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
-    Log() << Verbose(2) << *(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__);
   // print all lines
-  Log() << Verbose(1) << "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(2) << *(LineRunner->second) << endl;
-};
+    DoLog(0) && (Log() << Verbose(0) << *(LineRunner->second) << endl);
+}
+;
 
 void Tesselation::PrintAllBoundaryTriangles(ofstream *out) const
 {
+  Info FunctionInfo(__func__);
   // print all triangles
-  Log() << Verbose(1) << "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(2) << *(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".
@@ -1973,17 +2863,18 @@
 double Tesselation::PickFarthestofTwoBaselines(class BoundaryLineSet *Base)
 {
+  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(3) << "INFO: Current base line is " << *Base << "." << endl;
-  Log() << Verbose(3) << "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
@@ -2000,10 +2891,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(3) << "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
@@ -2011,23 +2902,24 @@
     BaseLineNormal.Zero();
     if (Base->triangles.size() < 2) {
-      Log() << Verbose(2) << "ERROR: 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(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl);
       BaseLineNormal.AddVector(&(runner->second->NormalVector));
     }
-    BaseLineNormal.Scale(1./2.);
+    BaseLineNormal.Scale(1. / 2.);
 
     if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
-      Log() << Verbose(2) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
+      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(2) << "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.
@@ -2040,71 +2932,70 @@
 class BoundaryLineSet * Tesselation::FlipBaseline(class BoundaryLineSet *Base)
 {
+  Info FunctionInfo(__func__);
   class BoundaryLineSet *OldLines[4], *NewLine;
   class BoundaryPointSet *OldPoints[2];
   Vector BaseLineNormal;
   int OldTriangleNrs[2], OldBaseLineNr;
-  int i,m;
-
-  Log() << Verbose(1) << "Begin of FlipBaseline" << endl;
+  int i, m;
 
   // calculate NormalVector for later use
   BaseLineNormal.Zero();
   if (Base->triangles.size() < 2) {
-    Log() << Verbose(2) << "ERROR: 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(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
+    DoLog(1) && (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()
+  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(3) << "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(3) << "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) {
-    Log() << Verbose(1) << "ERROR: 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) {
-      Log() << Verbose(1) << "ERROR: 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) {
-      Log() << Verbose(1) << "ERROR: 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(3) << "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(3) << "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);
@@ -2116,13 +3007,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(3) << "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];
@@ -2131,7 +3022,7 @@
     BTS->GetNormalVector(BaseLineNormal);
     AddTesselationTriangle(OldTriangleNrs[0]);
-    Log() << Verbose(3) << "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;
@@ -2139,14 +3030,13 @@
     BTS->GetNormalVector(BaseLineNormal);
     AddTesselationTriangle(OldTriangleNrs[1]);
-    Log() << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
+    DoLog(0) && (Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl);
   } else {
-    Log() << Verbose(1) << "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;
   }
 
-  Log() << Verbose(1) << "End of FlipBaseline" << endl;
   return NewLine;
-};
-
+}
+;
 
 /** Finds the second point of starting triangle.
@@ -2160,5 +3050,5 @@
 void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell *LC)
 {
-  Log() << Verbose(2) << "Begin of FindSecondPointForTesselation" << endl;
+  Info FunctionInfo(__func__);
   Vector AngleCheck;
   class TesselPoint* Candidate = NULL;
@@ -2169,32 +3059,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(0) << "ERROR: 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
-  Log() << Verbose(3) << "LC Intervals from [";
-  for (int i=0;i<NDIM;i++) {
-  Log() << Verbose(0) << " " << N[i] << "<->" << LC->N[i];
-  }
-  Log() << Verbose(0) << "] :";
-  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] << "] ";
-  }
-  Log() << Verbose(0) << 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();
-        //Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
+        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 ...
@@ -2222,29 +3105,28 @@
               norm = aCandidate.Norm();
               // second point shall have smallest angle with respect to Oben vector
-              if (norm < RADIUS*2.) {
+              if (norm < RADIUS * 2.) {
                 angle = AngleCheck.Angle(&Oben);
                 if (angle < Storage[0]) {
-                  //Log() << Verbose(3) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
-                  Log() << Verbose(3) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
+                  //Log() << Verbose(1) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
+                  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;
-                  //Log() << Verbose(3) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
+                  //Log() << Verbose(1) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
                 } else {
-                  //Log() << Verbose(3) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
+                  //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
                 }
               } else {
-                //Log() << Verbose(3) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
+                //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
               }
             } else {
-              //Log() << Verbose(3) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
+              //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
             }
           }
         } else {
-          Log() << Verbose(3) << "Linked cell list is empty." << endl;
+          DoLog(0) && (Log() << Verbose(0) << "Linked cell list is empty." << endl);
         }
       }
-  Log() << Verbose(2) << "End of FindSecondPointForTesselation" << endl;
-};
-
+}
+;
 
 /** This recursive function finds a third point, to form a triangle with two given ones.
@@ -2273,76 +3155,83 @@
  * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
  * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
- * @param BaseLine BoundaryLineSet with the current base line
- * @param ThirdNode third point to avoid in search
- * @param candidates list of equally good candidates to return
- * @param ShortestAngle the current path length on this circle band for the current OptCandidate
+ * @param CandidateLine CandidateForTesselation with the current base line and list of candidates and ShortestAngle
+ * @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, class BoundaryLineSet *BaseLine, class TesselPoint  *ThirdNode, CandidateList* &candidates, double *ShortestAngle, const double RADIUS, const LinkedCell *LC)
-{
-  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;
+  Vector NewPlaneCenter;
   double CircleRadius; // radius of this circle
   double radius;
+  double otherradius;
   double alpha, Otheralpha; // angles (i.e. parameter for the circle).
   int N[NDIM], Nlower[NDIM], Nupper[NDIM];
   TesselPoint *Candidate = NULL;
-  CandidateForTesselation *optCandidate = NULL;
-
-  Log() << Verbose(1) << "Begin of FindThirdPointForTesselation" << endl;
-
-  Log() << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
+
+  DoLog(1) && (Log() << Verbose(1) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl);
+
+  // copy old center
+  CandidateLine.OldCenter.CopyVector(&OldSphereCenter);
+  CandidateLine.ThirdPoint = ThirdPoint;
+  CandidateLine.pointlist.clear();
 
   // construct center of circle
-  CircleCenter.CopyVector(BaseLine->endpoints[0]->node->node);
-  CircleCenter.AddVector(BaseLine->endpoints[1]->node->node);
+  CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
+  CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
   CircleCenter.Scale(0.5);
 
   // construct normal vector of circle
-  CirclePlaneNormal.CopyVector(BaseLine->endpoints[0]->node->node);
-  CirclePlaneNormal.SubtractVector(BaseLine->endpoints[1]->node->node);
-
-  // calculate squared radius TesselPoint *ThirdNode,f circle
-  radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
-  if (radius/4. < RADIUS*RADIUS) {
-    CircleRadius = RADIUS*RADIUS - radius/4.;
+  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 *ThirdPoint,f circle
+  radius = CirclePlaneNormal.NormSquared() / 4.;
+  if (radius < RADIUS * RADIUS) {
+    CircleRadius = RADIUS * RADIUS - radius;
     CirclePlaneNormal.Normalize();
-    //Log() << Verbose(2) << "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(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
-      eLog() << Verbose(0) << "ERROR: Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
-      OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
-    }
-    radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
+    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(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
+      DoLog(1) && (Log() << Verbose(1) << "INFO: RelativeOldSphereCenter is at " << RelativeOldSphereCenter << "." << endl);
 
       // check SearchDirection
-      //Log() << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
-      if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {  // rotated the wrong way!
-        eLog() << Verbose(0) << "ERROR: 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];
-        //Log() << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
+        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(0) << "ERROR: 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(2) << "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;
+      //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;
         //Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
       }
@@ -2351,89 +3240,91 @@
         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();
-            //Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
+            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 << " at " << Candidate->node << "." << endl;
-                if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
-
-                  // construct both new centers
-                  GetCenterofCircumcircle(&NewSphereCenter, *BaseLine->endpoints[0]->node->node, *BaseLine->endpoints[1]->node->node, *Candidate->node);
-                  OtherNewSphereCenter.CopyVector(&NewSphereCenter);
-
-                  if ((NewNormalVector.MakeNormalVector(BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node))
-                  && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
-                  ) {
-                    helper.CopyVector(&NewNormalVector);
-                    //Log() << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
-                    radius = BaseLine->endpoints[0]->node->node->DistanceSquared(&NewSphereCenter);
-                    if (radius < RADIUS*RADIUS) {
-                      helper.Scale(sqrt(RADIUS*RADIUS - radius));
-                      //Log() << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
-                      NewSphereCenter.AddVector(&helper);
-                      NewSphereCenter.SubtractVector(&CircleCenter);
-                      //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);
-                      OtherNewSphereCenter.SubtractVector(&CircleCenter);
-                      //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 (*ShortestAngle > (alpha - HULLEPSILON)) {
-                        optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
-                        if (fabs(alpha - Otheralpha) > MYEPSILON) {
-                          optCandidate->OptCenter.CopyVector(&NewSphereCenter);
-                          optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
+                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);
+                  DoLog(1) && (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)) {
+                    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.CopyVector(&NewPlaneCenter);
+                        OtherNewSphereCenter.CopyVector(&NewPlaneCenter);
+                        helper.CopyVector(&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.AddVector(&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.AddVector(&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.CopyVector(&NewSphereCenter);
+                            CandidateLine.OtherOptCenter.CopyVector(&OtherNewSphereCenter);
+                          } else {
+                            CandidateLine.OptCenter.CopyVector(&OtherNewSphereCenter);
+                            CandidateLine.OtherOptCenter.CopyVector(&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 {
-                          optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
-                          optCandidate->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 ((*ShortestAngle - HULLEPSILON) < alpha) {
-                          candidates->push_back(optCandidate);
-                          Log() << Verbose(2) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
-                            << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
-                        } else {
-                          // remove all candidates from the list and then the list itself
-                          class CandidateForTesselation *remover = NULL;
-                          for (CandidateList::iterator it = candidates->begin(); it != candidates->end(); ++it) {
-                            remover = *it;
-                            delete(remover);
-                          }
-                          candidates->clear();
-                          candidates->push_back(optCandidate);
-                          Log() << Verbose(2) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
-                            << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
-                        }
-                        *ShortestAngle = alpha;
-                        //Log() << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
                       } else {
-                        if ((optCandidate != NULL) && (optCandidate->point != NULL)) {
-                          //Log() << Verbose(2) << "REJECT: Old candidate " << *(optCandidate->point) << " with " << *ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
-                        } else {
-                          //Log() << Verbose(2) << "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(2) << "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 {
-                    //Log() << Verbose(2) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
+                    DoLog(1) && (Log() << Verbose(1) << "REJECT: Three points from " << *CandidateLine.BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl);
                   }
                 } else {
-                  if (ThirdNode != NULL) {
-                    //Log() << Verbose(2) << "REJECT: Base triangle " << *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(2) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
+                    DoLog(1) && (Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " contains Candidate " << *Candidate << "." << endl);
                   }
                 }
@@ -2442,21 +3333,25 @@
           }
     } else {
-      eLog() << Verbose(2) << "ERROR: 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(2) << "Circumcircle for base line " << *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(2) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
-  }
-
-  //Log() << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
-  if (candidates->size() > 1) {
-    candidates->unique();
-    candidates->sort(SortCandidates);
-  }
-
-  Log() << Verbose(1) << "End of FindThirdPointForTesselation" << 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.
@@ -2467,106 +3362,230 @@
 class BoundaryPointSet *Tesselation::GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const
 {
+  Info FunctionInfo(__func__);
   const BoundaryLineSet * lines[2] = { line1, line2 };
   class BoundaryPointSet *node = NULL;
-  map<int, class BoundaryPointSet *> OrderMap;
-  pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
+  PointMap OrderMap;
+  PointTestPair OrderTest;
   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(5) << "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.
+ * \param *out output stream for debugging
+ * \param *x Vector to look from
+ * \return map of BoundaryPointSet of closest points sorted by squared distance or NULL.
+ */
+DistanceToPointMap * Tesselation::FindClosestBoundaryPointsToVector(const Vector *x, const LinkedCell* LC) const
+{
+  Info FunctionInfo(__func__);
+  PointMap::const_iterator FindPoint;
+  int N[NDIM], Nlower[NDIM], Nupper[NDIM];
+
+  if (LinesOnBoundary.empty()) {
+    DoeLog(1) && (eLog() << Verbose(1) << "There is no tesselation structure to compare the point with, please create one first." << endl);
+    return NULL;
+  }
+
+  // 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
+    N[i] = LC->n[i];
+  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);
+  //Log() << Verbose(1) << 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 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 (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));
+              DoLog(1) && (Log() << Verbose(1) << "INFO: Putting " << *FindPoint->second << " into the list." << endl);
+            }
           }
+        } else {
+          DoeLog(1) && (eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl);
+        }
       }
-  return node;
-};
+
+  // check whether we found some points
+  if (points->empty()) {
+    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.
+ * \param *out output stream for debugging
+ * \param *x Vector to look from
+ * \return closest BoundaryLineSet or NULL in degenerate case.
+ */
+BoundaryLineSet * Tesselation::FindClosestBoundaryLineToVector(const Vector *x, const LinkedCell* LC) const
+{
+  Info FunctionInfo(__func__);
+  // get closest points
+  DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x, LC);
+  if (points == NULL) {
+    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
+  DoLog(1) && (Log() << Verbose(1) << "Finding closest BoundaryLine to " << *x << " ... " << endl);
+  BoundaryLineSet *ClosestLine = NULL;
+  double MinDistance = -1.;
+  Vector helper;
+  Vector Center;
+  Vector BaseLine;
+  for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
+    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);
+      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
+          ClosestLine = LineRunner->second;
+          MinDistance = distance;
+          DoLog(1) && (Log() << Verbose(1) << "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl);
+        } else {
+          DoLog(1) && (Log() << Verbose(1) << "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << "." << endl);
+        }
+      } else {
+        DoLog(1) && (Log() << Verbose(1) << "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << "." << endl);
+      }
+    }
+  }
+  delete (points);
+  // check whether closest line is "too close" :), then it's inside
+  if (ClosestLine == NULL) {
+    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.
  * \param *out output stream for debugging
  * \param *x Vector to look from
- * \return list of BoundaryTriangleSet of nearest triangles or NULL in degenerate case.
- */
-list<BoundaryTriangleSet*> * Tesselation::FindClosestTrianglesToPoint(const Vector *x, const LinkedCell* LC) const
-{
-  TesselPoint *trianglePoints[3];
-  TesselPoint *SecondPoint = NULL;
-  list<BoundaryTriangleSet*> *triangles = NULL;
-
-  if (LinesOnBoundary.empty()) {
-    Log() << Verbose(0) << "Error: There is no tesselation structure to compare the point with, please create one first.";
+ * \return BoundaryTriangleSet of nearest triangle or NULL.
+ */
+TriangleList * Tesselation::FindClosestTrianglesToVector(const Vector *x, const LinkedCell* LC) const
+{
+  Info FunctionInfo(__func__);
+  // get closest points
+  DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x, LC);
+  if (points == NULL) {
+    DoeLog(1) && (eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl);
     return NULL;
   }
-  Log() << Verbose(1) << "Finding closest Tesselpoint to " << *x << " ... " << endl;
-  trianglePoints[0] = FindClosestPoint(x, SecondPoint, LC);
-  
-  // check whether closest point is "too close" :), then it's inside
-  if (trianglePoints[0] == NULL) {
-    Log() << Verbose(2) << "Is the only point, no one else is closeby." << endl;
+
+  // for each point, check its lines, remember closest
+  DoLog(1) && (Log() << Verbose(1) << "Finding closest BoundaryTriangle to " << *x << " ... " << endl);
+  LineSet ClosestLines;
+  double MinDistance = 1e+16;
+  Vector BaseLineIntersection;
+  Vector Center;
+  Vector BaseLine;
+  Vector BaseLineCenter;
+  for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
+    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);
+      const double lengthBase = BaseLine.NormSquared();
+
+      BaseLineIntersection.CopyVector(x);
+      BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
+      const double lengthEndA = BaseLineIntersection.NormSquared();
+
+      BaseLineIntersection.CopyVector(x);
+      BaseLineIntersection.SubtractVector((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
+        const double lengthEnd = Min(lengthEndA, lengthEndB);
+        if (lengthEnd - MinDistance < -MYEPSILON) { // new best line
+          ClosestLines.clear();
+          ClosestLines.insert(LineRunner->second);
+          MinDistance = lengthEnd;
+          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);
+          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
+          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);
+        const double distance = BaseLineIntersection.NormSquared();
+        if (Center.NormSquared() > BaseLine.NormSquared()) {
+          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;
+          DoLog(1) && (Log() << Verbose(1) << "ACCEPT: Intersection in between endpoints, new closest line " << *LineRunner->second << " is " << *ClosestLines.begin() << " with projected distance " << MinDistance << "." << endl);
+        } else {
+          DoLog(2) && (Log() << Verbose(2) << "REJECT: Point is further away from line " << *LineRunner->second << " than present closest line: " << distance << " >> " << MinDistance << "." << endl);
+        }
+      }
+    }
+  }
+  delete (points);
+
+  // check whether closest line is "too close" :), then it's inside
+  if (ClosestLines.empty()) {
+    DoLog(0) && (Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl);
     return NULL;
   }
-  if (trianglePoints[0]->node->DistanceSquared(x) < MYEPSILON) {
-    Log() << Verbose(3) << "Point is right on a tesselation point, no nearest triangle." << endl;
-    PointMap::const_iterator PointRunner = PointsOnBoundary.find(trianglePoints[0]->nr);
-    triangles = new list<BoundaryTriangleSet*>;
-    if (PointRunner != PointsOnBoundary.end()) {
-      for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
-        for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
-          triangles->push_back(TriangleRunner->second);
-      triangles->sort();
-      triangles->unique();
-    } else {
-      PointRunner = PointsOnBoundary.find(SecondPoint->nr);
-      trianglePoints[0] = SecondPoint;
-      if (PointRunner != PointsOnBoundary.end()) {
-        for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
-          for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
-            triangles->push_back(TriangleRunner->second);
-        triangles->sort();
-        triangles->unique();
-      } else {
-        Log() << Verbose(1) << "ERROR: I cannot find a boundary point to the tessel point " << *trianglePoints[0] << "." << endl;
-        return NULL;
-      }
-    }
-  } else {
-    list<TesselPoint*> *connectedClosestPoints = GetCircleOfConnectedPoints(trianglePoints[0], x);
-    if (connectedClosestPoints != NULL) {
-      trianglePoints[1] = connectedClosestPoints->front();
-      trianglePoints[2] = connectedClosestPoints->back();
-      for (int i=0;i<3;i++) {
-        if (trianglePoints[i] == NULL) {
-          Log() << Verbose(1) << "ERROR: IsInnerPoint encounters serious error, point " << i << " not found." << endl;
-        }
-        //Log() << Verbose(2) << "List of triangle points:" << endl;
-        //Log() << Verbose(3) << *trianglePoints[i] << endl;
-      }
-
-      triangles = FindTriangles(trianglePoints);
-      Log() << Verbose(2) << "List of possible triangles:" << endl;
-      for(list<BoundaryTriangleSet*>::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
-        Log() << Verbose(3) << **Runner << endl;
-
-      delete(connectedClosestPoints);
-    } else {
-      triangles = NULL;
-      Log() << Verbose(1) << "There is no circle of connected points!" << endl;
-    }
-  }
-  
-  if ((triangles == NULL) || (triangles->empty())) {
-    Log() << Verbose(0) << "ERROR: There is no nearest triangle. Please check the tesselation structure.";
-    delete(triangles);
-    return NULL;
-  } else
-    return triangles;
-};
+  TriangleList * candidates = new TriangleList;
+  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);
+    }
+  return candidates;
+}
+;
 
 /** Finds closest triangle to a point.
@@ -2574,76 +3593,157 @@
  * \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::FindClosestTriangleToPoint(const Vector *x, const LinkedCell* LC) const
-{
+class BoundaryTriangleSet * Tesselation::FindClosestTriangleToVector(const Vector *x, const LinkedCell* LC) const
+{
+  Info FunctionInfo(__func__);
   class BoundaryTriangleSet *result = NULL;
-  list<BoundaryTriangleSet*> *triangles = FindClosestTrianglesToPoint(x, LC);
+  TriangleList *triangles = FindClosestTrianglesToVector(x, LC);
+  TriangleList candidates;
   Vector Center;
-
-  if (triangles == NULL)
+  Vector helper;
+
+  if ((triangles == NULL) || (triangles->empty()))
     return NULL;
 
-  if (triangles->size() == 1) { // there is no degenerate case
-    result = triangles->front();
-    Log() << Verbose(2) << "Normal Vector of this triangle is " << result->NormalVector << "." << endl;
-  } else {
-    result = triangles->front();
-    result->GetCenter(&Center);
-    Center.SubtractVector(x);
-    Log() << Verbose(2) << "Normal Vector of this front side is " << result->NormalVector << "." << endl;
-    if (Center.ScalarProduct(&result->NormalVector) < 0) {
-      result = triangles->back();
-      Log() << Verbose(2) << "Normal Vector of this back side is " << result->NormalVector << "." << endl;
-      if (Center.ScalarProduct(&result->NormalVector) < 0) {
-        Log() << Verbose(1) << "ERROR: Front and back side yield NormalVector in wrong direction!" << endl;
-      }
-    }
-  }
-  delete(triangles);
+  // go through all and pick the one with the best alignment to x
+  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);
+    if (Alignment < MinAlignment) {
+      result = *Runner;
+      MinAlignment = Alignment;
+      DoLog(1) && (Log() << Verbose(1) << "ACCEPT: Triangle " << *result << " is better aligned with " << MinAlignment << "." << endl);
+    } else {
+      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.
+}
+;
+
+/** Checks whether the provided Vector is within the Tesselation structure.
+ * Basically calls Tesselation::GetDistanceToSurface() and checks the sign of the return value.
+ * @param point of which to check the position
+ * @param *LC LinkedCell structure
+ *
+ * @return true if the point is inside the Tesselation structure, false otherwise
+ */
+bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell* const LC) const
+{
+  Info FunctionInfo(__func__);
+  TriangleIntersectionList Intersections(&Point, this, LC);
+
+  return Intersections.IsInside();
+}
+;
+
+/** Returns the distance to the surface given by the tesselation.
+ * Calls FindClosestTriangleToVector() and checks whether the resulting triangle's BoundaryTriangleSet#NormalVector points
+ * towards or away from the given \a &Point. Additionally, we check whether it's normal to the normal vector, i.e. on the
+ * closest triangle's plane. Then, we have to check whether \a Point is inside the triangle or not to determine whether it's
+ * an inside or outside point. This is done by calling BoundaryTriangleSet::GetIntersectionInsideTriangle().
+ * In the end we additionally find the point on the triangle who was smallest distance to \a Point:
+ *  -# Separate distance from point to center in vector in NormalDirection and on the triangle plane.
+ *  -# Check whether vector on triangle plane points inside the triangle or crosses triangle bounds.
+ *  -# If inside, take it to calculate closest distance
+ *  -# If not, take intersection with BoundaryLine as distance
+ *
+ * @note distance is squared despite it still contains a sign to determine in-/outside!
  *
  * @param point of which to check the position
  * @param *LC LinkedCell structure
  *
- * @return true if the point is inside the tesselation structure, false otherwise
- */
-bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell* const LC) const
-{
-  class BoundaryTriangleSet *result = FindClosestTriangleToPoint(&Point, LC);
+ * @return >0 if outside, ==0 if on surface, <0 if inside
+ */
+double Tesselation::GetDistanceSquaredToTriangle(const Vector &Point, const BoundaryTriangleSet* const triangle) const
+{
+  Info FunctionInfo(__func__);
   Vector Center;
-
-  if (result == NULL) {// is boundary point or only point in point cloud?
-    Log() << Verbose(1) << Point << " is the only point in vicinity." << endl;
-    return false;
-  }
-
-  result->GetCenter(&Center);
-  Log() << Verbose(3) << "INFO: Central point of the triangle is " << Center << "." << endl;
-  Center.SubtractVector(&Point);
-  Log() << Verbose(3) << "INFO: Vector from center to point to test is " << Center << "." << endl;
-  if (Center.ScalarProduct(&result->NormalVector) > -MYEPSILON) {
-    Log() << Verbose(1) << Point << " is an inner point." << endl;
-    return true;
+  Vector helper;
+  Vector DistanceToCenter;
+  Vector Intersection;
+  double distance = 0.;
+
+  if (triangle == NULL) {// is boundary point or only point in point cloud?
+    DoLog(1) && (Log() << Verbose(1) << "No triangle given!" << endl);
+    return -1.;
   } else {
-    Log() << Verbose(1) << Point << " is NOT an inner point." << endl;
-    return false;
-  }
-}
-
-/** Checks whether the provided TesselPoint is within the tesselation structure.
- *
- * @param *Point of which to check the position
- * @param *LC Linked Cell structure
- *
- * @return true if the point is inside the tesselation structure, false otherwise
- */
-bool Tesselation::IsInnerPoint(const TesselPoint * const Point, const LinkedCell* const LC) const
-{
-  return IsInnerPoint(*(Point->node), LC);
-}
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Closest triangle found is " << *triangle << " with normal vector " << triangle->NormalVector << "." << endl);
+  }
+
+  triangle->GetCenter(&Center);
+  DoLog(2) && (Log() << Verbose(2) << "INFO: Central point of the triangle is " << Center << "." << endl);
+  DistanceToCenter.CopyVector(&Center);
+  DistanceToCenter.SubtractVector(&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) {
+    // calculate whether inside of triangle
+    DistanceToCenter.CopyVector(&Point);
+    Center.CopyVector(&Point);
+    Center.SubtractVector(&triangle->NormalVector); // points towards MolCenter
+    DistanceToCenter.AddVector(&triangle->NormalVector); // points outside
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Calling Intersection with " << Center << " and " << DistanceToCenter << "." << endl);
+    if (triangle->GetIntersectionInsideTriangle(&Center, &DistanceToCenter, &Intersection)) {
+      DoLog(1) && (Log() << Verbose(1) << Point << " is inner point: sufficiently close to boundary, " << Intersection << "." << endl);
+      return 0.;
+    } else {
+      DoLog(1) && (Log() << Verbose(1) << Point << " is NOT an inner point: on triangle plane but outside of triangle bounds." << endl);
+      return false;
+    }
+  } else {
+    // calculate smallest distance
+    distance = triangle->GetClosestPointInsideTriangle(&Point, &Intersection);
+    DoLog(1) && (Log() << Verbose(1) << "Closest point on triangle is " << Intersection << "." << endl);
+
+    // then check direction to boundary
+    if (DistanceToCenter.ScalarProduct(&triangle->NormalVector) > MYEPSILON) {
+      DoLog(1) && (Log() << Verbose(1) << Point << " is an inner point, " << distance << " below surface." << endl);
+      return -distance;
+    } else {
+      DoLog(1) && (Log() << Verbose(1) << Point << " is NOT an inner point, " << distance << " above surface." << endl);
+      return +distance;
+    }
+  }
+}
+;
+
+/** 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
+ */
+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.
@@ -2653,13 +3753,11 @@
  * @return set of the all points linked to the provided one
  */
-set<TesselPoint*> * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
-{
-  set<TesselPoint*> *connectedPoints = new set<TesselPoint*>;
+TesselPointSet * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
+{
+  Info FunctionInfo(__func__);
+  TesselPointSet *connectedPoints = new TesselPointSet;
   class BoundaryPointSet *ReferencePoint = NULL;
   TesselPoint* current;
   bool takePoint = false;
-
-  Log() << Verbose(3) << "Begin of GetAllConnectedPoints" << endl;
-
   // find the respective boundary point
   PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
@@ -2667,5 +3765,5 @@
     ReferencePoint = PointRunner->second;
   } else {
-    Log() << 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;
   }
@@ -2673,5 +3771,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);
@@ -2680,31 +3779,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(5) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
-     connectedPoints->insert(current);
-   }
-
-   findLines++;
-  }
-
-  if (connectedPoints->size() == 0) { // if have not found any points
-    Log() << Verbose(1) << "ERROR: We have not found any connected points to " << *Point<< "." << endl;
+    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
+    DoeLog(1) && (eLog() << Verbose(1) << "We have not found any connected points to " << *Point << "." << endl);
     return NULL;
   }
 
-  Log() << Verbose(3) << "End of GetAllConnectedPoints" << endl;
   return connectedPoints;
-};
-
+}
+;
 
 /** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
@@ -2715,13 +3813,96 @@
  *
  * @param *out output stream for debugging
+ * @param *SetOfNeighbours all points for which the angle should be calculated
  * @param *Point of which get all connected points
  * @param *Reference Reference vector for zero angle or NULL for no preference
  * @return list of the all points linked to the provided one
  */
-list<TesselPoint*> * Tesselation::GetCircleOfConnectedPoints(const TesselPoint* const Point, const Vector * const Reference) const
-{
+TesselPointList * Tesselation::GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
+{
+  Info FunctionInfo(__func__);
   map<double, TesselPoint*> anglesOfPoints;
-  set<TesselPoint*> *connectedPoints = GetAllConnectedPoints(Point);
-  list<TesselPoint*> *connectedCircle = new list<TesselPoint*>;
+  TesselPointList *connectedCircle = new TesselPointList;
+  Vector PlaneNormal;
+  Vector AngleZero;
+  Vector OrthogonalVector;
+  Vector helper;
+  const TesselPoint * const TrianglePoints[3] = { Point, NULL, NULL };
+  TriangleList *triangles = NULL;
+
+  if (SetOfNeighbours == NULL) {
+    DoeLog(2) && (eLog() << Verbose(2) << "Could not find any connected points!" << endl);
+    delete (connectedCircle);
+    return NULL;
+  }
+
+  // calculate central point
+  triangles = FindTriangles(TrianglePoints);
+  if ((triangles != NULL) && (!triangles->empty())) {
+    for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
+      PlaneNormal.AddVector(&(*Runner)->NormalVector);
+  } else {
+    DoeLog(0) && (eLog() << Verbose(0) << "Could not find any triangles for point " << *Point << "." << endl);
+    performCriticalExit();
+  }
+  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)) {
+    DoLog(1) && (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);
+    if (AngleZero.NormSquared() < MYEPSILON) {
+      DoeLog(0) && (eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl);
+      performCriticalExit();
+    }
+  }
+  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);
+  else
+    OrthogonalVector.MakeNormalVector(&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);
+    double angle = GetAngle(helper, AngleZero, OrthogonalVector);
+    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);
+  }
+
+  return connectedCircle;
+}
+
+/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
+ * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
+ * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
+ * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
+ * triangle we are looking for.
+ *
+ * @param *SetOfNeighbours all points for which the angle should be calculated
+ * @param *Point of which get all connected points
+ * @param *Reference Reference vector for zero angle or NULL for no preference
+ * @return list of the all points linked to the provided one
+ */
+TesselPointList * Tesselation::GetCircleOfSetOfPoints(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
+{
+  Info FunctionInfo(__func__);
+  map<double, TesselPoint*> anglesOfPoints;
+  TesselPointList *connectedCircle = new TesselPointList;
   Vector center;
   Vector PlaneNormal;
@@ -2730,24 +3911,45 @@
   Vector helper;
 
-  if (connectedPoints == NULL) {
-    Log() << Verbose(2) << "Could not find any connected points!" << endl;
-    delete(connectedCircle);
+  if (SetOfNeighbours == NULL) {
+    DoeLog(2) && (eLog() << Verbose(2) << "Could not find any connected points!" << endl);
+    delete (connectedCircle);
     return NULL;
   }
-  Log() << Verbose(2) << "Begin of GetCircleOfConnectedPoints" << endl;
-
+
+  // check whether there's something to do
+  if (SetOfNeighbours->size() < 3) {
+    for (TesselPointSet::iterator TesselRunner = SetOfNeighbours->begin(); TesselRunner != SetOfNeighbours->end(); TesselRunner++)
+      connectedCircle->push_back(*TesselRunner);
+    return connectedCircle;
+  }
+
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Point is " << *Point << " and Reference is " << *Reference << "." << endl);
   // calculate central point
-  for (set<TesselPoint*>::const_iterator TesselRunner = connectedPoints->begin(); TesselRunner != connectedPoints->end(); TesselRunner++)
-    center.AddVector((*TesselRunner)->node);
+  TesselPointSet::const_iterator TesselA = SetOfNeighbours->begin();
+  TesselPointSet::const_iterator TesselB = SetOfNeighbours->begin();
+  TesselPointSet::const_iterator TesselC = SetOfNeighbours->begin();
+  TesselB++;
+  TesselC++;
+  TesselC++;
+  int counter = 0;
+  while (TesselC != SetOfNeighbours->end()) {
+    helper.MakeNormalVector((*TesselA)->node, (*TesselB)->node, (*TesselC)->node);
+    DoLog(0) && (Log() << Verbose(0) << "Making normal vector out of " << *(*TesselA) << ", " << *(*TesselB) << " and " << *(*TesselC) << ":" << helper << endl);
+    counter++;
+    TesselA++;
+    TesselB++;
+    TesselC++;
+    PlaneNormal.AddVector(&helper);
+  }
   //Log() << Verbose(0) << "Summed vectors " << center << "; number of points " << connectedPoints.size()
-  //  << "; scale factor " << 1.0/connectedPoints.size();
-  center.Scale(1.0/connectedPoints->size());
-  Log() << Verbose(4) << "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(4) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
+  //  << "; 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();
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl);
 
   // construct one orthogonal vector
@@ -2757,38 +3959,41 @@
     AngleZero.ProjectOntoPlane(&PlaneNormal);
   }
-  if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
-    Log() << Verbose(4) << "Using alternatively " << *(*connectedPoints->begin())->node << " as angle 0 referencer." << endl;
-    AngleZero.CopyVector((*connectedPoints->begin())->node);
+  if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON)) {
+    DoLog(1) && (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);
     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(4) << "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);
   else
     OrthogonalVector.MakeNormalVector(&PlaneNormal);
-  Log() << Verbose(4) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl);
 
   // go through all connected points and calculate angle
-  for (set<TesselPoint*>::iterator listRunner = connectedPoints->begin(); listRunner != connectedPoints->end(); listRunner++) {
+  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);
     double angle = GetAngle(helper, AngleZero, OrthogonalVector);
-    Log() << Verbose(3) << "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++) {
+    if (angle > M_PI) // the correction is of no use here (and not desired)
+      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) {
+      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++) {
     connectedCircle->push_back(AngleRunner->second);
   }
-
-  delete(connectedPoints);
-
-  Log() << Verbose(2) << "End of GetCircleOfConnectedPoints" << endl;
 
   return connectedCircle;
@@ -2801,9 +4006,10 @@
  * @return list of the all points linked to the provided one
  */
-list<list<TesselPoint*> *> * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
-{
+ListOfTesselPointList * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
+{
+  Info FunctionInfo(__func__);
   map<double, TesselPoint*> anglesOfPoints;
-  list<list<TesselPoint*> *> *ListOfPaths = new list<list<TesselPoint*> *>;
-  list<TesselPoint*> *connectedPath = NULL;
+  list<TesselPointList *> *ListOfPaths = new list<TesselPointList *> ;
+  TesselPointList *connectedPath = NULL;
   Vector center;
   Vector PlaneNormal;
@@ -2816,5 +4022,4 @@
   class BoundaryLineSet *CurrentLine = NULL;
   class BoundaryLineSet *StartLine = NULL;
-
   // find the respective boundary point
   PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
@@ -2822,16 +4027,16 @@
     ReferencePoint = PointRunner->second;
   } else {
-    Log() << Verbose(2) << "ERROR: 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()) {
@@ -2839,21 +4044,21 @@
       LineRunner = TouchedLine.find(runner->second);
       if (LineRunner == TouchedLine.end()) {
-        Log() << Verbose(2) << "ERROR: 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;
-        connectedPath = new list<TesselPoint*>;
+        connectedPath = new TesselPointList;
         triangle = NULL;
         CurrentLine = runner->second;
         StartLine = CurrentLine;
         CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
-        Log() << Verbose(3)<< "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(3) << "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(3) << "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;
@@ -2862,12 +4067,12 @@
                 if (!TriangleRunner->second) {
                   TriangleRunner->second = true;
-                  Log() << Verbose(3) << "INFO: Connecting triangle is " << *triangle << "." << endl;
+                  DoLog(1) && (Log() << Verbose(1) << "INFO: Connecting triangle is " << *triangle << "." << endl);
                   break;
                 } else {
-                  Log() << Verbose(3) << "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 {
-                Log() << Verbose(2) << "ERROR: 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;
               }
@@ -2877,8 +4082,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(3) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
+              DoLog(1) && (Log() << Verbose(1) << "INFO: Connecting line is " << *CurrentLine << "." << endl);
               break;
             }
@@ -2886,5 +4091,5 @@
           LineRunner = TouchedLine.find(CurrentLine);
           if (LineRunner == TouchedLine.end())
-            Log() << Verbose(2) << "ERROR: 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;
@@ -2894,5 +4099,5 @@
         } while (CurrentLine != StartLine);
         // last point is missing, as it's on start line
-        Log() << Verbose(3) << "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);
@@ -2900,9 +4105,9 @@
         ListOfPaths->push_back(connectedPath);
       } else {
-        Log() << Verbose(3) << "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 {
-    Log() << Verbose(1) << "ERROR: There are no lines attached to " << *ReferencePoint << "." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "There are no lines attached to " << *ReferencePoint << "." << endl);
   }
 
@@ -2916,37 +4121,35 @@
  * @return list of the closed paths
  */
-list<list<TesselPoint*> *> * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
-{
-  list<list<TesselPoint*> *> *ListofPaths = GetPathsOfConnectedPoints(Point);
-  list<list<TesselPoint*> *> *ListofClosedPaths = new list<list<TesselPoint*> *>;
-  list<TesselPoint*> *connectedPath = NULL;
-  list<TesselPoint*> *newPath = NULL;
+ListOfTesselPointList * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
+{
+  Info FunctionInfo(__func__);
+  list<TesselPointList *> *ListofPaths = GetPathsOfConnectedPoints(Point);
+  list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *> ;
+  TesselPointList *connectedPath = NULL;
+  TesselPointList *newPath = NULL;
   int count = 0;
-
-
-  list<TesselPoint*>::iterator CircleRunner;
-  list<TesselPoint*>::iterator CircleStart;
-
-  for(list<list<TesselPoint*> *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
+  TesselPointList::iterator CircleRunner;
+  TesselPointList::iterator CircleStart;
+
+  for (list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
     connectedPath = *ListRunner;
 
-    Log() << Verbose(2) << "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
-    list<TesselPoint*>::iterator Marker = CircleStart;
+    TesselPointList::iterator Marker = CircleStart;
     for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
       if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
         // we have a closed circle from Marker to new Marker
-        Log() << Verbose(3) << count+1 << ". closed path consists of: ";
-        newPath = new list<TesselPoint*>;
-        list<TesselPoint*>::iterator CircleSprinter = Marker;
+        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;
@@ -2957,5 +4160,5 @@
     }
   }
-  Log() << Verbose(3) << "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
@@ -2963,12 +4166,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.
@@ -2977,21 +4180,22 @@
  * \return pointer to allocated list of triangles
  */
-set<BoundaryTriangleSet*> *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
-{
-  set<BoundaryTriangleSet*> *connectedTriangles = new set<BoundaryTriangleSet*>;
+TriangleSet *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
+{
+  Info FunctionInfo(__func__);
+  TriangleSet *connectedTriangles = new TriangleSet;
 
   if (Point == NULL) {
-    Log() << Verbose(1) << "ERROR: 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.
@@ -3006,5 +4210,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;
@@ -3014,8 +4219,8 @@
 
   if (point == NULL) {
-    Log() << Verbose(1) << "ERROR: 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(2) << "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
@@ -3024,58 +4229,57 @@
   // get list of connected points
   if (point->lines.empty()) {
-    Log() << Verbose(1) << "ERROR: 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.;
   }
 
-  list<list<TesselPoint*> *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
-  list<TesselPoint*> *connectedPath = NULL;
+  list<TesselPointList *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
+  TesselPointList *connectedPath = NULL;
 
   // gather all triangles
   for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
-    count+=LineRunner->second->triangles.size();
-  map<class BoundaryTriangleSet *, int> Candidates;
+    count += LineRunner->second->triangles.size();
+  TriangleMap Candidates;
   for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
     line = LineRunner->second;
     for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
       triangle = TriangleRunner->second;
-      Candidates.insert( pair<class BoundaryTriangleSet *, int> (triangle, triangle->Nr) );
+      Candidates.insert(TrianglePair(triangle->Nr, triangle));
     }
   }
 
   // remove all triangles
-  count=0;
+  count = 0;
   NormalVector.Zero();
-  for (map<class BoundaryTriangleSet *, int>::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
-    Log() << Verbose(3) << "INFO: Removing triangle " << *(Runner->first) << "." << endl;
-    NormalVector.SubtractVector(&Runner->first->NormalVector); // has to point inward
-    RemoveTesselationTriangle(Runner->first);
+  for (TriangleMap::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
+    DoLog(1) && (Log() << Verbose(1) << "INFO: Removing triangle " << *(Runner->second) << "." << endl);
+    NormalVector.SubtractVector(&Runner->second->NormalVector); // has to point inward
+    RemoveTesselationTriangle(Runner->second);
     count++;
   }
-  Log() << Verbose(1) << count << " triangles were removed." << endl;
-
-  list<list<TesselPoint*> *>::iterator ListAdvance = ListOfClosedPaths->begin();
-  list<list<TesselPoint*> *>::iterator ListRunner = ListAdvance;
-  map<class BoundaryTriangleSet *, int>::iterator NumberRunner = Candidates.begin();
-  list<TesselPoint*>::iterator StartNode, MiddleNode, EndNode;
+  DoLog(1) && (Log() << Verbose(1) << count << " triangles were removed." << endl);
+
+  list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
+  list<TesselPointList *>::iterator ListRunner = ListAdvance;
+  TriangleMap::iterator NumberRunner = Candidates.begin();
+  TesselPointList::iterator StartNode, MiddleNode, EndNode;
   double angle;
   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
-      list<class BoundaryLineSet *> NewLines;
-      for (;!connectedPath->empty();) {
+      LineList NewLines;
+      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(3) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
+          DoLog(1) && (Log() << Verbose(1) << "INFO: MiddleNode is " << **MiddleNode << "." << endl);
           // construct vectors to next and previous neighbour
           StartNode = MiddleNode;
@@ -3098,13 +4302,13 @@
           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()) {
-          Log() << Verbose(1) << "CRITICAL: Could not find a smallest angle!" << endl;
-          exit(255);
+          DoeLog(0) && (eLog() << Verbose(0) << "CRITICAL: Could not find a smallest angle!" << endl);
+          performCriticalExit();
         }
         StartNode = MiddleNode;
@@ -3115,8 +4319,8 @@
         if (EndNode == connectedPath->end())
           EndNode = connectedPath->begin();
-        Log() << Verbose(4) << "INFO: StartNode is " << **StartNode << "." << endl;
-        Log() << Verbose(4) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
-        Log() << Verbose(4) << "INFO: EndNode is " << **EndNode << "." << endl;
-        Log() << Verbose(3) << "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;
@@ -3124,5 +4328,5 @@
         triangle = GetPresentTriangle(TriangleCandidates);
         if (triangle != NULL) {
-          Log() << Verbose(1) << "WARNING: New triangle already present, skipping!" << endl;
+          DoeLog(0) && (eLog() << Verbose(0) << "New triangle already present, skipping!" << endl);
           StartNode++;
           MiddleNode++;
@@ -3136,13 +4340,13 @@
           continue;
         }
-        Log() << Verbose(5) << "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(5) << "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);
@@ -3155,5 +4359,5 @@
         // prepare nodes for next triangle
         StartNode = EndNode;
-        Log() << Verbose(4) << "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
@@ -3162,6 +4366,6 @@
           break;
         } else if (connectedPath->size() < 2) { // something's gone wrong!
-          Log() << Verbose(1) << "CRITICAL: There are only two endpoints left!" << endl;
-          exit(255);
+          DoeLog(0) && (eLog() << Verbose(0) << "CRITICAL: There are only two endpoints left!" << endl);
+          performCriticalExit();
         } else {
           MiddleNode = StartNode;
@@ -3177,10 +4381,10 @@
       // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
       if (NewLines.size() > 1) {
-        list<class BoundaryLineSet *>::iterator Candidate;
+        LineList::iterator Candidate;
         class BoundaryLineSet *OtherBase = NULL;
         double tmp, maxgain;
         do {
           maxgain = 0;
-          for(list<class BoundaryLineSet *>::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
+          for (LineList::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
             tmp = PickFarthestofTwoBaselines(*Runner);
             if (maxgain < tmp) {
@@ -3191,5 +4395,5 @@
           if (maxgain != 0) {
             volume += maxgain;
-            Log() << Verbose(3) << "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);
@@ -3200,7 +4404,7 @@
 
       ListOfClosedPaths->remove(connectedPath);
-      delete(connectedPath);
-    }
-    Log() << Verbose(1) << count << " triangles were created." << endl;
+      delete (connectedPath);
+    }
+    DoLog(0) && (Log() << Verbose(0) << count << " triangles were created." << endl);
   } else {
     while (!ListOfClosedPaths->empty()) {
@@ -3208,66 +4412,145 @@
       connectedPath = *ListRunner;
       ListOfClosedPaths->remove(connectedPath);
-      delete(connectedPath);
-    }
-    Log() << Verbose(1) << "No need to create any triangles." << endl;
-  }
-  delete(ListOfClosedPaths);
-
-  Log() << Verbose(1) << "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;
-};
-
-
+}
+;
 
 /**
  * Finds triangles belonging to the three provided points.
  *
- * @param *Points[3] list, is expected to contain three points
+ * @param *Points[3] list, is expected to contain three points (NULL means wildcard)
  *
  * @return triangles which belong to the provided points, will be empty if there are none,
  *         will usually be one, in case of degeneration, there will be two
  */
-list<BoundaryTriangleSet*> *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
-{
-  list<BoundaryTriangleSet*> *result = new list<BoundaryTriangleSet*>;
+TriangleList *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
+{
+  Info FunctionInfo(__func__);
+  TriangleList *result = new TriangleList;
   LineMap::const_iterator FindLine;
   TriangleMap::const_iterator FindTriangle;
   class BoundaryPointSet *TrianglePoints[3];
+  size_t NoOfWildcards = 0;
 
   for (int i = 0; i < 3; i++) {
-    PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->nr);
-    if (FindPoint != PointsOnBoundary.end()) {
-      TrianglePoints[i] = FindPoint->second;
+    if (Points[i] == NULL) {
+      NoOfWildcards++;
+      TrianglePoints[i] = NULL;
     } else {
-      TrianglePoints[i] = NULL;
-    }
-  }
-
-  // checks lines between the points in the Points for their adjacent triangles
-  for (int i = 0; i < 3; i++) {
-    if (TrianglePoints[i] != NULL) {
-      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++) {
-              if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
-                result->push_back(FindTriangle->second);
+      PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->nr);
+      if (FindPoint != PointsOnBoundary.end()) {
+        TrianglePoints[i] = FindPoint->second;
+      } else {
+        TrianglePoints[i] = NULL;
+      }
+    }
+  }
+
+  switch (NoOfWildcards) {
+    case 0: // checks lines between the points in the Points for their adjacent triangles
+      for (int i = 0; i < 3; i++) {
+        if (TrianglePoints[i] != NULL) {
+          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++) {
+                  if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
+                    result->push_back(FindTriangle->second);
+                  }
+                }
               }
+              // Is it sufficient to consider one of the triangle lines for this.
+              return result;
             }
           }
-          // Is it sufficient to consider one of the triangle lines for this.
-          return result;
         }
       }
-    }
+      break;
+    case 1: // copy all triangles of the respective line
+    {
+      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++) {
+          if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
+            result->push_back(FindTriangle->second);
+          }
+        }
+      }
+      break;
+    }
+    case 2: // copy all triangles of the respective point
+    {
+      int i = 0;
+      for (; i < 3; i++)
+        if (TrianglePoints[i] != NULL)
+          break;
+      for (LineMap::const_iterator line = TrianglePoints[i]->lines.begin(); line != TrianglePoints[i]->lines.end(); line++)
+        for (TriangleMap::const_iterator triangle = line->second->triangles.begin(); triangle != line->second->triangles.end(); triangle++)
+          result->push_back(triangle->second);
+      result->sort();
+      result->unique();
+      break;
+    }
+    case 3: // copy all triangles
+    {
+      for (TriangleMap::const_iterator triangle = TrianglesOnBoundary.begin(); triangle != TrianglesOnBoundary.end(); triangle++)
+        result->push_back(triangle->second);
+      break;
+    }
+    default:
+      DoeLog(0) && (eLog() << Verbose(0) << "Number of wildcards is greater than 3, cannot happen!" << endl);
+      performCriticalExit();
+      break;
   }
 
   return result;
 }
+
+struct BoundaryLineSetCompare
+{
+  bool operator()(const BoundaryLineSet * const a, const BoundaryLineSet * const b)
+  {
+    int lowerNra = -1;
+    int lowerNrb = -1;
+
+    if (a->endpoints[0] < a->endpoints[1])
+      lowerNra = 0;
+    else
+      lowerNra = 1;
+
+    if (b->endpoints[0] < b->endpoints[1])
+      lowerNrb = 0;
+    else
+      lowerNrb = 1;
+
+    if (a->endpoints[lowerNra] < b->endpoints[lowerNrb])
+      return true;
+    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;
+    }
+    return false;
+  }
+  ;
+};
+
+#define UniqueLines set < class BoundaryLineSet *, BoundaryLineSetCompare>
 
 /**
@@ -3277,22 +4560,22 @@
  *         in the list, once as key and once as value
  */
-map<int, int> * Tesselation::FindAllDegeneratedLines()
-{
-  map<int, class BoundaryLineSet *> AllLines;
-  map<int, int> * DegeneratedLines = new map<int, int>;
+IndexToIndex * Tesselation::FindAllDegeneratedLines()
+{
+  Info FunctionInfo(__func__);
+  UniqueLines AllLines;
+  IndexToIndex * DegeneratedLines = new IndexToIndex;
 
   // sanity check
   if (LinesOnBoundary.empty()) {
-    Log() << Verbose(1) << "Warning: 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<LineMap::iterator, bool> tester;
+  pair<UniqueLines::iterator, bool> tester;
   for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
-    tester = AllLines.insert( pair<int,BoundaryLineSet *> (LineRunner1->second->endpoints[0]->Nr, LineRunner1->second) );
-    if ((!tester.second) && (tester.first->second->endpoints[1]->Nr == LineRunner1->second->endpoints[1]->Nr)) { // found degenerated line
-      DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, tester.first->second->Nr) );
-      DegeneratedLines->insert ( pair<int, int> (tester.first->second->Nr, LineRunner1->second->Nr) );
+    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));
     }
   }
@@ -3300,8 +4583,14 @@
   AllLines.clear();
 
-  Log() << Verbose(1) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
-  map<int,int>::iterator it;
-  for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++)
-      Log() << Verbose(2) << (*it).first << " => " << (*it).second << endl;
+  DoLog(0) && (Log() << Verbose(0) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl);
+  IndexToIndex::iterator it;
+  for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++) {
+    const LineMap::const_iterator Line1 = LinesOnBoundary.find((*it).first);
+    const LineMap::const_iterator Line2 = LinesOnBoundary.find((*it).second);
+    if (Line1 != LinesOnBoundary.end() && Line2 != LinesOnBoundary.end())
+      DoLog(0) && (Log() << Verbose(0) << *Line1->second << " => " << *Line2->second << endl);
+    else
+      DoeLog(1) && (eLog() << Verbose(1) << "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!" << endl);
+  }
 
   return DegeneratedLines;
@@ -3314,14 +4603,14 @@
  *         in the list, once as key and once as value
  */
-map<int, int> * Tesselation::FindAllDegeneratedTriangles()
-{
-  map<int, int> * DegeneratedLines = FindAllDegeneratedLines();
-  map<int, int> * DegeneratedTriangles = new map<int, int>;
-
+IndexToIndex * Tesselation::FindAllDegeneratedTriangles()
+{
+  Info FunctionInfo(__func__);
+  IndexToIndex * DegeneratedLines = FindAllDegeneratedLines();
+  IndexToIndex * DegeneratedTriangles = new IndexToIndex;
   TriangleMap::iterator TriangleRunner1, TriangleRunner2;
   LineMap::iterator Liner;
   class BoundaryLineSet *line1 = NULL, *line2 = NULL;
 
-  for (map<int, int>::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
+  for (IndexToIndex::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
     // run over both lines' triangles
     Liner = LinesOnBoundary.find(LineRunner->first);
@@ -3333,18 +4622,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(1) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
-  map<int,int>::iterator it;
+  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(2) << (*it).first << " => " << (*it).second << endl;
+    DoLog(0) && (Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl);
 
   return DegeneratedTriangles;
@@ -3357,14 +4645,11 @@
 void Tesselation::RemoveDegeneratedTriangles()
 {
-  map<int, int> * DegeneratedTriangles = FindAllDegeneratedTriangles();
+  Info FunctionInfo(__func__);
+  IndexToIndex * DegeneratedTriangles = FindAllDegeneratedTriangles();
   TriangleMap::iterator finder;
   BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
-  int count  = 0;
-
-  Log() << Verbose(1) << "Begin of RemoveDegeneratedTriangles" << endl;
-
-  for (map<int, int>::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())
@@ -3383,9 +4668,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;
@@ -3407,6 +4688,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];
@@ -3414,6 +4695,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];
           }
@@ -3421,19 +4702,18 @@
       // erase the pair
       count += (int) DegeneratedTriangles->erase(triangle->Nr);
-      Log() << Verbose(1) << "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(1) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
+      DoLog(0) && (Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl);
       RemoveTesselationTriangle(partnerTriangle);
     } else {
-      Log() << Verbose(1) << "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);
-
-  Log() << Verbose(1) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
-  Log() << Verbose(1) << "End of RemoveDegeneratedTriangles" << endl;
+      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;
+
+  DoLog(0) && (Log() << Verbose(0) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl);
 }
 
@@ -3448,9 +4728,8 @@
 void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell *LC)
 {
-  Log() << Verbose(2) << "Begin of AddBoundaryPointByDegeneratedTriangle" << endl;
-
+  Info FunctionInfo(__func__);
   // find nearest boundary point
   class TesselPoint *BackupPoint = NULL;
-  class TesselPoint *NearestPoint = FindClosestPoint(point->node, BackupPoint, LC);
+  class TesselPoint *NearestPoint = FindClosestTesselPoint(point->node, BackupPoint, LC);
   class BoundaryPointSet *NearestBoundaryPoint = NULL;
   PointMap::iterator PointRunner;
@@ -3462,8 +4741,8 @@
     NearestBoundaryPoint = PointRunner->second;
   } else {
-    Log() << Verbose(1) << "ERROR: I cannot find the boundary point." << endl;
+    DoeLog(1) && (eLog() << Verbose(1) << "I cannot find the boundary point." << endl);
     return;
   }
-  Log() << Verbose(2) << "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
@@ -3480,5 +4759,5 @@
     CenterToPoint.SubtractVector(point->node);
     angle = CenterToPoint.Angle(&BaseLine);
-    if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
+    if (fabs(angle - M_PI / 2.) < fabs(BestAngle - M_PI / 2.)) {
       BestAngle = angle;
       BestLine = Runner->second;
@@ -3490,5 +4769,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;
@@ -3498,48 +4777,46 @@
 
   // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
-  Log() << Verbose(5) << "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(5) << "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(3) << "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(5) << "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(5) << "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(3) << "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]){
-        Log() << Verbose(1) << "CRITICAL: BestLine is same as found line, something's wrong here!" << endl;
-        exit(255);
+      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;
     }
   }
-
-  // exit
-  Log() << Verbose(2) << "End of AddBoundaryPointByDegeneratedTriangle" << endl;
-};
+}
+;
 
 /** Writes the envelope to file.
@@ -3550,4 +4827,5 @@
 void Tesselation::Output(const char *filename, const PointCloud * const cloud)
 {
+  Info FunctionInfo(__func__);
   ofstream *tempstream = NULL;
   string NameofTempFile;
@@ -3555,17 +4833,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(1) << "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);
     }
 
@@ -3573,8 +4851,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(1) << "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);
@@ -3582,8 +4860,210 @@
       tempstream->close();
       tempstream->flush();
-      delete(tempstream);
+      delete (tempstream);
     }
   }
   if (DoTecplotOutput || DoRaster3DOutput)
     TriangleFilesWritten++;
+}
+;
+
+struct BoundaryPolygonSetCompare
+{
+  bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const
+  {
+    if (s1->endpoints.size() < s2->endpoints.size())
+      return true;
+    else if (s1->endpoints.size() > s2->endpoints.size())
+      return false;
+    else { // equality of number of endpoints
+      PointSet::const_iterator Walker1 = s1->endpoints.begin();
+      PointSet::const_iterator Walker2 = s2->endpoints.begin();
+      while ((Walker1 != s1->endpoints.end()) || (Walker2 != s2->endpoints.end())) {
+        if ((*Walker1)->Nr < (*Walker2)->Nr)
+          return true;
+        else if ((*Walker1)->Nr > (*Walker2)->Nr)
+          return false;
+        Walker1++;
+        Walker2++;
+      }
+      return false;
+    }
+  }
 };
+
+#define UniquePolygonSet set < BoundaryPolygonSet *, BoundaryPolygonSetCompare>
+
+/** Finds all degenerated polygons and calls ReTesselateDegeneratedPolygon()/
+ * \return number of polygons found
+ */
+int Tesselation::CorrectAllDegeneratedPolygons()
+{
+  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;
+  for (PointMap::const_iterator Runner = PointsOnBoundary.begin(); Runner != PointsOnBoundary.end(); Runner++) {
+    DoLog(0) && (Log() << Verbose(0) << "Current point is " << *Runner->second << "." << endl);
+    map<int, Vector *> TriangleVectors;
+    // gather all NormalVectors
+    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)));
+          if (TriangleInsertionTester.second)
+            DoLog(1) && (Log() << Verbose(1) << " Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list." << endl);
+        } else {
+          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
+    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
+          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)
+              DoLog(0) && (Log() << Verbose(0) << " Adding " << *Runner->second << " to endpoint candidate list." << endl);
+            // and break out of both loops
+            VectorWalker = TriangleVectors.end();
+            VectorRunner = TriangleVectors.end();
+            break;
+          }
+        }
+  }
+  delete (DegeneratedTriangles);
+  /// 3. Find connected endpoint candidates and put them into a polygon
+  UniquePolygonSet ListofDegeneratedPolygons;
+  BoundaryPointSet *Walker = NULL;
+  BoundaryPointSet *OtherWalker = NULL;
+  BoundaryPolygonSet *Current = NULL;
+  stack<BoundaryPointSet*> ToCheckConnecteds;
+  while (!EndpointCandidateList.empty()) {
+    Walker = *(EndpointCandidateList.begin());
+    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);
+      EndpointCandidateList.erase(Walker);
+      ToCheckConnecteds.push(Walker);
+    }
+
+    // go through to-check stack
+    while (!ToCheckConnecteds.empty()) {
+      Walker = ToCheckConnecteds.top(); // fetch ...
+      ToCheckConnecteds.pop(); // ... and remove
+      for (LineMap::const_iterator LineWalker = Walker->lines.begin(); LineWalker != Walker->lines.end(); LineWalker++) {
+        OtherWalker = (LineWalker->second)->GetOtherEndpoint(Walker);
+        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
+        } else {
+          DoLog(1) && (Log() << Verbose(1) << " is not connected to " << *Walker << endl);
+        }
+      }
+    }
+
+    DoLog(0) && (Log() << Verbose(0) << "Final polygon is " << *Current << endl);
+    ListofDegeneratedPolygons.insert(Current);
+    Current = NULL;
+  }
+
+  const int counter = ListofDegeneratedPolygons.size();
+
+  DoLog(0) && (Log() << Verbose(0) << "The following " << counter << " degenerated polygons have been found: " << endl);
+  for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++)
+    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;
+    Vector NormalVector;
+    /// 4a. Gather all triangles of this polygon
+    TriangleSet *T = (*PolygonRunner)->GetAllContainedTrianglesFromEndpoints();
+
+    // check whether number is bigger than 2, otherwise it's just a simply degenerated one and nothing to do.
+    if (T->size() == 2) {
+      DoLog(1) && (Log() << Verbose(1) << " Skipping degenerated polygon, is just a (already simply degenerated) triangle." << endl);
+      delete (T);
+      continue;
+    }
+
+    // check whether number is even
+    // If this case occurs, we have to think about it!
+    // The Problem is probably due to two degenerated polygons being connected by a bridging, non-degenerated polygon, as somehow one node has
+    // connections to either polygon ...
+    if (T->size() % 2 != 0) {
+      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
+    /// 4a. Get NormalVector for one side (this is "front")
+    NormalVector.CopyVector(&(*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
+    /// 4b. Remove all triangles whose NormalVector is in opposite direction (i.e. "back")
+    BoundaryTriangleSet *triangle = NULL;
+    while (TriangleSprinter != T->end()) {
+      TriangleWalker = TriangleSprinter;
+      triangle = *TriangleWalker;
+      TriangleSprinter++;
+      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
+        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
+      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(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())
+        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.);
+      TriangleWalker++;
+    }
+    if (!TriangleNrs.empty()) {
+      DoeLog(0) && (eLog() << Verbose(0) << "There have been less triangles created than removed!" << endl);
+    }
+    delete (T); // remove the triangleset
+  }
+  IndexToIndex * SimplyDegeneratedTriangles = FindAllDegeneratedTriangles();
+  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++)
+    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);
+    ListofDegeneratedPolygons.erase(PolygonRunner);
+  }
+
+  return counter;
+}
+;
Index: src/tesselation.hpp
===================================================================
--- src/tesselation.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/tesselation.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -23,4 +23,5 @@
 #include <list>
 #include <set>
+#include <stack>
 
 #include "atom_particleinfo.hpp"
@@ -42,26 +43,52 @@
 #define DoTecplotOutput 1
 #define DoRaster3DOutput 1
-#define DoVRMLOutput 1
+#define DoVRMLOutput 0
 #define TecplotSuffix ".dat"
 #define Raster3DSuffix ".r3d"
 #define VRMLSUffix ".wrl"
 
+#define ParallelEpsilon 1e-3
+
 // ======================================================= some template functions =========================================
 
+#define IndexToIndex map <int, int>
+
 #define PointMap map < int, class BoundaryPointSet * >
+#define PointSet set < class BoundaryPointSet * >
+#define PointList list < class BoundaryPointSet * >
 #define PointPair pair < int, class BoundaryPointSet * >
 #define PointTestPair pair < PointMap::iterator, bool >
+
 #define CandidateList list <class CandidateForTesselation *>
+#define CandidateMap map <class BoundaryLineSet *, class CandidateForTesselation *>
 
 #define LineMap multimap < int, class BoundaryLineSet * >
+#define LineSet set < class BoundaryLineSet * >
+#define LineList list < class BoundaryLineSet * >
 #define LinePair pair < int, class BoundaryLineSet * >
 #define LineTestPair pair < LineMap::iterator, bool >
 
 #define TriangleMap map < int, class BoundaryTriangleSet * >
+#define TriangleSet set < class BoundaryTriangleSet * >
+#define TriangleList list < class BoundaryTriangleSet * >
 #define TrianglePair pair < int, class BoundaryTriangleSet * >
 #define TriangleTestPair pair < TrianglePair::iterator, bool >
 
+#define PolygonMap map < int, class BoundaryPolygonSet * >
+#define PolygonSet set < class BoundaryPolygonSet * >
+#define PolygonList list < class BoundaryPolygonSet * >
+
+#define DistanceToPointMap multimap <double, class BoundaryPointSet * >
+#define DistanceToPointPair pair <double, class BoundaryPointSet * >
+
 #define DistanceMultiMap multimap <double, pair < PointMap::iterator, PointMap::iterator> >
 #define DistanceMultiMapPair pair <double, pair < PointMap::iterator, PointMap::iterator> >
+
+#define TesselPointList list <TesselPoint *>
+#define TesselPointSet set <TesselPoint *>
+
+#define ListOfTesselPointList list<list <TesselPoint *> *>
+
+enum centers {Opt, OtherOpt};
 
 /********************************************** declarations *******************************/
@@ -83,8 +110,8 @@
   public:
     BoundaryPointSet();
-    BoundaryPointSet(TesselPoint * Walker);
+    BoundaryPointSet(TesselPoint * const Walker);
     ~BoundaryPointSet();
 
-    void AddLine(class BoundaryLineSet *line);
+    void AddLine(BoundaryLineSet * const line);
 
     LineMap lines;
@@ -102,16 +129,18 @@
   public:
     BoundaryLineSet();
-    BoundaryLineSet(class BoundaryPointSet *Point[2], const int number);
+    BoundaryLineSet(BoundaryPointSet * const Point[2], const int number);
+    BoundaryLineSet(BoundaryPointSet * const Point1, BoundaryPointSet * const Point2, const int number);
     ~BoundaryLineSet();
 
-    void AddTriangle(class BoundaryTriangleSet *triangle);
-    bool IsConnectedTo(class BoundaryLineSet *line);
-    bool ContainsBoundaryPoint(class BoundaryPointSet *point);
-    bool CheckConvexityCriterion();
-    class BoundaryPointSet *GetOtherEndpoint(class BoundaryPointSet *);
+    void AddTriangle(BoundaryTriangleSet * const triangle);
+    bool IsConnectedTo(const BoundaryLineSet * const line) const;
+    bool ContainsBoundaryPoint(const BoundaryPointSet * const point) const;
+    bool CheckConvexityCriterion() const;
+    class BoundaryPointSet *GetOtherEndpoint(const BoundaryPointSet * const point) const;
 
     class BoundaryPointSet *endpoints[2];
     TriangleMap triangles;
     int Nr;
+    bool skipped;
 };
 
@@ -123,24 +152,58 @@
   public:
     BoundaryTriangleSet();
-    BoundaryTriangleSet(class BoundaryLineSet *line[3], int number);
+    BoundaryTriangleSet(class BoundaryLineSet * const line[3], const int number);
     ~BoundaryTriangleSet();
 
-    void GetNormalVector(Vector &NormalVector);
-    void GetCenter(Vector *center);
-    bool GetIntersectionInsideTriangle(Vector *MolCenter, Vector *x, Vector *Intersection);
-    bool ContainsBoundaryLine(class BoundaryLineSet *line);
-    bool ContainsBoundaryPoint(class BoundaryPointSet *point);
-    bool ContainsBoundaryPoint(class TesselPoint *point);
-    class BoundaryPointSet *GetThirdEndpoint(class BoundaryLineSet *line);
-    bool IsPresentTupel(class BoundaryPointSet *Points[3]);
-    bool IsPresentTupel(class BoundaryTriangleSet *T);
+    void GetNormalVector(const Vector &NormalVector);
+    void GetCenter(Vector * const center) const;
+    bool GetIntersectionInsideTriangle(const Vector * const MolCenter, const Vector * const x, Vector * const Intersection) const;
+    double GetClosestPointInsideTriangle(const Vector * const x, Vector * const ClosestPoint) const;
+    bool ContainsBoundaryLine(const BoundaryLineSet * const line) const;
+    bool ContainsBoundaryPoint(const BoundaryPointSet * const point) const;
+    bool ContainsBoundaryPoint(const TesselPoint * const point) const;
+    class BoundaryPointSet *GetThirdEndpoint(const BoundaryLineSet * const line) const;
+    bool IsPresentTupel(const BoundaryPointSet * const Points[3]) const;
+    bool IsPresentTupel(const BoundaryTriangleSet * const T) const;
 
     class BoundaryPointSet *endpoints[3];
     class BoundaryLineSet *lines[3];
     Vector NormalVector;
+    Vector SphereCenter;
     int Nr;
 };
 
 ostream & operator << (ostream &ost, const BoundaryTriangleSet &a);
+
+
+// ======================================================== class BoundaryTriangleSet =======================================
+
+/** Set of BoundaryPointSet.
+ * This is just meant as a container for a group of endpoints, extending the node, line, triangle concept. However, this has
+ * only marginally something to do with the tesselation. Hence, there is no incorporation into the bookkeeping of the Tesselation
+ * class (i.e. no allocation, no deletion).
+ * \note we assume that the set of endpoints reside (more or less) on a plane.
+ */
+class BoundaryPolygonSet {
+  public:
+    BoundaryPolygonSet();
+    ~BoundaryPolygonSet();
+
+    Vector * GetNormalVector(const Vector &NormalVector) const;
+    void GetCenter(Vector *center) const;
+    bool ContainsBoundaryLine(const BoundaryLineSet * const line) const;
+    bool ContainsBoundaryPoint(const BoundaryPointSet * const point) const;
+    bool ContainsBoundaryPoint(const TesselPoint * const point) const;
+    bool ContainsBoundaryTriangle(const BoundaryTriangleSet * const point) const;
+    bool ContainsPresentTupel(const BoundaryPointSet * const * Points, const int dim) const;
+    bool ContainsPresentTupel(const BoundaryPolygonSet * const P) const;
+    bool ContainsPresentTupel(const PointSet &endpoints) const;
+    TriangleSet * GetAllContainedTrianglesFromEndpoints() const;
+    bool FillPolygonFromTrianglesOfLine(const BoundaryLineSet * const line);
+
+    PointSet endpoints;
+    int Nr;
+};
+
+ostream & operator << (ostream &ost, const BoundaryPolygonSet &a);
 
 // =========================================================== class TESSELPOINT ===========================================
@@ -170,13 +233,15 @@
   virtual ~PointCloud();
 
+  virtual const char * const GetName() const { return "unknown"; };
   virtual Vector *GetCenter() const { return NULL; };
   virtual TesselPoint *GetPoint() const { return NULL; };
   virtual TesselPoint *GetTerminalPoint() const { return NULL; };
+  virtual int GetMaxId() const { return 0; };
   virtual void GoToNext() const {};
   virtual void GoToPrevious() const {};
   virtual void GoToFirst() const {};
   virtual void GoToLast() const {};
-  virtual bool IsEmpty() const { return false; };
-  virtual bool IsEnd() const { return false; };
+  virtual bool IsEmpty() const { return true; };
+  virtual bool IsEnd() const { return true; };
 };
 
@@ -185,12 +250,22 @@
 class CandidateForTesselation {
   public :
-  CandidateForTesselation(TesselPoint* candidate, BoundaryLineSet* currentBaseLine, Vector OptCandidateCenter, Vector OtherOptCandidateCenter);
+  CandidateForTesselation(BoundaryLineSet* currentBaseLine);
+  CandidateForTesselation(TesselPoint* candidate, BoundaryLineSet* currentBaseLine, BoundaryPointSet *point, Vector OptCandidateCenter, Vector OtherOptCandidateCenter);
   ~CandidateForTesselation();
 
-  TesselPoint *point;
-  BoundaryLineSet *BaseLine;
+  bool CheckValidity(const double RADIUS, const LinkedCell *LC) const;
+
+  TesselPointList pointlist;
+  const BoundaryLineSet * BaseLine;
+  const BoundaryPointSet * ThirdPoint;
+  const BoundaryTriangleSet *T;
+  Vector OldCenter;
   Vector OptCenter;
   Vector OtherOptCenter;
-};
+  double ShortestAngle;
+  double OtherShortestAngle;
+};
+
+ostream & operator <<(ostream &ost, const  CandidateForTesselation &a);
 
 // =========================================================== class TESSELATION ===========================================
@@ -205,19 +280,26 @@
 
     void AddTesselationPoint(TesselPoint* Candidate, const int n);
-    void AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n);
-    void AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n);
+    void SetTesselationPoint(TesselPoint* Candidate, const int n) const;
+    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, 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, class BoundaryLineSet *BaseLine, class TesselPoint *ThirdNode, CandidateList* &candidates, double *ShortestAngle, const double RADIUS, const LinkedCell *LC);
-    bool FindNextSuitableTriangle(BoundaryLineSet &Line, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC);
-    int CheckPresenceOfTriangle(class TesselPoint *Candidates[3]);
+    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]);
 
@@ -230,21 +312,27 @@
     double PickFarthestofTwoBaselines(class BoundaryLineSet *Base);
     class BoundaryPointSet *IsConvexRectangle(class BoundaryLineSet *Base);
-    map<int, int> * FindAllDegeneratedTriangles();
-    map<int, int> * FindAllDegeneratedLines();
+    IndexToIndex * FindAllDegeneratedTriangles();
+    IndexToIndex * FindAllDegeneratedLines();
     void RemoveDegeneratedTriangles();
     void AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell *LC);
-
-    set<TesselPoint*> * GetAllConnectedPoints(const TesselPoint* const Point) const;
-    set<BoundaryTriangleSet*> *GetAllTriangles(const BoundaryPointSet * const Point) const;
-    list<list<TesselPoint*> *> * GetPathsOfConnectedPoints(const TesselPoint* const Point) const;
-    list<list<TesselPoint*> *> * GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const;
-    list<TesselPoint*> * GetCircleOfConnectedPoints(const TesselPoint* const Point, const Vector * const Reference = NULL) const;
-    class BoundaryPointSet *GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const;
-    list<BoundaryTriangleSet*> *FindTriangles(const TesselPoint* const Points[3]) const;
-    list<BoundaryTriangleSet*> * FindClosestTrianglesToPoint(const Vector *x, const LinkedCell* LC) const;
-    class BoundaryTriangleSet * FindClosestTriangleToPoint(const Vector *x, const LinkedCell* LC) const;
+    int CorrectAllDegeneratedPolygons();
+
+    TesselPointSet * GetAllConnectedPoints(const TesselPoint* const Point) const;
+    TriangleSet * GetAllTriangles(const BoundaryPointSet * const Point) const;
+    ListOfTesselPointList * GetPathsOfConnectedPoints(const TesselPoint* const Point) const;
+    ListOfTesselPointList * GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const;
+    TesselPointList * GetCircleOfSetOfPoints(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference = NULL) const;
+    TesselPointList * GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const;
+    class BoundaryPointSet * GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const;
+    TriangleList * FindTriangles(const TesselPoint* const Points[3]) const;
+    TriangleList * FindClosestTrianglesToVector(const Vector *x, const LinkedCell* LC) const;
+    BoundaryTriangleSet * FindClosestTriangleToVector(const Vector *x, const LinkedCell* LC) const;
     bool IsInnerPoint(const Vector &Point, const LinkedCell* const LC) const;
-    bool IsInnerPoint(const TesselPoint * const Point, const LinkedCell* const LC) const;
+    double GetDistanceSquaredToTriangle(const Vector &Point, const BoundaryTriangleSet* const triangle) 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;
+    BoundaryLineSet * FindClosestBoundaryLineToVector(const Vector *x, const LinkedCell* LC) const;
 
     // print for debugging
@@ -258,4 +346,5 @@
     PointMap PointsOnBoundary;
     LineMap LinesOnBoundary;
+    CandidateMap OpenLines;
     TriangleMap TrianglesOnBoundary;
     int PointsOnBoundaryCount;
@@ -281,7 +370,10 @@
 
   private:
-    class BoundaryPointSet *TPS[3]; //this is a Storage for pointers to triangle points, this and BPS[2] needed due to AddLine restrictions
+    mutable class BoundaryPointSet *TPS[3]; //this is a Storage for pointers to triangle points, this and BPS[2] needed due to AddLine restrictions
 
     mutable PointMap::const_iterator InternalPointer;
+
+    //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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/tesselationhelpers.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -8,4 +8,5 @@
 #include <fstream>
 
+#include "info.hpp"
 #include "linkedcell.hpp"
 #include "log.hpp"
@@ -15,5 +16,7 @@
 #include "verbose.hpp"
 
-double DetGet(gsl_matrix * const A, const int inPlace) {
+double DetGet(gsl_matrix * const A, const int inPlace)
+{
+	Info FunctionInfo(__func__);
   /*
   inPlace = 1 => A is replaced with the LU decomposed copy.
@@ -45,4 +48,5 @@
 void GetSphere(Vector * const center, const Vector &a, const Vector &b, const Vector &c, const double RADIUS)
 {
+	Info FunctionInfo(__func__);
   gsl_matrix *A = gsl_matrix_calloc(3,3);
   double m11, m12, m13, m14;
@@ -77,5 +81,5 @@
 
   if (fabs(m11) < MYEPSILON)
-    eLog() << Verbose(0) << "ERROR: three points are colinear." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "three points are colinear." << endl);
 
   center->x[0] =  0.5 * m12/ m11;
@@ -84,5 +88,5 @@
 
   if (fabs(a.Distance(center) - RADIUS) > MYEPSILON)
-    eLog() << Verbose(0) << "ERROR: The given center is further way by " << fabs(a.Distance(center) - RADIUS) << " from a than RADIUS." << endl;
+    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);
@@ -111,8 +115,8 @@
     const double HalfplaneIndicator, const double AlternativeIndicator, const double alpha, const double beta, const double gamma, const double RADIUS, const double Umkreisradius)
 {
+	Info FunctionInfo(__func__);
   Vector TempNormal, helper;
   double Restradius;
   Vector OtherCenter;
-  Log() << Verbose(3) << "Begin of GetCenterOfSphere.\n";
   Center->Zero();
   helper.CopyVector(&a);
@@ -128,7 +132,7 @@
   Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
   NewUmkreismittelpunkt->CopyVector(Center);
-  Log() << Verbose(4) << "Center of new circumference is " << *NewUmkreismittelpunkt << ".\n";
+  DoLog(1) && (Log() << Verbose(1) << "Center of new circumference is " << *NewUmkreismittelpunkt << ".\n");
   // Here we calculated center of circumscribing circle, using barycentric coordinates
-  Log() << Verbose(4) << "Center of circumference is " << *Center << " in direction " << *Direction << ".\n";
+  DoLog(1) && (Log() << Verbose(1) << "Center of circumference is " << *Center << " in direction " << *Direction << ".\n");
 
   TempNormal.CopyVector(&a);
@@ -139,5 +143,5 @@
   if (fabs(HalfplaneIndicator) < MYEPSILON)
     {
-      if ((TempNormal.ScalarProduct(AlternativeDirection) <0 and AlternativeIndicator >0) or (TempNormal.ScalarProduct(AlternativeDirection) >0 and AlternativeIndicator <0))
+      if ((TempNormal.ScalarProduct(AlternativeDirection) <0 && AlternativeIndicator >0) || (TempNormal.ScalarProduct(AlternativeDirection) >0 && AlternativeIndicator <0))
         {
           TempNormal.Scale(-1);
@@ -146,5 +150,5 @@
   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);
@@ -154,13 +158,12 @@
   TempNormal.Normalize();
   Restradius = sqrt(RADIUS*RADIUS - Umkreisradius*Umkreisradius);
-  Log() << Verbose(4) << "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(4) << "Shift vector to sphere of circumference is " << TempNormal << ".\n";
+  DoLog(1) && (Log() << Verbose(1) << "Shift vector to sphere of circumference is " << TempNormal << ".\n");
 
   Center->AddVector(&TempNormal);
-  Log() << Verbose(0) << "Center of sphere of circumference is " << *Center << ".\n";
+  DoLog(1) && (Log() << Verbose(1) << "Center of sphere of circumference is " << *Center << ".\n");
   GetSphere(&OtherCenter, a, b, c, RADIUS);
-  Log() << Verbose(0) << "OtherCenter of sphere of circumference is " << OtherCenter << ".\n";
-  Log() << Verbose(3) << "End of GetCenterOfSphere.\n";
+  DoLog(1) && (Log() << Verbose(1) << "OtherCenter of sphere of circumference is " << OtherCenter << ".\n");
 };
 
@@ -174,4 +177,5 @@
 void GetCenterofCircumcircle(Vector * const Center, const Vector &a, const Vector &b, const Vector &c)
 {
+	Info FunctionInfo(__func__);
   Vector helper;
   double alpha, beta, gamma;
@@ -186,7 +190,8 @@
   beta = M_PI - SideC.Angle(&SideA);
   gamma = M_PI - SideA.Angle(&SideB);
-  //Log() << Verbose(3) << "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(0) << "GetCenterofCircumcircle: Sum of angles " << (alpha+beta+gamma)/M_PI*180. << " > 180 degrees by " << fabs(M_PI - alpha - beta - gamma)/M_PI*180. << "!" << endl;
+  //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) {
+    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();
@@ -218,30 +223,37 @@
 double GetPathLengthonCircumCircle(const Vector &CircleCenter, const Vector &CirclePlaneNormal, const double CircleRadius, const Vector &NewSphereCenter, const Vector &OldSphereCenter, const Vector &NormalVector, const Vector &SearchDirection)
 {
+	Info FunctionInfo(__func__);
   Vector helper;
   double radius, alpha;
-
-  helper.CopyVector(&NewSphereCenter);
+  Vector RelativeOldSphereCenter;
+  Vector RelativeNewSphereCenter;
+
+  RelativeOldSphereCenter.CopyVector(&OldSphereCenter);
+  RelativeOldSphereCenter.SubtractVector(&CircleCenter);
+  RelativeNewSphereCenter.CopyVector(&NewSphereCenter);
+  RelativeNewSphereCenter.SubtractVector(&CircleCenter);
+  helper.CopyVector(&RelativeNewSphereCenter);
   // test whether new center is on the parameter circle's plane
   if (fabs(helper.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
-    eLog() << Verbose(0) << "ERROR: Something's very wrong here: NewSphereCenter is not on the band's plane as desired by " <<fabs(helper.ScalarProduct(&CirclePlaneNormal))  << "!" << endl;
+    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.ScalarProduct(&helper);
+  radius = helper.NormSquared();
   // test whether the new center vector has length of CircleRadius
   if (fabs(radius - CircleRadius) > HULLEPSILON)
-    eLog() << Verbose(1) << "ERROR: The projected center of the new sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
-  alpha = helper.Angle(&OldSphereCenter);
+    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
     alpha = 2.*M_PI - alpha;
-  //Log() << Verbose(2) << "INFO: RelativeNewSphereCenter is " << helper << ", RelativeOldSphereCenter is " << OldSphereCenter << " and resulting angle is " << alpha << "." << endl;
-  radius = helper.Distance(&OldSphereCenter);
+  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(2) << "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 " << helper << " is too close to OldSphereCenter" << OldSphereCenter << "." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "INFO: NewSphereCenter " << RelativeNewSphereCenter << " is too close to RelativeOldSphereCenter" << RelativeOldSphereCenter << "." << endl);
     return 2.*M_PI;
   }
@@ -263,4 +275,5 @@
 double MinIntersectDistance(const gsl_vector * x, void *params)
 {
+	Info FunctionInfo(__func__);
   double retval = 0;
   struct Intersection *I = (struct Intersection *)params;
@@ -283,5 +296,5 @@
 
   retval = HeightA.ScalarProduct(&HeightA) + HeightB.ScalarProduct(&HeightB);
-  //Log() << Verbose(2) << "MinIntersectDistance called, result: " << retval << endl;
+  //Log() << Verbose(1) << "MinIntersectDistance called, result: " << retval << endl;
 
   return retval;
@@ -303,4 +316,5 @@
 bool existsIntersection(const Vector &point1, const Vector &point2, const Vector &point3, const Vector &point4)
 {
+	Info FunctionInfo(__func__);
   bool result;
 
@@ -350,5 +364,5 @@
 
         if (status == GSL_SUCCESS) {
-          Log() << Verbose(2) << "converged to minimum" <<  endl;
+          DoLog(1) && (Log() << Verbose(1) << "converged to minimum" <<  endl);
         }
     } while (status == GSL_CONTINUE && iter < 100);
@@ -375,13 +389,13 @@
   t2 = HeightB.ScalarProduct(&SideB)/SideB.ScalarProduct(&SideB);
 
-  Log() << Verbose(2) << "Intersection " << intersection << " is at "
+  Log() << Verbose(1) << "Intersection " << intersection << " is at "
     << t1 << " for (" << point1 << "," << point2 << ") and at "
     << t2 << " for (" << point3 << "," << point4 << "): ";
 
   if (((t1 >= 0) && (t1 <= 1)) && ((t2 >= 0) && (t2 <= 1))) {
-    Log() << Verbose(0) << "true intersection." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "true intersection." << endl);
     result = true;
   } else {
-    Log() << Verbose(0) << "intersection out of region of interest." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "intersection out of region of interest." << endl);
     result = false;
   }
@@ -406,4 +420,5 @@
 double GetAngle(const Vector &point, const Vector &reference, const Vector &OrthogonalVector)
 {
+	Info FunctionInfo(__func__);
   if (reference.IsZero())
     return M_PI;
@@ -417,5 +432,5 @@
   }
 
-  Log() << Verbose(4) << "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;
@@ -432,4 +447,5 @@
 double CalculateVolumeofGeneralTetraeder(const Vector &a, const Vector &b, const Vector &c, const Vector &d)
 {
+	Info FunctionInfo(__func__);
   Vector Point, TetraederVector[3];
   double volume;
@@ -455,4 +471,5 @@
 bool CheckLineCriteriaForDegeneratedTriangle(const BoundaryPointSet * const nodes[3])
 {
+	Info FunctionInfo(__func__);
   bool result = false;
   int counter = 0;
@@ -461,5 +478,8 @@
   for (int i=0;i<3;i++)
     for (int j=i+1; j<3; j++) {
-      if (nodes[i]->lines.find(nodes[j]->node->nr) != nodes[i]->lines.end()) {  // there already is a line
+      if (nodes[i] == NULL) {
+        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
         LineMap::const_iterator FindLine;
         pair<LineMap::const_iterator,LineMap::const_iterator> FindPair;
@@ -473,10 +493,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(2) << "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;
   }
@@ -485,47 +505,48 @@
 
 
-/** Sort function for the candidate list.
- */
-bool SortCandidates(const CandidateForTesselation* candidate1, const CandidateForTesselation* candidate2)
-{
-  Vector BaseLineVector, OrthogonalVector, helper;
-  if (candidate1->BaseLine != candidate2->BaseLine) {  // sanity check
-    Log() << Verbose(0) << "ERROR: sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl;
-    //return false;
-    exit(1);
-  }
-  // create baseline vector
-  BaseLineVector.CopyVector(candidate1->BaseLine->endpoints[1]->node->node);
-  BaseLineVector.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
-  BaseLineVector.Normalize();
-
-  // create normal in-plane vector to cope with acos() non-uniqueness on [0,2pi] (note that is pointing in the "right" direction already, hence ">0" test!)
-  helper.CopyVector(candidate1->BaseLine->endpoints[0]->node->node);
-  helper.SubtractVector(candidate1->point->node);
-  OrthogonalVector.CopyVector(&helper);
-  helper.VectorProduct(&BaseLineVector);
-  OrthogonalVector.SubtractVector(&helper);
-  OrthogonalVector.Normalize();
-
-  // calculate both angles and correct with in-plane vector
-  helper.CopyVector(candidate1->point->node);
-  helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
-  double phi = BaseLineVector.Angle(&helper);
-  if (OrthogonalVector.ScalarProduct(&helper) > 0) {
-    phi = 2.*M_PI - phi;
-  }
-  helper.CopyVector(candidate2->point->node);
-  helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
-  double psi = BaseLineVector.Angle(&helper);
-  if (OrthogonalVector.ScalarProduct(&helper) > 0) {
-    psi = 2.*M_PI - psi;
-  }
-
-  Log() << Verbose(2) << *candidate1->point << " has angle " << phi << endl;
-  Log() << Verbose(2) << *candidate2->point << " has angle " << psi << endl;
-
-  // return comparison
-  return phi < psi;
-};
+///** Sort function for the candidate list.
+// */
+//bool SortCandidates(const CandidateForTesselation* candidate1, const CandidateForTesselation* candidate2)
+//{
+//	Info FunctionInfo(__func__);
+//  Vector BaseLineVector, OrthogonalVector, helper;
+//  if (candidate1->BaseLine != candidate2->BaseLine) {  // sanity check
+//    DoeLog(1) && (eLog()<< Verbose(1) << "sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl);
+//    //return false;
+//    exit(1);
+//  }
+//  // create baseline vector
+//  BaseLineVector.CopyVector(candidate1->BaseLine->endpoints[1]->node->node);
+//  BaseLineVector.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
+//  BaseLineVector.Normalize();
+//
+//  // create normal in-plane vector to cope with acos() non-uniqueness on [0,2pi] (note that is pointing in the "right" direction already, hence ">0" test!)
+//  helper.CopyVector(candidate1->BaseLine->endpoints[0]->node->node);
+//  helper.SubtractVector(candidate1->point->node);
+//  OrthogonalVector.CopyVector(&helper);
+//  helper.VectorProduct(&BaseLineVector);
+//  OrthogonalVector.SubtractVector(&helper);
+//  OrthogonalVector.Normalize();
+//
+//  // calculate both angles and correct with in-plane vector
+//  helper.CopyVector(candidate1->point->node);
+//  helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
+//  double phi = BaseLineVector.Angle(&helper);
+//  if (OrthogonalVector.ScalarProduct(&helper) > 0) {
+//    phi = 2.*M_PI - phi;
+//  }
+//  helper.CopyVector(candidate2->point->node);
+//  helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
+//  double psi = BaseLineVector.Angle(&helper);
+//  if (OrthogonalVector.ScalarProduct(&helper) > 0) {
+//    psi = 2.*M_PI - psi;
+//  }
+//
+//  Log() << Verbose(1) << *candidate1->point << " has angle " << phi << endl;
+//  Log() << Verbose(1) << *candidate2->point << " has angle " << psi << endl;
+//
+//  // return comparison
+//  return phi < psi;
+//};
 
 /**
@@ -537,6 +558,7 @@
  * @return point which is second closest to the provided one
  */
-TesselPoint* FindSecondClosestPoint(const Vector* Point, const LinkedCell* const LC)
-{
+TesselPoint* FindSecondClosestTesselPoint(const Vector* Point, const LinkedCell* const LC)
+{
+	Info FunctionInfo(__func__);
   TesselPoint* closestPoint = NULL;
   TesselPoint* secondClosestPoint = NULL;
@@ -549,15 +571,15 @@
   for(int i=0;i<NDIM;i++) // store indices of this cell
     N[i] = LC->n[i];
-  Log() << Verbose(2) << "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);
-  //Log() << Verbose(0) << endl;
+  //Log() << Verbose(1) << 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();
-        //Log() << Verbose(3) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
+        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++) {
             helper.CopyVector(Point);
             helper.SubtractVector((*Runner)->node);
@@ -574,5 +596,5 @@
           }
         } else {
-          eLog() << Verbose(0) << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << ","
+          eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << ","
             << LC->n[2] << " is invalid!" << endl;
         }
@@ -591,6 +613,7 @@
  * @return point which is closest to the provided one, NULL if none found
  */
-TesselPoint* FindClosestPoint(const Vector* Point, TesselPoint *&SecondPoint, const LinkedCell* const LC)
-{
+TesselPoint* FindClosestTesselPoint(const Vector* Point, TesselPoint *&SecondPoint, const LinkedCell* const LC)
+{
+	Info FunctionInfo(__func__);
   TesselPoint* closestPoint = NULL;
   SecondPoint = NULL;
@@ -603,18 +626,18 @@
   for(int i=0;i<NDIM;i++) // store indices of this cell
     N[i] = LC->n[i];
-  Log() << Verbose(3) << "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);
-  //Log() << Verbose(0) << endl;
+  //Log() << Verbose(1) << 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();
-        //Log() << Verbose(3) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
+        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++) {
             helper.CopyVector(Point);
             helper.SubtractVector((*Runner)->node);
-            double currentNorm = helper. Norm();
+            double currentNorm = helper.NormSquared();
             if (currentNorm < distance) {
               secondDistance = distance;
@@ -622,13 +645,13 @@
               distance = currentNorm;
               closestPoint = (*Runner);
-              //Log() << Verbose(2) << "INFO: New Nearest Neighbour is " << *closestPoint << "." << endl;
+              //Log() << Verbose(1) << "INFO: New Nearest Neighbour is " << *closestPoint << "." << endl;
             } else if (currentNorm < secondDistance) {
               secondDistance = currentNorm;
               SecondPoint = (*Runner);
-              //Log() << Verbose(2) << "INFO: New Second Nearest Neighbour is " << *SecondPoint << "." << endl;
+              //Log() << Verbose(1) << "INFO: New Second Nearest Neighbour is " << *SecondPoint << "." << endl;
             }
           }
         } else {
-          eLog() << Verbose(0) << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << ","
+          eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << ","
             << LC->n[2] << " is invalid!" << endl;
         }
@@ -636,8 +659,8 @@
   // output
   if (closestPoint != NULL) {
-    Log() << Verbose(2) << "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;
@@ -652,4 +675,5 @@
 Vector * GetClosestPointBetweenLine(const BoundaryLineSet * const Base, const BoundaryLineSet * const OtherBase)
 {
+	Info FunctionInfo(__func__);
   // construct the plane of the two baselines (i.e. take both their directional vectors)
   Vector Normal;
@@ -662,5 +686,5 @@
   Normal.VectorProduct(&OtherBaseline);
   Normal.Normalize();
-  Log() << Verbose(4) << "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)
@@ -679,5 +703,5 @@
   Normal.CopyVector(Intersection);
   Normal.SubtractVector(Base->endpoints[0]->node->node);
-  Log() << Verbose(3) << "Found closest point on " << *Base << " at " << *Intersection << ", factor in line is " << fabs(Normal.ScalarProduct(&Baseline)/Baseline.NormSquared()) << "." << endl;
+  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;
@@ -692,4 +716,5 @@
 double DistanceToTrianglePlane(const Vector *x, const BoundaryTriangleSet * const triangle)
 {
+	Info FunctionInfo(__func__);
   double distance = 0.;
   if (x == NULL) {
@@ -708,4 +733,5 @@
 void WriteVrmlFile(ofstream * const vrmlfile, const Tesselation * const Tess, const PointCloud * const cloud)
 {
+	Info FunctionInfo(__func__);
   TesselPoint *Walker = NULL;
   int i;
@@ -738,5 +764,5 @@
     }
   } else {
-    eLog() << Verbose(0) << "ERROR: Given vrmlfile is " << vrmlfile << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Given vrmlfile is " << vrmlfile << "." << endl);
   }
   delete(center);
@@ -751,19 +777,23 @@
 void IncludeSphereinRaster3D(ofstream * const rasterfile, const Tesselation * const Tess, const PointCloud * const cloud)
 {
+	Info FunctionInfo(__func__);
   Vector helper;
-  // include the current position of the virtual sphere in the temporary raster3d file
-  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);
-  // 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 << "9\n  terminating special property\n";
-  delete(center);
+
+  if (Tess->LastTriangle != NULL) {
+    // include the current position of the virtual sphere in the temporary raster3d file
+    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);
+    // 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 << "9\n  terminating special property\n";
+    delete(center);
+  }
 };
 
@@ -776,4 +806,5 @@
 void WriteRaster3dFile(ofstream * const rasterfile, const Tesselation * const Tess, const PointCloud * const cloud)
 {
+	Info FunctionInfo(__func__);
   TesselPoint *Walker = NULL;
   int i;
@@ -808,5 +839,5 @@
     *rasterfile << "9\n#  terminating special property\n";
   } else {
-    eLog() << Verbose(0) << "ERROR: Given rasterfile is " << rasterfile << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "Given rasterfile is " << rasterfile << "." << endl);
   }
   IncludeSphereinRaster3D(rasterfile, Tess, cloud);
@@ -821,14 +852,23 @@
 void WriteTecplotFile(ofstream * const tecplot, const Tesselation * const TesselStruct, const PointCloud * const cloud, const int N)
 {
+	Info FunctionInfo(__func__);
   if ((tecplot != NULL) && (TesselStruct != NULL)) {
     // write header
     *tecplot << "TITLE = \"3D CONVEX SHELL\"" << endl;
     *tecplot << "VARIABLES = \"X\" \"Y\" \"Z\" \"U\"" << endl;
-    *tecplot << "ZONE T=\"" << N << "-";
-    for (int i=0;i<3;i++)
-      *tecplot << (i==0 ? "" : "_") << TesselStruct->LastTriangle->endpoints[i]->node->Name;
+    *tecplot << "ZONE T=\"";
+    if (N < 0) {
+      *tecplot << cloud->GetName();
+    } else {
+      *tecplot << N << "-";
+      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;
-    int i=0;
-    for (cloud->GoToFirst(); !cloud->IsEnd(); cloud->GoToNext(), i++);
+    int i=cloud->GetMaxId();
     int *LookupList = new int[i];
     for (cloud->GoToFirst(), i=0; !cloud->IsEnd(); cloud->GoToNext(), i++)
@@ -836,5 +876,4 @@
 
     // print atom coordinates
-    Log() << Verbose(2) << "The following triangles were created:";
     int Counter = 1;
     TesselPoint *Walker = NULL;
@@ -846,10 +885,10 @@
     *tecplot << endl;
     // print connectivity
+    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(0) << " " << runner->second->endpoints[0]->node->Name << "<->" << runner->second->endpoints[1]->node->Name << "<->" << runner->second->endpoints[2]->node->Name;
+      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;
     }
     delete[] (LookupList);
-    Log() << Verbose(0) << endl;
   }
 };
@@ -862,21 +901,20 @@
 void CalculateConcavityPerBoundaryPoint(const Tesselation * const TesselStruct)
 {
+	Info FunctionInfo(__func__);
   class BoundaryPointSet *point = NULL;
   class BoundaryLineSet *line = NULL;
 
-  //Log() << Verbose(2) << "Begin of CalculateConcavityPerBoundaryPoint" << endl;
   // calculate remaining concavity
   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++) {
       line = LineRunner->second;
-      //Log() << Verbose(2) << "INFO: Current line of point " << *point << " is " << *line << "." << endl;
+      //Log() << Verbose(1) << "INFO: Current line of point " << *point << " is " << *line << "." << endl;
       if (!line->CheckConvexityCriterion())
         point->value += 1;
     }
   }
-  //Log() << Verbose(2) << "End of CalculateConcavityPerBoundaryPoint" << endl;
 };
 
@@ -889,17 +927,18 @@
 bool CheckListOfBaselines(const Tesselation * const TesselStruct)
 {
+	Info FunctionInfo(__func__);
   LineMap::const_iterator testline;
   bool result = false;
   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(1) << *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;
   }
@@ -907,2 +946,91 @@
 }
 
+/** Counts the number of triangle pairs that contain the given polygon.
+ * \param *P polygon with endpoints to look for
+ * \param *T set of triangles to create pairs from containing \a *P
+ */
+int CountTrianglePairContainingPolygon(const BoundaryPolygonSet * const P, const TriangleSet * const T)
+{
+  Info FunctionInfo(__func__);
+  // check number of endpoints in *P
+  if (P->endpoints.size() != 4) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "CountTrianglePairContainingPolygon works only on polygons with 4 nodes!" << endl);
+    return 0;
+  }
+
+  // check number of triangles in *T
+  if (T->size() < 2) {
+    DoeLog(1) && (eLog()<< Verbose(1) << "Not enough triangles to have pairs!" << endl);
+    return 0;
+  }
+
+  DoLog(0) && (Log() << Verbose(0) << "Polygon is " << *P << endl);
+  // create each pair, get the endpoints and check whether *P is contained.
+  int counter = 0;
+  PointSet Trianglenodes;
+  class BoundaryPolygonSet PairTrianglenodes;
+  for(TriangleSet::iterator Walker = T->begin(); Walker != T->end(); Walker++) {
+    for (int i=0;i<3;i++)
+      Trianglenodes.insert((*Walker)->endpoints[i]);
+
+    for(TriangleSet::iterator PairWalker = Walker; PairWalker != T->end(); PairWalker++) {
+      if (Walker != PairWalker) { // skip first
+        PairTrianglenodes.endpoints = Trianglenodes;
+        for (int i=0;i<3;i++)
+          PairTrianglenodes.endpoints.insert((*PairWalker)->endpoints[i]);
+        const int size = PairTrianglenodes.endpoints.size();
+        if (size == 4) {
+          DoLog(0) && (Log() << Verbose(0) << " Current pair of triangles: " << **Walker << "," << **PairWalker << " with " << size << " distinct endpoints:" << PairTrianglenodes << endl);
+          // now check
+          if (PairTrianglenodes.ContainsPresentTupel(P)) {
+            counter++;
+            DoLog(0) && (Log() << Verbose(0) << "  ACCEPT: Matches with " << *P << endl);
+          } else {
+            DoLog(0) && (Log() << Verbose(0) << "  REJECT: No match with " << *P << endl);
+          }
+        } else {
+          DoLog(0) && (Log() << Verbose(0) << "  REJECT: Less than four endpoints." << endl);
+        }
+      }
+    }
+    Trianglenodes.clear();
+  }
+  return counter;
+};
+
+/** Checks whether two give polygons have two or more points in common.
+ * \param *P1 first polygon
+ * \param *P2 second polygon
+ * \return true - are connected, false = are note
+ */
+bool ArePolygonsEdgeConnected(const BoundaryPolygonSet * const P1, const BoundaryPolygonSet * const P2)
+{
+  Info FunctionInfo(__func__);
+  int counter = 0;
+  for(PointSet::const_iterator Runner = P1->endpoints.begin(); Runner != P1->endpoints.end(); Runner++) {
+    if (P2->ContainsBoundaryPoint((*Runner))) {
+      counter++;
+      DoLog(1) && (Log() << Verbose(1) << *(*Runner) << " of second polygon is found in the first one." << endl);
+      return true;
+    }
+  }
+  return false;
+};
+
+/** Combines second into the first and deletes the second.
+ * \param *P1 first polygon, contains all nodes on return
+ * \param *&P2 second polygon, is deleted.
+ */
+void CombinePolygons(BoundaryPolygonSet * const P1, BoundaryPolygonSet * &P2)
+{
+  Info FunctionInfo(__func__);
+  pair <PointSet::iterator, bool> Tester;
+  for(PointSet::iterator Runner = P2->endpoints.begin(); Runner != P2->endpoints.end(); Runner++) {
+    Tester = P1->endpoints.insert((*Runner));
+    if (Tester.second)
+      DoLog(0) && (Log() << Verbose(0) << "Inserting endpoint " << *(*Runner) << " into first polygon." << endl);
+  }
+  P2->endpoints.clear();
+  delete(P2);
+};
+
Index: src/tesselationhelpers.hpp
===================================================================
--- src/tesselationhelpers.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/tesselationhelpers.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -59,6 +59,6 @@
 bool CheckLineCriteriaForDegeneratedTriangle(const BoundaryPointSet * const nodes[3]);
 bool SortCandidates(const CandidateForTesselation* candidate1, const CandidateForTesselation *candidate2);
-TesselPoint* FindClosestPoint(const Vector* Point, TesselPoint *&SecondPoint, const LinkedCell* const LC);
-TesselPoint* FindSecondClosestPoint(const Vector*, const LinkedCell* const LC);
+TesselPoint* FindClosestTesselPoint(const Vector* Point, TesselPoint *&SecondPoint, const LinkedCell* const LC);
+TesselPoint* FindSecondClosestTesselPoint(const Vector*, const LinkedCell* const LC);
 Vector * GetClosestPointBetweenLine(const BoundaryLineSet * const Base, const BoundaryLineSet * const OtherBase);
 
@@ -72,4 +72,8 @@
 bool CheckListOfBaselines(const Tesselation * const TesselStruct);
 
+int CountTrianglePairContainingPolygon(const BoundaryPolygonSet * const P, const TriangleSet * const T);
+bool ArePolygonsEdgeConnected(const BoundaryPolygonSet * const P1, const BoundaryPolygonSet * const P2);
+void CombinePolygons(BoundaryPolygonSet * const P1, BoundaryPolygonSet * &P2);
+
 
 #endif /* TESSELATIONHELPERS_HPP_ */
Index: src/triangleintersectionlist.cpp
===================================================================
--- src/triangleintersectionlist.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/triangleintersectionlist.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,173 @@
+/*
+ * 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);
+    TestVector.SubtractVector((*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 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/triangleintersectionlist.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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/unittests/AnalysisCorrelationToPointUnitTest.cpp
===================================================================
--- src/unittests/AnalysisCorrelationToPointUnitTest.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/AnalysisCorrelationToPointUnitTest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -11,4 +11,6 @@
 #include <cppunit/extensions/TestFactoryRegistry.h>
 #include <cppunit/ui/text/TestRunner.h>
+
+#include <cstring>
 
 #include "analysis_correlation.hpp"
@@ -116,6 +118,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 );
@@ -129,6 +131,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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -11,4 +11,6 @@
 #include <cppunit/extensions/TestFactoryRegistry.h>
 #include <cppunit/ui/text/TestRunner.h>
+
+#include <cstring>
 
 #include "analysis_correlation.hpp"
@@ -58,55 +60,55 @@
 
   // construct molecule (tetraeder of hydrogens) base
+  TestSurfaceMolecule = new molecule(tafel);
+  Walker = new atom();
+  Walker->type = hydrogen;
+  Walker->node->Init(1., 0., 1. );
+  TestSurfaceMolecule->AddAtom(Walker);
+  Walker = new atom();
+  Walker->type = hydrogen;
+  Walker->node->Init(0., 1., 1. );
+  TestSurfaceMolecule->AddAtom(Walker);
+  Walker = new atom();
+  Walker->type = hydrogen;
+  Walker->node->Init(1., 1., 0. );
+  TestSurfaceMolecule->AddAtom(Walker);
+  Walker = new atom();
+  Walker->type = hydrogen;
+  Walker->node->Init(0., 0., 0. );
+  TestSurfaceMolecule->AddAtom(Walker);
+
+  // check that TestMolecule was correctly constructed
+  CPPUNIT_ASSERT_EQUAL( TestSurfaceMolecule->AtomCount, 4 );
+
+  TestList = new MoleculeListClass;
+  TestSurfaceMolecule->ActiveFlag = true;
+  TestList->insert(TestSurfaceMolecule);
+
+  // init tesselation and linked cell
+  Surface = new Tesselation;
+  LC = new LinkedCell(TestSurfaceMolecule, 5.);
+  FindNonConvexBorder(TestSurfaceMolecule, Surface, (const LinkedCell *&)LC, 2.5, NULL);
+
+  // add outer atoms
   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);
-
-  // check that TestMolecule was correctly constructed
-  CPPUNIT_ASSERT_EQUAL( TestMolecule->AtomCount, 4 );
-
-  TestList = new MoleculeListClass;
+  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);
+  // add inner atoms
+  Walker = new atom();
+  Walker->type = carbon;
+  Walker->node->Init(0.5, 0.5, 0.5 );
+  TestMolecule->AddAtom(Walker);
   TestMolecule->ActiveFlag = true;
   TestList->insert(TestMolecule);
-
-  // 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() );
-
-  // 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);
-  // add inner atoms
-  Walker = new atom();
-  Walker->type = carbon;
-  Walker->node->Init(0.5, 0.5, 0.5 );
-  TestMolecule->AddAtom(Walker);
 
   // init maps
@@ -134,8 +136,21 @@
 
 
+/** Checks whether setup() does the right thing.
+ */
+void AnalysisCorrelationToSurfaceUnitTest::SurfaceTest()
+{
+  CPPUNIT_ASSERT_EQUAL( 4, TestSurfaceMolecule->AtomCount );
+  CPPUNIT_ASSERT_EQUAL( 4, TestMolecule->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()
 {
   // 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() );
@@ -147,7 +162,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 );
@@ -160,8 +176,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 );
@@ -177,14 +194,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 );
@@ -195,17 +213,17 @@
   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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/AnalysisCorrelationToSurfaceUnitTest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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();
@@ -43,4 +45,5 @@
       MoleculeListClass *TestList;
       molecule *TestMolecule;
+      molecule *TestSurfaceMolecule;
       element *hydrogen;
       element *carbon;
Index: src/unittests/AnalysisPairCorrelationUnitTest.cpp
===================================================================
--- src/unittests/AnalysisPairCorrelationUnitTest.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/AnalysisPairCorrelationUnitTest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -11,4 +11,6 @@
 #include <cppunit/extensions/TestFactoryRegistry.h>
 #include <cppunit/ui/text/TestRunner.h>
+
+#include <cstring>
 
 #include "analysis_correlation.hpp"
Index: src/unittests/CountBondsUnitTest.cpp
===================================================================
--- src/unittests/CountBondsUnitTest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/CountBondsUnitTest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,257 @@
+/*
+ * 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 "CountBondsUnitTest.hpp"
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( CountBondsTest );
+
+
+void CountBondsTest::setUp()
+{
+  atom *Walker = 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 = new periodentafel;
+  tafel->AddElement(hydrogen);
+  tafel->AddElement(oxygen);
+
+  // construct molecule (water molecule)
+  molecules = new MoleculeListClass;
+  TestMolecule1 = new molecule(tafel);
+  Walker = new atom();
+  Walker->type = hydrogen;
+  Walker->node->Init(-0.2418, 0.9350, 0. );
+  TestMolecule1->AddAtom(Walker);
+  Walker = new atom();
+  Walker->type = hydrogen;
+  Walker->node->Init(0.9658, 0., 0. );
+  TestMolecule1->AddAtom(Walker);
+  Walker = new atom();
+  Walker->type = oxygen;
+  Walker->node->Init(0., 0., 0. );
+  TestMolecule1->AddAtom(Walker);
+  molecules->insert(TestMolecule1);
+
+  TestMolecule2 = new molecule(tafel);
+  Walker = new atom();
+  Walker->type = hydrogen;
+  Walker->node->Init(-0.2418, 0.9350, 0. );
+  TestMolecule2->AddAtom(Walker);
+  Walker = new atom();
+  Walker->type = hydrogen;
+  Walker->node->Init(0.9658, 0., 0. );
+  TestMolecule2->AddAtom(Walker);
+  Walker = new atom();
+  Walker->type = oxygen;
+  Walker->node->Init(0., 0., 0. );
+  TestMolecule2->AddAtom(Walker);
+  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);
+
+  // remove molecule
+  delete(molecules);
+  // note that all the atoms are cleaned by TestMolecule
+  delete(tafel);
+  // note that element is cleaned by periodentafel
+};
+
+/** 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.Init(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.Init(-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.Init(0,3,0);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 1 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-2.xyz");
+  Translator.Init(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.Init(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.Init(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.Init(2,1,0);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 1 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-4.xyz");
+  Translator.Init(-2,-1,0);
+  TestMolecule2->Translate(&Translator);
+
+  cout << "Case 5: offset of (0,0,3), hence angle are (90, 90, 90, 90) > 30." << endl;
+  Translator.Init(0,0,3);
+  TestMolecule2->Translate(&Translator);
+  CPPUNIT_ASSERT_EQUAL( 0 , CountHydrogenBridgeBonds(molecules, NULL) );
+  //OutputTestMolecule(TestMolecule2, "testmolecule2-5.xyz");
+  Translator.Init(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.Init(-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.Init(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.Init(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.Init(-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.Init(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.Init(0,-3,0);
+  TestMolecule2->Translate(&Translator);
+  TestMolecule2->Scale((const double ** const)&mirror);
+
+  delete(mirror);
+};
+
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
Index: src/unittests/CountBondsUnitTest.hpp
===================================================================
--- src/unittests/CountBondsUnitTest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/CountBondsUnitTest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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/LinkedCellUnitTest.cpp
===================================================================
--- src/unittests/LinkedCellUnitTest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/LinkedCellUnitTest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,391 @@
+/*
+ * 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"
+
+/********************************************** 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 = new periodentafel;
+  tafel->AddElement(hydrogen);
+
+  // construct molecule (water molecule)
+  TestMolecule = new molecule(tafel);
+  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 = new atom();
+        Walker->type = hydrogen;
+        Walker->node->Init(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);
+  delete(TestMolecule);
+  // note that all the atoms are cleaned by TestMolecule
+  delete(tafel);
+  // note that element is cleaned by periodentafel
+};
+
+
+/** 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 = new atom();
+  Walker->Name = Malloc<char>(6, "LinkedCellTest::SetIndexToNodeTest - Walker");
+  strcpy(Walker->Name, "test");
+  Walker->x.Init(1,1,1);
+  CPPUNIT_ASSERT_EQUAL( false, LC->SetIndexToNode(Walker) );
+  delete(Walker);
+
+  // check out of bounds vectors
+  Walker = new atom();
+  Walker->Name = Malloc<char>(6, "LinkedCellTest::SetIndexToNodeTest - Walker");
+  strcpy(Walker->Name, "test");
+  Walker->x.Init(0,-1,0);
+  CPPUNIT_ASSERT_EQUAL( false, LC->SetIndexToNode(Walker) );
+  delete(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.Init(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.Init(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.Init(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.Init(-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.Init(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.Init(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.Init(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.x[0] <2) && (Walker->x.x[1] <2) && (Walker->x.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.Init(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.Init(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);
+};
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
+
Index: src/unittests/LinkedCellUnitTest.hpp
===================================================================
--- src/unittests/LinkedCellUnitTest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/LinkedCellUnitTest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/Makefile.am	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -4,43 +4,96 @@
 AM_CXXFLAGS = $(CPPUNIT_CFLAGS)
 
-TESTS = ActOnAllUnitTest AnalysisBondsUnitTests AnalysisCorrelationToPointUnitTest AnalysisCorrelationToSurfaceUnitTest AnalysisPairCorrelationUnitTest BondGraphUnitTest ListOfBondsUnitTest LogUnitTest MemoryUsageObserverUnitTest MemoryAllocatorUnitTest StackClassUnitTest VectorUnitTest
+TESTS = \
+  ActOnAllUnitTest \
+  AnalysisBondsUnitTests \
+  AnalysisCorrelationToPointUnitTest \
+  AnalysisCorrelationToSurfaceUnitTest \
+  AnalysisPairCorrelationUnitTest \
+  BondGraphUnitTest \
+  CountBondsUnitTest \
+  GSLMatrixSymmetricUnitTest \
+  GSLMatrixUnitTest \
+  GSLVectorUnitTest \
+  InfoUnitTest \
+  LinearSystemOfEquationsUnitTest \
+  LinkedCellUnitTest \
+  ListOfBondsUnitTest \
+  LogUnitTest \
+  MemoryUsageObserverUnitTest \
+  MemoryAllocatorUnitTest \
+  StackClassUnitTest \
+  TesselationUnitTest \
+  Tesselation_BoundaryTriangleUnitTest \
+  Tesselation_InOutsideUnitTest \
+  VectorUnitTest
+  
 check_PROGRAMS = $(TESTS)
 noinst_PROGRAMS = $(TESTS)
 
 ActOnAllUnitTest_SOURCES = ../test/ActOnAllTest.hpp ActOnAllUnitTest.cpp ActOnAllUnitTest.hpp
-ActOnAllUnitTest_LDADD = ../libmolecuilder.a
+ActOnAllUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 AnalysisBondsUnitTests_SOURCES = analysisbondsunittest.cpp analysisbondsunittest.hpp
-AnalysisBondsUnitTests_LDADD = ../libmolecuilder.a
+AnalysisBondsUnitTests_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 AnalysisCorrelationToPointUnitTest_SOURCES = analysis_correlation.hpp AnalysisCorrelationToPointUnitTest.cpp AnalysisCorrelationToPointUnitTest.hpp
-AnalysisCorrelationToPointUnitTest_LDADD = ../libmolecuilder.a
+AnalysisCorrelationToPointUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 AnalysisCorrelationToSurfaceUnitTest_SOURCES = analysis_correlation.hpp AnalysisCorrelationToSurfaceUnitTest.cpp AnalysisCorrelationToSurfaceUnitTest.hpp
-AnalysisCorrelationToSurfaceUnitTest_LDADD = ../libmolecuilder.a
+AnalysisCorrelationToSurfaceUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 AnalysisPairCorrelationUnitTest_SOURCES = analysis_correlation.hpp AnalysisPairCorrelationUnitTest.cpp AnalysisPairCorrelationUnitTest.hpp
-AnalysisPairCorrelationUnitTest_LDADD = ../libmolecuilder.a
+AnalysisPairCorrelationUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 BondGraphUnitTest_SOURCES = bondgraphunittest.cpp bondgraphunittest.hpp
-BondGraphUnitTest_LDADD = ../libmolecuilder.a
+BondGraphUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
+
+CountBondsUnitTest_SOURCES = CountBondsUnitTest.cpp CountBondsUnitTest.hpp
+CountBondsUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
+
+GSLMatrixSymmetricUnitTest_SOURCES = gslmatrixsymmetricunittest.cpp gslmatrixsymmetricunittest.hpp
+GSLMatrixSymmetricUnitTest_LDADD = ../libgslwrapper.a
+
+GSLMatrixUnitTest_SOURCES = gslmatrixunittest.cpp gslmatrixunittest.hpp
+GSLMatrixUnitTest_LDADD = ../libgslwrapper.a
+
+GSLVectorUnitTest_SOURCES = gslvectorunittest.cpp gslvectorunittest.hpp
+GSLVectorUnitTest_LDADD = ../libgslwrapper.a
+
+InfoUnitTest_SOURCES = infounittest.cpp infounittest.hpp
+InfoUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
+
+LinearSystemOfEquationsUnitTest_SOURCES = linearsystemofequationsunittest.cpp linearsystemofequationsunittest.hpp
+LinearSystemOfEquationsUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
+
+LinkedCellUnitTest_SOURCES = LinkedCellUnitTest.cpp LinkedCellUnitTest.hpp 
+LinkedCellUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 ListOfBondsUnitTest_SOURCES = listofbondsunittest.cpp listofbondsunittest.hpp
-ListOfBondsUnitTest_LDADD = ../libmolecuilder.a
+ListOfBondsUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 LogUnitTest_SOURCES = logunittest.cpp logunittest.hpp 
-LogUnitTest_LDADD = ../libmolecuilder.a
+LogUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 MemoryAllocatorUnitTest_SOURCES = memoryallocatorunittest.cpp memoryallocatorunittest.hpp 
-MemoryAllocatorUnitTest_LDADD = ../libmolecuilder.a
+MemoryAllocatorUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 MemoryUsageObserverUnitTest_SOURCES = memoryusageobserverunittest.cpp memoryusageobserverunittest.hpp 
-MemoryUsageObserverUnitTest_LDADD = ../libmolecuilder.a
+MemoryUsageObserverUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 StackClassUnitTest_SOURCES = stackclassunittest.cpp stackclassunittest.hpp
-StackClassUnitTest_LDADD = ../libmolecuilder.a
+StackClassUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
+
+TesselationUnitTest_SOURCES = tesselationunittest.cpp tesselationunittest.hpp
+TesselationUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
+
+Tesselation_BoundaryTriangleUnitTest_SOURCES = tesselation_boundarytriangleunittest.cpp tesselation_boundarytriangleunittest.hpp
+Tesselation_BoundaryTriangleUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
+
+Tesselation_InOutsideUnitTest_SOURCES = tesselation_insideoutsideunittest.cpp tesselation_insideoutsideunittest.hpp
+Tesselation_InOutsideUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 VectorUnitTest_SOURCES = vectorunittest.cpp vectorunittest.hpp 
-VectorUnitTest_LDADD = ../libmolecuilder.a
+VectorUnitTest_LDADD = ../libmolecuilder.a ../libgslwrapper.a
 
 
Index: src/unittests/analysisbondsunittest.cpp
===================================================================
--- src/unittests/analysisbondsunittest.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/analysisbondsunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -14,5 +14,8 @@
 #include <iostream>
 #include <stdio.h>
+#include <cstring>
 
+#include "analysis_bonds.hpp"
+#include "analysisbondsunittest.hpp"
 #include "atom.hpp"
 #include "bond.hpp"
@@ -21,5 +24,4 @@
 #include "molecule.hpp"
 #include "periodentafel.hpp"
-#include "analysisbondsunittest.hpp"
 
 /********************************************** Test classes **************************************/
@@ -41,8 +43,12 @@
   hydrogen = new element;
   hydrogen->Z = 1;
+  hydrogen->Valence = 1;
+  hydrogen->NoValenceOrbitals = 1;
   strcpy(hydrogen->name, "hydrogen");
   strcpy(hydrogen->symbol, "H");
   carbon = new element;
   carbon->Z = 2;
+  carbon->Valence = 4;
+  carbon->NoValenceOrbitals = 4;
   strcpy(carbon->name, "carbon");
   strcpy(carbon->symbol, "C");
@@ -58,13 +64,13 @@
   Walker = new atom();
   Walker->type = hydrogen;
-  Walker->node->Init(1., 0., 1. );
+  Walker->node->Init(1.5, 0., 1.5 );
   TestMolecule->AddAtom(Walker);
   Walker = new atom();
   Walker->type = hydrogen;
-  Walker->node->Init(0., 1., 1. );
+  Walker->node->Init(0., 1.5, 1.5 );
   TestMolecule->AddAtom(Walker);
   Walker = new atom();
   Walker->type = hydrogen;
-  Walker->node->Init(1., 1., 0. );
+  Walker->node->Init(1.5, 1.5, 0. );
   TestMolecule->AddAtom(Walker);
   Walker = new atom();
@@ -72,7 +78,11 @@
   Walker->node->Init(0., 0., 0. );
   TestMolecule->AddAtom(Walker);
+  Walker = new atom();
+  Walker->type = carbon;
+  Walker->node->Init(0.5, 0.5, 0.5 );
+  TestMolecule->AddAtom(Walker);
 
   // check that TestMolecule was correctly constructed
-  CPPUNIT_ASSERT_EQUAL( TestMolecule->AtomCount, 4 );
+  CPPUNIT_ASSERT_EQUAL( TestMolecule->AtomCount, 5 );
 
   // create a small file with table
@@ -82,5 +92,13 @@
   test << "H\t1.\t1.2\n";
   test << "C\t1.2\t1.5\n";
+  test.close();
   BG = new BondGraph(true);
+
+  CPPUNIT_ASSERT_EQUAL( true , BG->LoadBondLengthTable(*filename) );
+  CPPUNIT_ASSERT_EQUAL( 1., BG->GetBondLength(0,0) );
+  CPPUNIT_ASSERT_EQUAL( 1.2, BG->GetBondLength(0,1) );
+  CPPUNIT_ASSERT_EQUAL( 1.5, BG->GetBondLength(1,1) );
+
+  BG->ConstructBondGraph(TestMolecule);
 };
 
@@ -100,16 +118,50 @@
 };
 
-/** UnitTest for AnalysisBondsTest::LoadBondLengthTable().
+/** UnitTest for GetMaxMinMeanBondCount().
  */
-void AnalysisBondsTest::BondsTest()
+void AnalysisBondsTest::GetMaxMinMeanBondCountTest()
 {
-  CPPUNIT_ASSERT_EQUAL( true , BG->LoadBondLengthTable(*filename) );
-  CPPUNIT_ASSERT_EQUAL( 1., BG->GetBondLength(0,0) );
-  CPPUNIT_ASSERT_EQUAL( 1.2, BG->GetBondLength(0,1) );
-  CPPUNIT_ASSERT_EQUAL( 1.5, BG->GetBondLength(1,1) );
-
-  CPPUNIT_ASSERT_EQUAL( true , true );
+  double Min = 20.; // check that initialization resets these arbitrary values
+  double Mean = 200.;
+  double Max = 1e-6;
+  GetMaxMinMeanBondCount(TestMolecule, Min, Mean, Max);
+  CPPUNIT_ASSERT_EQUAL( 1., Min );
+  CPPUNIT_ASSERT_EQUAL( 1.6, Mean );
+  CPPUNIT_ASSERT_EQUAL( 4., Max );
 
 };
+
+/** UnitTest for MinMaxBondDistanceBetweenElements().
+ */
+void AnalysisBondsTest::MinMeanMaxBondDistanceBetweenElementsTest()
+{
+  double Min = 20.; // check that initialization resets these arbitrary values
+  double Mean = 2e+6;
+  double Max = 1e-6;
+  double Min2 = 20.;
+  double Mean2 = 2e+6;
+  double Max2 = 1e-6;
+  const double maxbondlength = sqrt(1.*1. + 1.*1. + .5*.5);
+  const double minbondlength = sqrt(.5*.5 + .5*.5 + .5*.5);
+  const double meanbondlength = (minbondlength+3.*maxbondlength)/4.;
+  // check bond lengths C-H
+  MinMeanMaxBondDistanceBetweenElements(TestMolecule, hydrogen, carbon, Min, Mean, Max);
+  CPPUNIT_ASSERT_EQUAL( minbondlength , Min );
+  CPPUNIT_ASSERT_EQUAL( meanbondlength , Mean );
+  CPPUNIT_ASSERT_EQUAL( maxbondlength , Max );
+
+  // check that elements are symmetric, i.e. C-H == H-C
+  MinMeanMaxBondDistanceBetweenElements(TestMolecule, carbon, hydrogen, Min2, Mean2, Max2);
+  CPPUNIT_ASSERT_EQUAL( Min , Min2 );
+  CPPUNIT_ASSERT_EQUAL( Mean , Mean2 );
+  CPPUNIT_ASSERT_EQUAL( Max , Max2 );
+
+  // check no bond case (no bonds H-H in system!)
+  MinMeanMaxBondDistanceBetweenElements(TestMolecule, hydrogen, hydrogen, Min, Mean, Max);
+  CPPUNIT_ASSERT_EQUAL( 0. , Min );
+  CPPUNIT_ASSERT_EQUAL( 0. , Mean );
+  CPPUNIT_ASSERT_EQUAL( 0. , Max );
+};
+
 
 /********************************************** Main routine **************************************/
Index: src/unittests/analysisbondsunittest.hpp
===================================================================
--- src/unittests/analysisbondsunittest.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/analysisbondsunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -11,6 +11,5 @@
 #include <cppunit/extensions/HelperMacros.h>
 
-#include "bondgraph.hpp"
-
+class BondGraph;
 class element;
 class molecule;
@@ -22,5 +21,6 @@
 {
     CPPUNIT_TEST_SUITE( AnalysisBondsTest) ;
-    CPPUNIT_TEST ( BondsTest );
+    CPPUNIT_TEST ( GetMaxMinMeanBondCountTest );
+    CPPUNIT_TEST ( MinMeanMaxBondDistanceBetweenElementsTest );
     CPPUNIT_TEST_SUITE_END();
 
@@ -28,5 +28,6 @@
       void setUp();
       void tearDown();
-      void BondsTest();
+      void GetMaxMinMeanBondCountTest();
+      void MinMeanMaxBondDistanceBetweenElementsTest();
 
 private:
Index: src/unittests/bondgraphunittest.cpp
===================================================================
--- src/unittests/bondgraphunittest.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/bondgraphunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -14,4 +14,5 @@
 #include <iostream>
 #include <stdio.h>
+#include <cstring>
 
 #include "atom.hpp"
@@ -19,4 +20,5 @@
 #include "bondgraph.hpp"
 #include "element.hpp"
+#include "log.hpp"
 #include "molecule.hpp"
 #include "periodentafel.hpp"
@@ -41,8 +43,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");
@@ -57,17 +63,17 @@
   TestMolecule = new molecule(tafel);
   Walker = new atom();
-  Walker->type = hydrogen;
+  Walker->type = carbon;
   Walker->node->Init(1., 0., 1. );
   TestMolecule->AddAtom(Walker);
   Walker = new atom();
-  Walker->type = hydrogen;
+  Walker->type = carbon;
   Walker->node->Init(0., 1., 1. );
   TestMolecule->AddAtom(Walker);
   Walker = new atom();
-  Walker->type = hydrogen;
+  Walker->type = carbon;
   Walker->node->Init(1., 1., 0. );
   TestMolecule->AddAtom(Walker);
   Walker = new atom();
-  Walker->type = hydrogen;
+  Walker->type = carbon;
   Walker->node->Init(0., 0., 0. );
   TestMolecule->AddAtom(Walker);
@@ -77,4 +83,5 @@
 
   // create a small file with table
+  dummyname = new string("dummy.dat");
   filename = new string("test.dat");
   ofstream test(filename->c_str());
@@ -82,4 +89,5 @@
   test << "H\t1.\t1.2\n";
   test << "C\t1.2\t1.5\n";
+  test.close();
   BG = new BondGraph(true);
 };
@@ -91,4 +99,5 @@
   remove(filename->c_str());
   delete(filename);
+  delete(dummyname);
   delete(BG);
 
@@ -112,5 +121,5 @@
 /** UnitTest for BondGraphTest::ConstructBondGraph().
  */
-void BondGraphTest::ConstructGraphTest()
+void BondGraphTest::ConstructGraphFromTableTest()
 {
   atom *Walker = TestMolecule->start->next;
@@ -118,4 +127,16 @@
   CPPUNIT_ASSERT( TestMolecule->end != Walker );
   CPPUNIT_ASSERT_EQUAL( true , BG->LoadBondLengthTable(*filename) );
+  CPPUNIT_ASSERT_EQUAL( true , BG->ConstructBondGraph(TestMolecule) );
+  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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/bondgraphunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -11,6 +11,6 @@
 #include <cppunit/extensions/HelperMacros.h>
 
-#include "bondgraph.hpp"
 
+class BondGraph;
 class element;
 class molecule;
@@ -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/gslmatrixsymmetricunittest.cpp
===================================================================
--- src/unittests/gslmatrixsymmetricunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/gslmatrixsymmetricunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,288 @@
+/*
+ * gslmatrixunittest.cpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+using namespace std;
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include "gslmatrixsymmetricunittest.hpp"
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( GSLMatrixSymmetricTest );
+
+
+void GSLMatrixSymmetricTest::setUp()
+{
+  m = new GSLMatrix(3,3);
+};
+
+void GSLMatrixSymmetricTest::tearDown()
+{
+  delete(m);
+};
+
+/** Unit Test for accessing matrix elements.
+ *
+ */
+void GSLMatrixSymmetricTest::AccessTest()
+{
+  // check whether all elements are initially zero
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( 0., m->Get(i,j) );
+
+  // set
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, i*3+j );
+
+  // and check
+  double *ptr = NULL;
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++) {
+      CPPUNIT_ASSERT_EQUAL( (double)(i*3+j), m->Get(i,j) );
+      ptr = m->Pointer(i,j);
+      CPPUNIT_ASSERT_EQUAL( (double)(i*3+j), *ptr );
+    }
+
+  // assignment
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, i*3+j );
+  GSLMatrix *dest = new GSLMatrix(3,3);
+  *dest = *m;
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( dest->Get(i,j), m->Get(i,j) );
+  delete(dest);
+
+  // out of bounds
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(4,2) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(2,17) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(1024,140040) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(-1,0) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(0,-1) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(-1,-1) );
+};
+
+/** Unit Test for initializating matrices.
+ *
+ */
+void GSLMatrixSymmetricTest::InitializationTest()
+{
+  // set zero
+  m->SetZero();
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( 0., m->Get(i,j) );
+
+  // set all
+  m->SetAll(1.5);
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( 1.5, m->Get(i,j) );
+
+  // set basis
+  m->SetIdentity();
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( i == j ? 1. : 0. , m->Get(i,j) );
+
+  // set from array
+  double array[] = { 1., 0., 0.,
+                     0., 1., 0.,
+                     0., 0., 1. };
+  m->SetFromDoubleArray(array);
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( i == j ? 1. : 0. , m->Get(i,j) );
+
+};
+
+/** Unit Test for copying matrices.
+ *
+ */
+void GSLMatrixSymmetricTest::CopyTest()
+{
+  // set basis
+  GSLMatrix *dest = NULL;
+  for (int i=0;i<3;i++) {
+    m->SetAll(i);
+    dest = new GSLMatrix(m);
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( m->Get(i,j) , dest->Get(i,j) );
+
+    delete(dest);
+  }
+};
+
+/** Unit Test for exchanging rows and columns.
+ *
+ */
+void GSLMatrixSymmetricTest::ExchangeTest()
+{
+  // set to 1,1,1,2, ...
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, i+1 );
+
+  // swap such that nothing happens
+  m->SwapColumns(1,2);
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)i+1., m->Get(i,j) );
+
+  // swap two rows
+  m->SwapRows(1,2);
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      switch (j) {
+        case 0:
+          CPPUNIT_ASSERT_EQUAL( 1., m->Get(j,i) );
+          break;
+        case 1:
+          CPPUNIT_ASSERT_EQUAL( 3., m->Get(j,i) );
+          break;
+        case 2:
+          CPPUNIT_ASSERT_EQUAL( 2., m->Get(j,i) );
+          break;
+        default:
+          CPPUNIT_ASSERT_EQUAL( -1., m->Get(i,j) );
+      }
+  // check that op is reversable
+  m->SwapRows(1,2);
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)i+1., m->Get(i,j) );
+
+  // set to 1,2,3,1, ...
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, j+1. );
+
+  // swap such that nothing happens
+  m->SwapRows(0,2);
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)j+1., m->Get(i,j) );
+
+  // swap two columns
+  m->SwapColumns(0,2);
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      switch (j) {
+        case 0:
+          CPPUNIT_ASSERT_EQUAL( 3., m->Get(i,j) );
+          break;
+        case 1:
+          CPPUNIT_ASSERT_EQUAL( 2., m->Get(i,j) );
+          break;
+        case 2:
+          CPPUNIT_ASSERT_EQUAL( 1., m->Get(i,j) );
+          break;
+        default:
+          CPPUNIT_ASSERT_EQUAL( -1., m->Get(i,j) );
+      }
+  // check that op is reversable
+  m->SwapColumns(0,2);
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)j+1., m->Get(i,j) );
+
+
+  // set to 1,2,3,4, ...
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, 3*i+j+1 );
+  // transpose
+  m->Transpose();
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)(3*i+j+1), m->Get(j,i) );
+  // second transpose
+  m->Transpose();
+  for (int i=0;i<3;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)(3*i+j+1), m->Get(i,j) );
+};
+
+/** Unit Test for matrix properties.
+ *
+ */
+void GSLMatrixSymmetricTest::PropertiesTest()
+{
+  // is zero
+  m->SetZero();
+  CPPUNIT_ASSERT_EQUAL( true, m->IsNull() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsPositive() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNegative() );
+  CPPUNIT_ASSERT_EQUAL( true, m->IsNonNegative() );
+
+  // is positive
+  m->SetAll(0.5);
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNull() );
+  CPPUNIT_ASSERT_EQUAL( true, m->IsPositive() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNegative() );
+  CPPUNIT_ASSERT_EQUAL( true, m->IsNonNegative() );
+
+  // is negative
+  m->SetAll(-0.1);
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNull() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsPositive() );
+  CPPUNIT_ASSERT_EQUAL( true, m->IsNegative() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNonNegative() );
+
+  // is positive definite
+  double array[] = { 1., 0., 0.,
+                     0., 1., 1.,
+                     0., 0., 1. };
+  m->SetFromDoubleArray(array);
+  CPPUNIT_ASSERT_EQUAL( true, m->IsPositiveDefinite() );
+
+  //determinant
+  m->SetIdentity();
+  CPPUNIT_ASSERT_EQUAL( 1., m->Determinant() );
+
+  m->SetZero();
+  CPPUNIT_ASSERT_EQUAL( 0., m->Determinant() );
+
+  m->Set( 0, 0, 1.);
+  m->Set( 1, 1, 1.);
+  m->Set( 2, 1, 1.);
+  CPPUNIT_ASSERT_EQUAL( 0., m->Determinant() );
+  
+  double array2[] = { 2., 0., 1.,
+                     -3., 1., 1.,
+                     1., 5.5, 1. };
+  m->SetFromDoubleArray(array2);
+  CPPUNIT_ASSERT_EQUAL( -26.5, m->Determinant() );
+};
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
Index: src/unittests/gslmatrixsymmetricunittest.hpp
===================================================================
--- src/unittests/gslmatrixsymmetricunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/gslmatrixsymmetricunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,42 @@
+/*
+ * gslmatrixunittest.hpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+#ifndef GSLMATRIXUNITTEST_HPP_
+#define GSLMATRIXUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "gslmatrix.hpp"
+
+/********************************************** Test classes **************************************/
+
+class GSLMatrixSymmetricTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( GSLMatrixSymmetricTest) ;
+    CPPUNIT_TEST (AccessTest );
+    CPPUNIT_TEST (InitializationTest );
+    CPPUNIT_TEST (CopyTest );
+    CPPUNIT_TEST (ExchangeTest );
+    CPPUNIT_TEST (PropertiesTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+    void setUp();
+    void tearDown();
+
+    void AccessTest();
+    void InitializationTest();
+    void CopyTest();
+    void ExchangeTest();
+    void PropertiesTest();
+
+private:
+    GSLMatrix *m;
+};
+
+
+#endif /* GSLMATRIXUNITTEST_HPP_ */
Index: src/unittests/gslmatrixunittest.cpp
===================================================================
--- src/unittests/gslmatrixunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/gslmatrixunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,270 @@
+/*
+ * gslmatrixunittest.cpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+using namespace std;
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include "gslmatrixunittest.hpp"
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( GSLMatrixTest );
+
+
+void GSLMatrixTest::setUp()
+{
+  m = new GSLMatrix(4,3);
+};
+
+void GSLMatrixTest::tearDown()
+{
+  delete(m);
+};
+
+/** Unit Test for accessing matrix elements.
+ *
+ */
+void GSLMatrixTest::AccessTest()
+{
+  // check whether all elements are initially zero
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( 0., m->Get(i,j) );
+
+  // set
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, i*3+j );
+
+  // and check
+  double *ptr = NULL;
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++) {
+      CPPUNIT_ASSERT_EQUAL( (double)(i*3+j), m->Get(i,j) );
+      ptr = m->Pointer(i,j);
+      CPPUNIT_ASSERT_EQUAL( (double)(i*3+j), *ptr );
+    }
+
+  // assignment
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, i*3+j );
+  GSLMatrix *dest = new GSLMatrix(4,3);
+  *dest = *m;
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( dest->Get(i,j), m->Get(i,j) );
+  delete(dest);
+
+  // out of bounds
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(5,2) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(2,17) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(1024,140040) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(-1,0) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(0,-1) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(-1,-1) );
+};
+
+/** Unit Test for initializating matrices.
+ *
+ */
+void GSLMatrixTest::InitializationTest()
+{
+  // set zero
+  m->SetZero();
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( 0., m->Get(i,j) );
+
+  // set all
+  m->SetAll(1.5);
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( 1.5, m->Get(i,j) );
+
+  // set basis
+  m->SetIdentity();
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( i == j ? 1. : 0. , m->Get(i,j) );
+
+  // set from array
+  double array[] = { 1., 0., 0.,
+                     0., 1., 0.,
+                     0., 0., 1.,
+                     0., 0., 0. };
+  m->SetFromDoubleArray(array);
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( i == j ? 1. : 0. , m->Get(i,j) );
+
+};
+
+/** Unit Test for copying matrices.
+ *
+ */
+void GSLMatrixTest::CopyTest()
+{
+  // set basis
+  GSLMatrix *dest = NULL;
+  for (int i=0;i<4;i++) {
+    m->SetAll(i);
+    dest = new GSLMatrix(m);
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( m->Get(i,j) , dest->Get(i,j) );
+
+    delete(dest);
+  }
+};
+
+/** Unit Test for exchanging rows and columns.
+ *
+ */
+void GSLMatrixTest::ExchangeTest()
+{
+  // set to 1,1,1,2, ...
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, i+1 );
+
+  // swap such that nothing happens
+  CPPUNIT_ASSERT_EQUAL( true, m->SwapColumns(1,2) );
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)i+1., m->Get(i,j) );
+
+  // swap two rows
+  CPPUNIT_ASSERT_EQUAL( true, m->SwapRows(1,2) );
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      switch (i) {
+        case 0:
+          CPPUNIT_ASSERT_EQUAL( 1., m->Get(i,j) );
+          break;
+        case 1:
+          CPPUNIT_ASSERT_EQUAL( 3., m->Get(i,j) );
+          break;
+        case 2:
+          CPPUNIT_ASSERT_EQUAL( 2., m->Get(i,j) );
+          break;
+        case 3:
+          CPPUNIT_ASSERT_EQUAL( 4., m->Get(i,j) );
+          break;
+        default:
+          CPPUNIT_ASSERT_EQUAL( -1., m->Get(i,j) );
+      }
+  // check that op is reversable
+  CPPUNIT_ASSERT_EQUAL( true, m->SwapRows(1,2) );
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)i+1., m->Get(i,j) );
+
+  // set to 1,2,3,1, ...
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, j+1. );
+
+  // swap such that nothing happens
+  CPPUNIT_ASSERT_EQUAL( true, m->SwapRows(0,2) );
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)j+1., m->Get(i,j) );
+
+  // swap two columns
+  CPPUNIT_ASSERT_EQUAL( true, m->SwapColumns(0,2) );
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      switch (j) {
+        case 0:
+          CPPUNIT_ASSERT_EQUAL( 3., m->Get(i,j) );
+          break;
+        case 1:
+          CPPUNIT_ASSERT_EQUAL( 2., m->Get(i,j) );
+          break;
+        case 2:
+          CPPUNIT_ASSERT_EQUAL( 1., m->Get(i,j) );
+          break;
+        default:
+          CPPUNIT_ASSERT_EQUAL( -1., m->Get(i,j) );
+      }
+  // check that op is reversable
+  CPPUNIT_ASSERT_EQUAL( true, m->SwapColumns(0,2) );
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)j+1., m->Get(i,j) );
+
+
+  // set to 1,2,3,4, ...
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      m->Set(i,j, 3*i+j+1 );
+  // transpose
+  CPPUNIT_ASSERT_EQUAL( true, m->Transpose() );
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)(3*i+j+1), m->Get(j,i) );
+  // second transpose
+  CPPUNIT_ASSERT_EQUAL( true, m->Transpose() );
+  for (int i=0;i<4;i++)
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (double)(3*i+j+1), m->Get(i,j) );
+};
+
+/** Unit Test for matrix properties.
+ *
+ */
+void GSLMatrixTest::PropertiesTest()
+{
+  // is zero
+  m->SetZero();
+  CPPUNIT_ASSERT_EQUAL( true, m->IsNull() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsPositive() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNegative() );
+  CPPUNIT_ASSERT_EQUAL( true, m->IsNonNegative() );
+
+  // is positive
+  m->SetAll(0.5);
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNull() );
+  CPPUNIT_ASSERT_EQUAL( true, m->IsPositive() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNegative() );
+  CPPUNIT_ASSERT_EQUAL( true, m->IsNonNegative() );
+
+  // is negative
+  m->SetAll(-0.1);
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNull() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsPositive() );
+  CPPUNIT_ASSERT_EQUAL( true, m->IsNegative() );
+  CPPUNIT_ASSERT_EQUAL( false, m->IsNonNegative() );
+
+  // is positive definite
+  CPPUNIT_ASSERT_EQUAL( false, m->IsPositiveDefinite() );
+};
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
Index: src/unittests/gslmatrixunittest.hpp
===================================================================
--- src/unittests/gslmatrixunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/gslmatrixunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,42 @@
+/*
+ * gslmatrixunittest.hpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+#ifndef GSLMATRIXUNITTEST_HPP_
+#define GSLMATRIXUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "gslmatrix.hpp"
+
+/********************************************** Test classes **************************************/
+
+class GSLMatrixTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( GSLMatrixTest) ;
+    CPPUNIT_TEST (AccessTest );
+    CPPUNIT_TEST (InitializationTest );
+    CPPUNIT_TEST (CopyTest );
+    CPPUNIT_TEST (ExchangeTest );
+    CPPUNIT_TEST (PropertiesTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+    void setUp();
+    void tearDown();
+
+    void AccessTest();
+    void InitializationTest();
+    void CopyTest();
+    void ExchangeTest();
+    void PropertiesTest();
+
+private:
+    GSLMatrix *m;
+};
+
+
+#endif /* GSLMATRIXUNITTEST_HPP_ */
Index: src/unittests/gslvectorunittest.cpp
===================================================================
--- src/unittests/gslvectorunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/gslvectorunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,182 @@
+/*
+ * gslvectorunittest.cpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+using namespace std;
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include "gslvectorunittest.hpp"
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( GSLVectorTest );
+
+
+void GSLVectorTest::setUp()
+{
+  v = new GSLVector(3);
+};
+
+void GSLVectorTest::tearDown()
+{
+  delete(v);
+};
+
+/** Unit test for accessing elements in the vector.
+ *
+ */
+void GSLVectorTest::AccessTest()
+{
+  // set
+  for (int i=0;i<3;i++)
+    v->Set(i,i);
+
+  // and check
+  double *ptr = NULL;
+  for (int i=0;i<3;i++) {
+    CPPUNIT_ASSERT_EQUAL( (double)i, v->Get(i) );
+    ptr = v->Pointer(i);
+    CPPUNIT_ASSERT_EQUAL( (double)i, *ptr );
+  }
+
+  // out of bounds
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(3) );
+  //CPPUNIT_ASSERT_EQUAL(0., v->Get(-1) );
+};
+
+
+/** Unit test for initializing the vector.
+ *
+ */
+void GSLVectorTest::InitializaionTest()
+{
+  // set zero
+  v->SetZero();
+  for (int i=0;i<3;i++)
+    CPPUNIT_ASSERT_EQUAL( 0., v->Get(i) );
+
+  // set basis
+  for (int i=0;i<3;i++) {
+    v->SetBasis(i);
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( i == j ? 1. : 0. , v->Get(j) );
+  }
+
+  // set all
+  v->SetAll(1.5);
+  for (int i=0;i<3;i++)
+    CPPUNIT_ASSERT_EQUAL( 1.5, v->Get(i) );
+};
+
+/** Unit test for copying vectors.
+ *
+ */
+void GSLVectorTest::CopyTest()
+{
+  // set basis
+  GSLVector *dest = NULL;
+  for (int i=0;i<3;i++) {
+    v->SetBasis(i);
+    dest = new GSLVector(v);
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( v->Get(j) , dest->Get(j) );
+
+    delete(dest);
+  }
+};
+
+/** Unit test for exchanging elements of a vector.
+ *
+ */
+void GSLVectorTest::ExchangeTest()
+{
+  // set basis
+  for (int i=0;i<3;i++) {
+    v->SetBasis(i);
+    v->SwapElements((i)%3,(i+1)%3);
+    for (int j=0;j<3;j++)
+      CPPUNIT_ASSERT_EQUAL( (i+1)%3 == j ? 1. : 0. , v->Get(j) );
+  }
+
+  // set to 1,2,3 and reverse
+  for (int i=0;i<3;i++)
+    v->Set(i,i+1);
+  v->Reverse();
+  for (int j=0;j<3;j++)
+    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() );
+};
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
Index: src/unittests/gslvectorunittest.hpp
===================================================================
--- src/unittests/gslvectorunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/gslvectorunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,45 @@
+/*
+ * gslvectorunittest.hpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+#ifndef GSLVECTORUNITTEST_HPP_
+#define GSLVECTORUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "gslvector.hpp"
+
+/********************************************** Test classes **************************************/
+
+class GSLVectorTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( GSLVectorTest) ;
+    CPPUNIT_TEST (AccessTest );
+    CPPUNIT_TEST (InitializaionTest );
+    CPPUNIT_TEST (CopyTest );
+    CPPUNIT_TEST (ExchangeTest );
+    CPPUNIT_TEST (OperatorAlgebraTest );
+    CPPUNIT_TEST (OperatorIsTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+    void setUp();
+    void tearDown();
+
+    void AccessTest();
+    void InitializaionTest();
+    void CopyTest();
+    void ExchangeTest();
+    void OperatorIsTest();
+    void OperatorAlgebraTest();
+
+private:
+
+    GSLVector *v;
+};
+
+
+#endif /* GSLVECTORUNITTEST_HPP_ */
Index: src/unittests/infounittest.cpp
===================================================================
--- src/unittests/infounittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/infounittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,66 @@
+/*
+ * InfoUnitTest.cpp
+ *
+ *  Created on: Nov 25, 2009
+ *      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 "info.hpp"
+#include "infounittest.hpp"
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( InfoTest );
+
+
+void InfoTest::setUp()
+{
+};
+
+
+void InfoTest::tearDown()
+{
+};
+
+/** UnitTest for FunctionTest().
+ */
+void InfoTest::FunctionTest()
+{
+  const char *msg = __func__;
+  class Info test(msg);
+
+  CPPUNIT_ASSERT_EQUAL( msg , test.FunctionName );
+  CPPUNIT_ASSERT_EQUAL( 1, test.verbosity );
+};
+
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
Index: src/unittests/infounittest.hpp
===================================================================
--- src/unittests/infounittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/infounittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,32 @@
+/*
+ * InfoUnitTest.hpp
+ *
+ *  Created on: Nov 25, 2009
+ *      Author: heber
+ */
+
+#ifndef INFOUNITTEST_HPP_
+#define INFOUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+class info;
+
+/********************************************** Test classes **************************************/
+
+class InfoTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( InfoTest) ;
+    CPPUNIT_TEST ( FunctionTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+      void setUp();
+      void tearDown();
+      void FunctionTest();
+
+private:
+
+};
+
+#endif /* INFOUNITTEST_HPP_ */
Index: src/unittests/linearsystemofequationsunittest.cpp
===================================================================
--- src/unittests/linearsystemofequationsunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/linearsystemofequationsunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,125 @@
+/*
+ * linearsystemofequationsunittest.cpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+using namespace std;
+
+#include <iomanip>
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include "linearsystemofequationsunittest.hpp"
+#include "vector.hpp"
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( LinearSystemOfEquationsTest );
+
+
+void LinearSystemOfEquationsTest::setUp()
+{
+  s = new LinearSystemOfEquations(4,4);
+};
+
+void LinearSystemOfEquationsTest::tearDown()
+{
+  delete(s);
+};
+
+/** Unit test for initialization.
+ *
+ */
+void LinearSystemOfEquationsTest::InitializationTest()
+{
+  // Setting A
+  double array[] = { 1., 0., 0., 0.,
+                     0., 2., 0., 0.,
+                     0., 0., 3., 0.,
+                     0., 0., 0., 4. };
+  s->SetA(array);
+
+  // Setting b
+};
+
+/** Unit test for symmetry property.
+ *
+ */
+void LinearSystemOfEquationsTest::SymmetricTest()
+{
+  CPPUNIT_ASSERT_EQUAL( true, s->SetSymmetric(true) );
+  //LinearSystemOfEquations *t = new LinearSystemOfEquations(4,3);
+  //CPPUNIT_ASSERT_EQUAL( true, t->SetSymmetric(true) );
+  //delete(t);
+};
+
+/** Unit test for simple Solve.
+ *
+ */
+void LinearSystemOfEquationsTest::SolveSimpleTest()
+{
+  // set up A and b
+  double m_array[] = { 1., 0., 0., 0.,
+                       0., 2., 0., 0.,
+                       0., 0., 3., 0.,
+                       0., 0., 0., 4. };
+  double v_array[] = { 1., 2., 3., 4. };
+  s->SetA(m_array);
+  s->Setb(v_array);
+
+  // solve
+  double *array = new double[4];
+  s->GetSolutionAsArray(array);
+  for (int i=0;i<4;i++)
+    CPPUNIT_ASSERT_EQUAL( 1., array[i]);
+  delete[](array);
+};
+
+/** Unit test for advanced Solve.
+ *
+ */
+void LinearSystemOfEquationsTest::SolveAdvancedTest()
+{
+  // set up A and b
+  double m_array[] = { 0.18, 0.60, 0.57, 0.96,
+                       0.41, 0.24, 0.99, 0.58,
+                       0.14, 0.30, 0.97, 0.66,
+                       0.51, 0.13, 0.19, 0.85 };
+  double v_array[] = { 1.0, 2.0, 3.0, 4.0 };
+  double x_array[] = { -4.05205022957398, -12.60561139590692, 1.660911626708844, 8.693766928795233 };
+  s->SetA(m_array);
+  s->Setb(v_array);
+
+  // solve
+  double *array = new double[4];
+  s->GetSolutionAsArray(array);
+  for (int i=0;i<4;i++) {
+    CPPUNIT_ASSERT( fabs(x_array[i] - array[i]) < MYEPSILON );
+  }
+  delete[](array);
+};
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
Index: src/unittests/linearsystemofequationsunittest.hpp
===================================================================
--- src/unittests/linearsystemofequationsunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/linearsystemofequationsunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,40 @@
+/*
+ * linearsystemofequationsunittest.hpp
+ *
+ *  Created on: Jan 8, 2010
+ *      Author: heber
+ */
+
+#ifndef LINEARSYSTEMOFEQUATIONSUNITTEST_HPP_
+#define LINEARSYSTEMOFEQUATIONSUNITTEST_HPP_
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "linearsystemofequations.hpp"
+
+/********************************************** Test classes **************************************/
+
+class LinearSystemOfEquationsTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( LinearSystemOfEquationsTest) ;
+    CPPUNIT_TEST ( InitializationTest );
+    CPPUNIT_TEST ( SymmetricTest );
+    CPPUNIT_TEST ( SolveSimpleTest );
+    CPPUNIT_TEST ( SolveAdvancedTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+    void setUp();
+    void tearDown();
+
+    void InitializationTest();
+    void SymmetricTest();
+    void SolveSimpleTest();
+    void SolveAdvancedTest();
+
+private:
+    LinearSystemOfEquations *s;
+};
+
+
+#endif /* LINEARSYSTEMOFEQUATIONSUNITTEST_HPP_ */
Index: src/unittests/listofbondsunittest.cpp
===================================================================
--- src/unittests/listofbondsunittest.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/listofbondsunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -11,4 +11,6 @@
 #include <cppunit/extensions/TestFactoryRegistry.h>
 #include <cppunit/ui/text/TestRunner.h>
+
+#include <cstring>
 
 #include "listofbondsunittest.hpp"
Index: src/unittests/logunittest.cpp
===================================================================
--- src/unittests/logunittest.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/logunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -35,16 +35,16 @@
 {
   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;
+  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/memoryallocatorunittest.cpp
===================================================================
--- src/unittests/memoryallocatorunittest.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/memoryallocatorunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -46,5 +46,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/tesselation_boundarytriangleunittest.cpp
===================================================================
--- src/unittests/tesselation_boundarytriangleunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/tesselation_boundarytriangleunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,214 @@
+/*
+ * tesselation_boundarytriangleunittest.cpp
+ *
+ *  Created on: Jan 13, 2010
+ *      Author: heber
+ */
+
+using namespace std;
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include <cstring>
+
+#include "defs.hpp"
+#include "tesselation.hpp"
+#include "tesselation_boundarytriangleunittest.hpp"
+
+#define SPHERERADIUS 2.
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( TesselationBoundaryTriangleTest );
+
+
+void TesselationBoundaryTriangleTest::setUp()
+{
+  setVerbosity(5);
+
+  // 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);
+
+  // create line
+  lines[0] = new BoundaryLineSet(points[0], points[1], 0);
+  lines[1] = new BoundaryLineSet(points[1], points[2], 1);
+  lines[2] = new BoundaryLineSet(points[0], points[2], 2);
+
+  // create triangle
+  triangle = new BoundaryTriangleSet(lines, 0);
+  triangle->GetNormalVector(Vector(0.,0.,1.));
+};
+
+
+void TesselationBoundaryTriangleTest::tearDown()
+{
+  delete(triangle);
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
+  errorLogger::purgeInstance();
+};
+
+/** UnitTest for Tesselation::IsInnerPoint()
+ */
+void TesselationBoundaryTriangleTest::GetClosestPointOnPlaneTest()
+{
+  Vector TestIntersection;
+  Vector Point;
+
+  // 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.);
+  CPPUNIT_ASSERT_EQUAL( 16., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(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.);
+  CPPUNIT_ASSERT_EQUAL( 36., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(0.5,0.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+
+  // simple test on slanted line
+  Point.Init(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.);
+  CPPUNIT_ASSERT_EQUAL( 40.5, triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(0.5,0.5,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+
+  // simple test on first node
+  Point.Init(-1.,-1.,0.);
+  CPPUNIT_ASSERT_EQUAL( 2., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(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.);
+  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.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+};
+
+/** UnitTest for Tesselation::IsInnerPoint()
+ */
+void TesselationBoundaryTriangleTest::GetClosestPointOffPlaneTest()
+{
+  Vector TestIntersection;
+  Vector Point;
+
+  // straight down/up
+  Point.Init(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.);
+  CPPUNIT_ASSERT_EQUAL( 25. , triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(1./3.,1./3.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+
+  // simple test on y line
+  Point.Init(-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.);
+  CPPUNIT_ASSERT_EQUAL( 10., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(0.,0.5,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+
+  // simple test on x line
+  Point.Init(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.);
+  CPPUNIT_ASSERT_EQUAL( 5., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(0.5,0.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+
+  // simple test on slanted line
+  Point.Init(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.);
+  CPPUNIT_ASSERT_EQUAL( 16.5, triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(0.5,0.5,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+
+  // simple test on first node
+  Point.Init(-1.,-1.,5.);
+  CPPUNIT_ASSERT_EQUAL( 27., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(0.,0.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+
+  // simple test on second node
+  Point.Init(0.,2.,5.);
+  CPPUNIT_ASSERT_EQUAL( 26., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(0.,1.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+
+  // simple test on third node
+  Point.Init(2.,0.,5.);
+  CPPUNIT_ASSERT_EQUAL( 26., triangle->GetClosestPointInsideTriangle(&Point, &TestIntersection) );
+  Point.Init(1.,0.,0.);
+  CPPUNIT_ASSERT_EQUAL( true , Point == TestIntersection );
+};
+
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
Index: src/unittests/tesselation_boundarytriangleunittest.hpp
===================================================================
--- src/unittests/tesselation_boundarytriangleunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/tesselation_boundarytriangleunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,41 @@
+/*
+ * tesselation_boundarytriangleunittest.hpp
+ *
+ *  Created on: Jan 13, 2010
+ *      Author: heber
+ */
+
+#ifndef TESSELATION_BOUNDARYTRIANGLEUNITTEST_HPP_
+#define TESSELATION_BOUNDARYTRIANGLEUNITTEST_HPP_
+
+/*********************************************** includes ***********************************/
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "linkedcell.hpp"
+#include "tesselation.hpp"
+
+/********************************************** Test classes **************************************/
+
+class TesselationBoundaryTriangleTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( TesselationBoundaryTriangleTest) ;
+    CPPUNIT_TEST ( GetClosestPointOnPlaneTest );
+    CPPUNIT_TEST ( GetClosestPointOffPlaneTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+      void setUp();
+      void tearDown();
+      void GetClosestPointOnPlaneTest();
+      void GetClosestPointOffPlaneTest();
+
+private:
+      class BoundaryTriangleSet *triangle;
+      class BoundaryLineSet *lines[3];
+      class BoundaryPointSet *points[3];
+      LinkedCell::LinkedNodes Corners;
+};
+
+
+#endif /* TESSELATION_BOUNDARYTRIANGLEUNITTEST_HPP_ */
Index: src/unittests/tesselation_insideoutsideunittest.cpp
===================================================================
--- src/unittests/tesselation_insideoutsideunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/tesselation_insideoutsideunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,183 @@
+/*
+ * tesselation_insideoutsideunittest.cpp
+ *
+ *  Created on: Dec 28, 2009
+ *      Author: heber
+ */
+
+using namespace std;
+
+#include <cppunit/CompilerOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
+
+#include <cstring>
+
+#include "defs.hpp"
+#include "tesselation.hpp"
+#include "tesselation_insideoutsideunittest.hpp"
+
+#define SPHERERADIUS 2.
+
+/********************************************** Test classes **************************************/
+
+// Registers the fixture into the 'registry'
+CPPUNIT_TEST_SUITE_REGISTRATION( TesselationInOutsideTest );
+
+
+void TesselationInOutsideTest::setUp()
+{
+  setVerbosity(2);
+
+  // create corners
+  class TesselPoint *Walker;
+  Walker = new TesselPoint;
+  Walker->node = new Vector(0., 0., 0.);
+  Walker->Name = Malloc<char>(3, "TesselationInOutsideTest::setUp - *Name");
+  strcpy(Walker->Name, "1");
+  Walker->nr = 1;
+  Corners.push_back(Walker);
+  Walker = new TesselPoint;
+  Walker->node = new Vector(0., 1., 0.);
+  Walker->Name = Malloc<char>(3, "TesselationInOutsideTest::setUp - *Name");
+  strcpy(Walker->Name, "2");
+  Walker->nr = 2;
+  Corners.push_back(Walker);
+  Walker = new TesselPoint;
+  Walker->node = new Vector(1., 0., 0.);
+  Walker->Name = Malloc<char>(3, "TesselationInOutsideTest::setUp - *Name");
+  strcpy(Walker->Name, "3");
+  Walker->nr = 3;
+  Corners.push_back(Walker);
+  Walker = new TesselPoint;
+  Walker->node = new Vector(1., 1., 0.);
+  Walker->Name = Malloc<char>(3, "TesselationInOutsideTest::setUp - *Name");
+  strcpy(Walker->Name, "4");
+  Walker->nr = 4;
+  Corners.push_back(Walker);
+  Walker = new TesselPoint;
+  Walker->node = new Vector(0., 0., 1.);
+  Walker->Name = Malloc<char>(3, "TesselationInOutsideTest::setUp - *Name");
+  strcpy(Walker->Name, "5");
+  Walker->nr = 5;
+  Corners.push_back(Walker);
+  Walker = new TesselPoint;
+  Walker->node = new Vector(0., 1., 1.);
+  Walker->Name = Malloc<char>(3, "TesselationInOutsideTest::setUp - *Name");
+  strcpy(Walker->Name, "6");
+  Walker->nr = 6;
+  Corners.push_back(Walker);
+  Walker = new TesselPoint;
+  Walker->node = new Vector(1., 0., 1.);
+  Walker->Name = Malloc<char>(3, "TesselationInOutsideTest::setUp - *Name");
+  strcpy(Walker->Name, "7");
+  Walker->nr = 7;
+  Corners.push_back(Walker);
+  Walker = new TesselPoint;
+  Walker->node = new Vector(1., 1., 1.);
+  Walker->Name = Malloc<char>(3, "TesselationInOutsideTest::setUp - *Name");
+  strcpy(Walker->Name, "8");
+  Walker->nr = 8;
+  Corners.push_back(Walker);
+
+  // create linkedcell
+  LinkedList = new LinkedCell(&Corners, 2.*SPHERERADIUS);
+
+  // create tesselation
+  TesselStruct = new Tesselation;
+  TesselStruct->FindStartingTriangle(SPHERERADIUS, LinkedList);
+
+  CandidateForTesselation *baseline = NULL;
+  BoundaryTriangleSet *T = NULL;
+  bool OneLoopWithoutSuccessFlag = true;
+  bool TesselationFailFlag = false;
+  while ((!TesselStruct->OpenLines.empty()) && (OneLoopWithoutSuccessFlag)) {
+    // 2a. fill all new OpenLines
+    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++)
+      DoLog(2) && (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);
+        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.
+      }
+    }
+
+    // 2b. search for smallest ShortestAngle among all candidates
+    double ShortestAngle = 4.*M_PI;
+    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(2) && (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;
+      }
+    }
+    if ((ShortestAngle == 4.*M_PI) || (baseline->pointlist.empty()))
+      OneLoopWithoutSuccessFlag = false;
+    else {
+      TesselStruct->AddCandidatePolygon(*baseline, SPHERERADIUS, LinkedList);
+    }
+  }
+};
+
+
+void TesselationInOutsideTest::tearDown()
+{
+  delete(LinkedList);
+  delete(TesselStruct);
+  for (LinkedCell::LinkedNodes::iterator Runner = Corners.begin(); Runner != Corners.end(); Runner++) {
+    delete((*Runner)->node);
+    delete(*Runner);
+  }
+  Corners.clear();
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
+  errorLogger::purgeInstance();
+};
+
+/** UnitTest for Tesselation::IsInnerPoint()
+ */
+void TesselationInOutsideTest::IsInnerPointTest()
+{
+  double n[3];
+  const double boundary = 2.;
+  const double step = 1.;
+
+  // go through the mesh and check each point
+  for (n[0] = -boundary; n[0] <= boundary; n[0]+=step)
+    for (n[1] = -boundary; n[1] <= boundary; n[1]+=step)
+      for (n[2] = -boundary; n[2] <= boundary; n[2]+=step) {
+        if ( ((n[0] >= 0.) && (n[1] >= 0.) && (n[2] >= 0.)) && ((n[0] <= 1.) && (n[1] <= 1.) && (n[2] <= 1.)))
+          CPPUNIT_ASSERT_EQUAL( true , TesselStruct->IsInnerPoint(Vector(n[0], n[1], n[2]), LinkedList) );
+        else
+          CPPUNIT_ASSERT_EQUAL( false , TesselStruct->IsInnerPoint(Vector(n[0], n[1], n[2]), LinkedList) );
+      }
+};
+
+/********************************************** Main routine **************************************/
+
+int main(int argc, char **argv)
+{
+  // Get the top level suite from the registry
+  CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
+
+  // Adds the test to the list of test to run
+  CppUnit::TextUi::TestRunner runner;
+  runner.addTest( suite );
+
+  // Change the default outputter to a compiler error format outputter
+  runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
+                                                       std::cerr ) );
+  // Run the tests.
+  bool wasSucessful = runner.run();
+
+  // Return error code 1 if the one of test failed.
+  return wasSucessful ? 0 : 1;
+};
Index: src/unittests/tesselation_insideoutsideunittest.hpp
===================================================================
--- src/unittests/tesselation_insideoutsideunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/unittests/tesselation_insideoutsideunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,38 @@
+/*
+ * tesselation_insideoutsideunittest.hpp
+ *
+ *  Created on: Dec 28, 2009
+ *      Author: heber
+ */
+
+#ifndef TESSELATION_INSIDEOUTSIDEUNITTEST_HPP_
+#define TESSELATION_INSIDEOUTSIDEUNITTEST_HPP_
+
+/*********************************************** includes ***********************************/
+
+#include <cppunit/extensions/HelperMacros.h>
+
+#include "linkedcell.hpp"
+#include "tesselation.hpp"
+
+/********************************************** Test classes **************************************/
+
+class TesselationInOutsideTest : public CppUnit::TestFixture
+{
+    CPPUNIT_TEST_SUITE( TesselationInOutsideTest) ;
+    CPPUNIT_TEST ( IsInnerPointTest );
+    CPPUNIT_TEST_SUITE_END();
+
+public:
+      void setUp();
+      void tearDown();
+      void IsInnerPointTest();
+
+private:
+      class Tesselation *TesselStruct;
+      LinkedCell::LinkedNodes Corners;
+      class LinkedCell *LinkedList;
+};
+
+
+#endif /* TESSELATION_INSIDEOUTSIDEUNITTEST_HPP_ */
Index: src/unittests/tesselationunittest.cpp
===================================================================
--- src/unittests/tesselationunittest.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/tesselationunittest.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -12,4 +12,6 @@
 #include <cppunit/extensions/TestFactoryRegistry.h>
 #include <cppunit/ui/text/TestRunner.h>
+
+#include <cstring>
 
 #include "defs.hpp"
@@ -30,18 +32,18 @@
   class TesselPoint *Walker;
   Walker = new TesselPoint;
-  Walker->node = new Vector(1., 0., 0.);
-  Walker->Name = new char[3];
+  Walker->node = new Vector(1., 0., -1.);
+  Walker->Name = Malloc<char>(3, "TesselationTest::setUp");
   strcpy(Walker->Name, "1");
   Walker->nr = 1;
   Corners.push_back(Walker);
   Walker = new TesselPoint;
-  Walker->node = new Vector(-1., 1., 0.);
-  Walker->Name = new char[3];
+  Walker->node = new Vector(-1., 1., -1.);
+  Walker->Name = Malloc<char>(3, "TesselationTest::setUp");
   strcpy(Walker->Name, "2");
   Walker->nr = 2;
   Corners.push_back(Walker);
   Walker = new TesselPoint;
-  Walker->node = new Vector(-1., -1., 0.);
-  Walker->Name = new char[3];
+  Walker->node = new Vector(-1., -1., -1.);
+  Walker->Name = Malloc<char>(3, "TesselationTest::setUp");
   strcpy(Walker->Name, "3");
   Walker->nr = 3;
@@ -49,5 +51,5 @@
   Walker = new TesselPoint;
   Walker->node = new Vector(-1., 0., 1.);
-  Walker->Name = new char[3];
+  Walker->Name = Malloc<char>(3, "TesselationTest::setUp");
   strcpy(Walker->Name, "4");
   Walker->nr = 4;
@@ -59,19 +61,35 @@
   // create tesselation
   TesselStruct = new Tesselation;
-  TesselStruct->PointsOnBoundary.clear();
-  TesselStruct->LinesOnBoundary.clear();
-  TesselStruct->TrianglesOnBoundary.clear();
+  CPPUNIT_ASSERT_EQUAL( true, TesselStruct->PointsOnBoundary.empty() );
+  CPPUNIT_ASSERT_EQUAL( true, TesselStruct->LinesOnBoundary.empty() );
+  CPPUNIT_ASSERT_EQUAL( true, TesselStruct->TrianglesOnBoundary.empty() );
   TesselStruct->FindStartingTriangle(SPHERERADIUS, LinkedList);
-  bool flag = false;
 
-  LineMap::iterator baseline = TesselStruct->LinesOnBoundary.begin();
-  while (baseline != TesselStruct->LinesOnBoundary.end()) {
-    if (baseline->second->triangles.size() == 1) {
-      flag = TesselStruct->FindNextSuitableTriangle(*(baseline->second), *(((baseline->second->triangles.begin()))->second), SPHERERADIUS, LinkedList); //the line is there, so there is a triangle, but only one.
+  CandidateForTesselation *baseline = NULL;
+  BoundaryTriangleSet *T = NULL;
+  bool OneLoopWithoutSuccessFlag = true;
+  bool TesselationFailFlag = false;
+  while ((!TesselStruct->OpenLines.empty()) && (OneLoopWithoutSuccessFlag)) {
+    // 2a. fill all new OpenLines
+    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);
+        TesselationFailFlag = TesselStruct->FindNextSuitableTriangle(*baseline, *T, SPHERERADIUS, LinkedList); //the line is there, so there is a triangle, but only one.
+      }
     }
-    baseline++;
-    if ((baseline == TesselStruct->LinesOnBoundary.end()) && (flag)) {
-      baseline = TesselStruct->LinesOnBoundary.begin();   // restart if we reach end due to newly inserted lines
-      flag = false;
+
+    // 2b. search for smallest ShortestAngle among all candidates
+    double ShortestAngle = 4.*M_PI;
+    for (CandidateMap::iterator Runner = TesselStruct->OpenLines.begin(); Runner != TesselStruct->OpenLines.end(); Runner++) {
+      if (Runner->second->ShortestAngle < ShortestAngle) {
+        baseline = Runner->second;
+        ShortestAngle = baseline->ShortestAngle;
+      }
+    }
+    if ((ShortestAngle == 4.*M_PI) || (baseline->pointlist.empty()))
+      OneLoopWithoutSuccessFlag = false;
+    else {
+      TesselStruct->AddCandidatePolygon(*baseline, SPHERERADIUS, LinkedList);
     }
   }
@@ -83,34 +101,12 @@
   delete(LinkedList);
   delete(TesselStruct);
-  for (LinkedNodes::iterator Runner = Corners.begin(); Runner != Corners.end(); Runner++) {
-    delete[]((*Runner)->Name);
+  for (LinkedCell::LinkedNodes::iterator Runner = Corners.begin(); Runner != Corners.end(); Runner++) {
     delete((*Runner)->node);
     delete(*Runner);
   }
   Corners.clear();
-};
-
-/** UnitTest for Tesselation::IsInnerPoint()
- */
-void TesselationTest::IsInnerPointTest()
-{
-  // true inside points
-  CPPUNIT_ASSERT_EQUAL( true, TesselStruct->IsInnerPoint(Vector(0.,0.,0.), LinkedList) );
-  CPPUNIT_ASSERT_EQUAL( true, TesselStruct->IsInnerPoint(Vector(0.5,0.,0.), LinkedList) );
-  CPPUNIT_ASSERT_EQUAL( true, TesselStruct->IsInnerPoint(Vector(0.,0.5,0.), LinkedList) );
-  CPPUNIT_ASSERT_EQUAL( true, TesselStruct->IsInnerPoint(Vector(0.,0.,0.5), LinkedList) );
-
-  // corners
-  for (LinkedNodes::iterator Runner = Corners.begin(); Runner != Corners.end(); Runner++)
-    CPPUNIT_ASSERT_EQUAL( true, TesselStruct->IsInnerPoint((*Runner), LinkedList) );
-
-  // true outside points
-  CPPUNIT_ASSERT_EQUAL( false, TesselStruct->IsInnerPoint(Vector(0.,5.,0.), LinkedList) );
-  CPPUNIT_ASSERT_EQUAL( false, TesselStruct->IsInnerPoint(Vector(0.,0.,5.), LinkedList) );
-  CPPUNIT_ASSERT_EQUAL( false, TesselStruct->IsInnerPoint(Vector(1.,1.,1.), LinkedList) );
-
-  // tricky point, there are three equally close triangles
-  CPPUNIT_ASSERT_EQUAL( false, TesselStruct->IsInnerPoint(Vector(5.,0.,0.), LinkedList) );
-
+  MemoryUsageObserver::purgeInstance();
+  logger::purgeInstance();
+  errorLogger::purgeInstance();
 };
 
Index: src/unittests/tesselationunittest.hpp
===================================================================
--- src/unittests/tesselationunittest.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/unittests/tesselationunittest.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -21,5 +21,4 @@
 {
     CPPUNIT_TEST_SUITE( TesselationTest) ;
-    CPPUNIT_TEST ( IsInnerPointTest );
     CPPUNIT_TEST ( GetAllTrianglesTest );
     CPPUNIT_TEST ( ContainmentTest );
@@ -29,5 +28,4 @@
       void setUp();
       void tearDown();
-      void IsInnerPointTest();
       void GetAllTrianglesTest();
       void ContainmentTest();
@@ -36,5 +34,5 @@
 private:
       class Tesselation *TesselStruct;
-      LinkedNodes Corners;
+      LinkedCell::LinkedNodes Corners;
       class LinkedCell *LinkedList;
 };
Index: src/vector.cpp
===================================================================
--- src/vector.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/vector.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -8,9 +8,17 @@
 #include "defs.hpp"
 #include "helpers.hpp"
-#include "memoryallocator.hpp"
+#include "info.hpp"
+#include "gslmatrix.hpp"
 #include "leastsquaremin.hpp"
 #include "log.hpp"
+#include "memoryallocator.hpp"
 #include "vector.hpp"
 #include "verbose.hpp"
+#include "World.hpp"
+
+#include <gsl/gsl_linalg.h>
+#include <gsl/gsl_matrix.h>
+#include <gsl/gsl_permutation.h>
+#include <gsl/gsl_vector.h>
 
 /************************************ Functions for class vector ************************************/
@@ -19,4 +27,22 @@
  */
 Vector::Vector() { x[0] = x[1] = x[2] = 0.; };
+
+/** Constructor of class vector.
+ */
+Vector::Vector(const Vector * const a)
+{
+  x[0] = a->x[0];
+  x[1] = a->x[1];
+  x[2] = a->x[2];
+};
+
+/** Constructor of class vector.
+ */
+Vector::Vector(const Vector &a)
+{
+  x[0] = a.x[0];
+  x[1] = a.x[1];
+  x[2] = a.x[2];
+};
 
 /** Constructor of class vector.
@@ -215,8 +241,9 @@
  * \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
+ * \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;
@@ -226,8 +253,9 @@
   Direction.SubtractVector(Origin);
   Direction.Normalize();
-  //Log() << Verbose(4) << "INFO: Direction is " << Direction << "." << endl;
+  DoLog(1) && (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 (factor < MYEPSILON) { // Uniqueness: line parallel to plane?
-    Log() << Verbose(2) << "WARNING: Line is parallel to plane, no intersection." << endl;
+  if (fabs(factor) < MYEPSILON) { // Uniqueness: line parallel to plane?
+    DoLog(1) && (Log() << Verbose(1) << "BAD: Line is parallel to plane, no intersection." << endl);
     return false;
   }
@@ -235,6 +263,6 @@
   helper.SubtractVector(Origin);
   factor = helper.ScalarProduct(PlaneNormal)/factor;
-  if (factor < MYEPSILON) { // Origin is in-plane
-    //Log() << Verbose(2) << "Origin of line is in-plane, simple." << endl;
+  if (fabs(factor) < MYEPSILON) { // Origin is in-plane
+    DoLog(1) && (Log() << Verbose(1) << "GOOD: Origin of line is in-plane." << endl);
     CopyVector(Origin);
     return true;
@@ -243,5 +271,5 @@
   Direction.Scale(factor);
   CopyVector(Origin);
-  //Log() << Verbose(4) << "INFO: Scaled direction is " << Direction << "." << endl;
+  DoLog(1) && (Log() << Verbose(1) << "INFO: Scaled direction is " << Direction << "." << endl);
   AddVector(&Direction);
 
@@ -250,19 +278,19 @@
   helper.SubtractVector(PlaneOffset);
   if (helper.ScalarProduct(PlaneNormal) < MYEPSILON) {
-    //Log() << Verbose(2) << "INFO: Intersection at " << *this << " is good." << endl;
+    DoLog(1) && (Log() << Verbose(1) << "GOOD: Intersection is " << *this << "." << endl);
     return true;
   } else {
-    Log() << Verbose(2) << "WARNING: Intersection point " << *this << " is not on plane." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "Intersection point " << *this << " is not on plane." << endl);
     return false;
   }
 };
 
-/** Calculates the minimum distance of this vector to the plane.
+/** 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
+ * \return distance vector onto to plane
+ */
+Vector Vector::GetDistanceVectorToPlane(const Vector * const PlaneNormal, const Vector * const PlaneOffset) const
 {
   Vector temp;
@@ -282,11 +310,23 @@
     sign = 0.;
 
-  return (temp.Norm()*sign);
+  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 *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
+{
+  return GetDistanceVectorToPlane(PlaneNormal,PlaneOffset).Norm();
 };
 
 /** Calculates the intersection of the two lines that are both on the same plane.
- * We construct auxiliary plane with its vector normal to one line direction and the PlaneNormal, then a vector
- * from the first line's offset onto the plane. Finally, scale by factor is 1/cos(angle(line1,line2..)) = 1/SP(...), and
- * project onto the first line's direction and add its offset.
+ * 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
@@ -299,80 +339,97 @@
 bool Vector::GetIntersectionOfTwoLinesOnPlane(const Vector * const Line1a, const Vector * const Line1b, const Vector * const Line2a, const Vector * const Line2b, const Vector *PlaneNormal)
 {
-  bool result = true;
-  Vector Direction, OtherDirection;
-  Vector AuxiliaryNormal;
-  Vector Distance;
-  const Vector *Normal = NULL;
-  Vector *ConstructedNormal = NULL;
-  bool FreeNormal = false;
-
-  // construct both direction vectors
-  Zero();
-  Direction.CopyVector(Line1b);
-  Direction.SubtractVector(Line1a);
-  if (Direction.IsZero())
+  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;
+  //ostream &output = Log() << Verbose(1);
+  //for (int i=0;i<4;i++) {
+  //  for (int j=0;j<4;j++)
+  //    output << "\t" << M->Get(i,j);
+  //  output << endl;
+  //}
+  if (fabs(M->Determinant()) > MYEPSILON) {
+    DoLog(1) && (Log() << Verbose(1) << "Determinant of coefficient matrix is NOT zero." << endl);
     return false;
-  OtherDirection.CopyVector(Line2b);
-  OtherDirection.SubtractVector(Line2a);
-  if (OtherDirection.IsZero())
+  }
+  DoLog(1) && (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);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: a = " << a << ", b = " << b << ", c = " << c << "." << endl);
+  if ((a.NormSquared() < MYEPSILON) || (b.NormSquared() < MYEPSILON)) {
+   Zero();
+   DoLog(1) && (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);
+      DoLog(1) && (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);
+        DoLog(1) && (Log() << Verbose(1) << "Lines conincide." << endl);
+        return true;
+      }
+    }
+    DoLog(1) && (Log() << Verbose(1) << "Lines are parallel." << endl);
+    Zero();
     return false;
-
-  Direction.Normalize();
-  OtherDirection.Normalize();
-
-  //Log() << Verbose(4) << "INFO: Normalized Direction " << Direction << " and OtherDirection " << OtherDirection << "." << endl;
-
-  if (fabs(OtherDirection.ScalarProduct(&Direction) - 1.) < MYEPSILON) { // lines are parallel
-    if ((Line1a == Line2a) || (Line1a == Line2b))
-      CopyVector(Line1a);
-    else if ((Line1b == Line2b) || (Line1b == Line2b))
-        CopyVector(Line1b);
-    else
-      return false;
-    Log() << Verbose(4) << "INFO: Intersection is " << *this << "." << endl;
-    return true;
-  } else {
-    // check whether we have a plane normal vector
-    if (PlaneNormal == NULL) {
-      ConstructedNormal = new Vector;
-      ConstructedNormal->MakeNormalVector(&Direction, &OtherDirection);
-      Normal = ConstructedNormal;
-      FreeNormal = true;
-    } else
-      Normal = PlaneNormal;
-
-    AuxiliaryNormal.MakeNormalVector(&OtherDirection, Normal);
-    //Log() << Verbose(4) << "INFO: PlaneNormal is " << *Normal << " and AuxiliaryNormal " << AuxiliaryNormal << "." << endl;
-
-    Distance.CopyVector(Line2a);
-    Distance.SubtractVector(Line1a);
-    //Log() << Verbose(4) << "INFO: Distance is " << Distance << "." << endl;
-    if (Distance.IsZero()) {
-      // offsets are equal, match found
-      CopyVector(Line1a);
-      result = true;
-    } else {
-      CopyVector(Distance.Projection(&AuxiliaryNormal));
-      //Log() << Verbose(4) << "INFO: Projected Distance is " << *this << "." << endl;
-      double factor = Direction.ScalarProduct(&AuxiliaryNormal);
-      //Log() << Verbose(4) << "INFO: Scaling factor is " << factor << "." << endl;
-      Scale(1./(factor*factor));
-      //Log() << Verbose(4) << "INFO: Scaled Distance is " << *this << "." << endl;
-      CopyVector(Projection(&Direction));
-      //Log() << Verbose(4) << "INFO: Distance, projected into Direction, is " << *this << "." << endl;
-      if (this->IsZero())
-        result = false;
-      else
-        result = true;
-      AddVector(Line1a);
-    }
-
-    if (FreeNormal)
-      delete(ConstructedNormal);
-  }
-  if (result)
-    Log() << Verbose(4) << "INFO: Intersection is " << *this << "." << endl;
-
-  return result;
+  }
+
+  // obtain s
+  double s;
+  Vector temp1, temp2;
+  temp1.CopyVector(&c);
+  temp1.VectorProduct(&b);
+  temp2.CopyVector(&a);
+  temp2.VectorProduct(&b);
+  DoLog(1) && (Log() << Verbose(1) << "INFO: temp1 = " << temp1 << ", temp2 = " << temp2 << "." << endl);
+  if (fabs(temp2.NormSquared()) > MYEPSILON)
+    s = temp1.ScalarProduct(&temp2)/temp2.NormSquared();
+  else
+    s = 0.;
+  DoLog(1) && (Log() << Verbose(1) << "Factor s is " << temp1.ScalarProduct(&temp2) << "/" << temp2.NormSquared() << " = " << s << "." << endl);
+
+  // construct intersection
+  CopyVector(&a);
+  Scale(s);
+  AddVector(Line1a);
+  DoLog(1) && (Log() << Verbose(1) << "Intersection is at " << *this << "." << endl);
+
+  return true;
 };
 
@@ -480,4 +537,17 @@
   else
     return false;
+};
+
+/** Checks whether vector is normal to \a *normal.
+ * @return true - vector is normalized, false - vector is not
+ */
+bool Vector::IsEqualTo(const Vector * const a) const
+{
+  bool status = true;
+  for (int i=0;i<NDIM;i++) {
+    if (fabs(x[i] - a->x[i]) > MYEPSILON)
+      status = false;
+  }
+  return status;
 };
 
@@ -632,11 +702,11 @@
 void Vector::Output() const
 {
-  Log() << Verbose(0) << "(";
+  DoLog(0) && (Log() << Verbose(0) << "(");
   for (int i=0;i<NDIM;i++) {
-    Log() << Verbose(0) << x[i];
+    DoLog(0) && (Log() << Verbose(0) << x[i]);
     if (i != 2)
-      Log() << Verbose(0) << ",";
-  }
-  Log() << Verbose(0) << ")";
+      DoLog(0) && (Log() << Verbose(0) << ",");
+  }
+  DoLog(0) && (Log() << Verbose(0) << ")");
 };
 
@@ -747,5 +817,5 @@
       x[i] = C.x[i];
   } else {
-    eLog() << Verbose(0) << "ERROR: inverse of matrix does not exists: det A = " << detA << "." << endl;
+    DoeLog(1) && (eLog()<< Verbose(1) << "inverse of matrix does not exists: det A = " << detA << "." << endl);
   }
 };
@@ -773,12 +843,12 @@
   projection = ScalarProduct(n)/n->ScalarProduct(n);    // remove constancy from n (keep as logical one)
   // withdraw projected vector twice from original one
-  Log() << Verbose(1) << "Vector: ";
+  DoLog(1) && (Log() << Verbose(1) << "Vector: ");
   Output();
-  Log() << Verbose(0) << "\t";
+  DoLog(0) && (Log() << Verbose(0) << "\t");
   for (int i=NDIM;i--;)
     x[i] -= 2.*projection*n->x[i];
-  Log() << Verbose(0) << "Projected vector: ";
+  DoLog(0) && (Log() << Verbose(0) << "Projected vector: ");
   Output();
-  Log() << Verbose(0) << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
 };
 
@@ -799,5 +869,5 @@
   x2.SubtractVector(y2);
   if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
-    Log() << Verbose(4) << "WARNING: Given vectors are linear dependent." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "Given vectors are linear dependent." << endl);
     return false;
   }
@@ -833,5 +903,5 @@
   Zero();
   if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
-    Log() << Verbose(4) << "WARNING: Given vectors are linear dependent." << endl;
+    DoeLog(2) && (eLog()<< Verbose(2) << "Given vectors are linear dependent." << endl);
     return false;
   }
@@ -884,7 +954,7 @@
   double norm;
 
-  Log() << Verbose(4);
+  DoLog(4) && (Log() << Verbose(4));
   GivenVector->Output();
-  Log() << Verbose(0) << endl;
+  DoLog(0) && (Log() << Verbose(0) << endl);
   for (j=NDIM;j--;)
     Components[j] = -1;
@@ -893,5 +963,5 @@
     if (fabs(GivenVector->x[j]) > MYEPSILON)
       Components[Last++] = j;
-  Log() << Verbose(4) << Last << " Components != 0: (" << Components[0] << "," << Components[1] << "," << Components[2] << ")" << endl;
+  DoLog(4) && (Log() << Verbose(4) << Last << " Components != 0: (" << Components[0] << "," << Components[1] << "," << Components[2] << ")" << endl);
 
   switch(Last) {
@@ -943,7 +1013,7 @@
 
   for (j=0;j<num;j++) {
-    Log() << Verbose(1) << j << "th atom's vector: ";
+    DoLog(1) && (Log() << Verbose(1) << j << "th atom's vector: ");
     (vectors[j])->Output();
-    Log() << Verbose(0) << endl;
+    DoLog(0) && (Log() << Verbose(0) << endl);
   }
 
@@ -1065,5 +1135,5 @@
     j += i+1;
     do {
-      Log() << Verbose(0) << coords[i] << "[0.." << cell_size[j] << "]: ";
+      DoLog(0) && (Log() << Verbose(0) << coords[i] << "[0.." << cell_size[j] << "]: ");
       cin >> x[i];
     } while (((x[i] < 0) || (x[i] >= cell_size[j])) && (check));
@@ -1096,5 +1166,5 @@
   B2 = cos(beta) * x2->Norm() * c;
   C = c * c;
-  Log() << Verbose(2) << "A " << A << "\tB " << B1 << "\tC " << C << endl;
+  DoLog(2) && (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
@@ -1135,27 +1205,27 @@
   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";
+  DoLog(2) && (Log() << Verbose(2) << "D1 " << D1 << "\tD2 " << D2 << "\tD3 " << D3 << "\n");
   if (fabs(D1) < MYEPSILON) {
-    Log() << Verbose(2) << "D1 == 0!\n";
+    DoLog(2) && (Log() << Verbose(2) << "D1 == 0!\n");
     if (fabs(D2) > MYEPSILON) {
-      Log() << Verbose(3) << "D2 != 0!\n";
+      DoLog(3) && (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";
+      DoLog(3) && (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";
+      DoLog(3) && (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";
+        DoLog(4) && (Log() << Verbose(4) << "F1 == 0!\n");
+        DoLog(4) && (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;
+        DoLog(4) && (Log() << Verbose(4) << "p " << p << "\tq " << q << endl);
         if (q < 0) {
-          Log() << Verbose(4) << "q < 0" << endl;
+          DoLog(4) && (Log() << Verbose(4) << "q < 0" << endl);
           return false;
         }
@@ -1164,5 +1234,5 @@
       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";
+      DoLog(2) && (Log() << Verbose(2) << "Gleichungssystem unterbestimmt\n");
       return false;
     }
@@ -1170,19 +1240,19 @@
     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";
+    DoLog(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";
+    DoLog(2) && (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";
+      DoLog(3) && (Log() << Verbose(3) << "F1 == 0!\n");
+      DoLog(3) && (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;
+      DoLog(3) && (Log() << Verbose(3) << "p " << p << "\tq " << q << endl);
       if (q < 0) {
-        Log() << Verbose(3) << "q < 0" << endl;
+        DoLog(3) && (Log() << Verbose(3) << "q < 0" << endl);
         return false;
       }
@@ -1222,8 +1292,8 @@
     for (j=2;j>=0;j--) {
       k = (i & pot(2,j)) << j;
-      Log() << Verbose(2) << "k " << k << "\tpot(2,j) " << pot(2,j) << endl;
+      DoLog(2) && (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";
+    DoLog(2) && (Log() << Verbose(2) << i << ": sign matrix is " << sign[0] << "\t" << sign[1] << "\t" << sign[2] << "\n");
     // apply sign matrix
     for (j=NDIM;j--;)
@@ -1231,5 +1301,5 @@
     // calculate angle and check
     ang = x2->Angle (this);
-    Log() << Verbose(1) << i << "th angle " << ang << "\tbeta " << cos(beta) << " :\t";
+    DoLog(1) && (Log() << Verbose(1) << i << "th angle " << ang << "\tbeta " << cos(beta) << " :\t");
     if (fabs(ang - cos(beta)) < MYEPSILON) {
       break;
Index: src/vector.hpp
===================================================================
--- src/vector.hpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/vector.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -27,4 +27,6 @@
 
   Vector();
+  Vector(const Vector * const a);
+  Vector(const Vector &a);
   Vector(const double x1, const double x2, const double x3);
   ~Vector();
@@ -42,4 +44,5 @@
   bool IsOne() const;
   bool IsNormalTo(const Vector * const normal) const;
+  bool IsEqualTo(const Vector * const a) const;
 
   void AddVector(const Vector * const y);
@@ -66,4 +69,5 @@
   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;
+  Vector GetDistanceVectorToPlane(const Vector * const PlaneNormal, const Vector * const PlaneOffset) 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);
Index: src/verbose.cpp
===================================================================
--- src/verbose.cpp	(revision 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/verbose.cpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -1,4 +1,5 @@
 using namespace std;
 
+#include "info.hpp"
 #include "verbose.hpp"
 
@@ -9,5 +10,5 @@
 ostream& Verbose::print (ostream &ost) const
 {
-  for (int i=Verbosity;i--;)
+  for (int i=Verbosity+Info::verbosity;i--;)
     ost.put('\t');
   //Log() << Verbose(0) << "Verbose(.) called." << endl;
@@ -16,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
@@ -22,7 +23,16 @@
 bool Verbose::DoOutput(int verbosityLevel) const
 {
+  return (verbosityLevel >= Verbosity+Info::verbosity);
+};
+
+/** 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 6056f1f6a543f7dbfa9dde0b7705d6820addf1c4)
+++ src/verbose.hpp	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -29,6 +29,13 @@
     Verbose(int value) : Verbosity(value) { }
 
+    // allow access to private variable Verbose::Verbosity
+    friend ostream& operator<<(class errorLogger& l, const Verbose& v);
+    friend ostream& operator<<(class errorLogger* l, const Verbose& v);
+    friend ostream& operator<<(class logger& l, const Verbose& v);
+    friend ostream& operator<<(class logger* l, const Verbose& v);
+
     ostream& print (ostream &ost) const;
     bool DoOutput(int verbosityLevel) const;
+    bool DoErrorOutput(int verbosityLevel) const;
   private:
     int Verbosity;
Index: src/version.h
===================================================================
--- src/version.h	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
+++ src/version.h	(revision 6cd16bc4b2635b48c1eb855a13b887a00af82259)
@@ -0,0 +1,6 @@
+#ifndef VERSION_H_
+#define VERSION_H_
+
+extern const char *ESPACKVersion;
+
+#endif /* VERSION_H_ */
