Index: molecuilder/src/Hbondangle.db
===================================================================
--- molecuilder/src/Hbondangle.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/Hbondangle.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,10 @@
+1	180	-1	-1
+5	180	131.0	109.2
+6	180	120	109.47
+7	180	110	106.67
+8	180	104.5	-1
+15	180	-1	-1
+16	180	-1	-1
+17	180 -1 -1
+34	180 -1 -1
+35	180 -1 -1
Index: molecuilder/src/Hbonddistance.db
===================================================================
--- molecuilder/src/Hbonddistance.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/Hbonddistance.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,11 @@
+1	0.74	-1	-1
+2	0.77429209	-1	-1
+5	1.23	1.19	1.18
+6	1.09	1.076	1.06
+7	1.04	1.02	1.01
+8	0.96	0.957	-1
+15	1.42	-1	-1
+16	1.35	-1	-1
+17	1.29	-1	-1
+34	1.47	-1	-1
+35	1.44	-1	-1
Index: molecuilder/src/Makefile.am
===================================================================
--- molecuilder/src/Makefile.am	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/Makefile.am	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,15 @@
+SOURCE = atom.cpp bond.cpp builder.cpp config.cpp element.cpp helpers.cpp molecules.cpp moleculelist.cpp periodentafel.cpp vector.cpp verbose.cpp
+HEADER = defs.hpp helpers.hpp molecules.hpp
+
+bin_PROGRAMS = molecuilder joiner analyzer
+molecuilderdir = ${bindir}
+molecuilder_DATA = elements.db valence.db	orbitals.db Hbonddistance.db Hbondangle.db
+molecuilder_SOURCES =  ${SOURCE} ${HEADER}
+joiner_SOURCES = joiner.cpp parser.cpp helpers.cpp verbose.cpp helpers.hpp parser.hpp
+analyzer_SOURCES = analyzer.cpp parser.cpp datacreator.cpp helpers.cpp verbose.cpp helpers.hpp parser.hpp datacreator.hpp 
+#molecuilder_CXXFLAGS = -cc=/opt/packages/gcc-4.0.2/bin/gcc  -g -O -march=nocona -Wall -DBIGENDIAN=0
+molecuilder_CXXFLAGS = -g3 -march=nocona -Wall -DBIGENDIAN=0
+joiner_CXXFLAGS = -g3 -march=nocona -Wall -DBIGENDIAN=0
+analyzer_CXXFLAGS = -g3 -march=nocona -Wall -DBIGENDIAN=0
+
+#EXTRA_DIST = ${molecuilder_DATA}
Index: molecuilder/src/analyzer.cpp
===================================================================
--- molecuilder/src/analyzer.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/analyzer.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,389 @@
+/** \file analyzer.cpp
+ *
+ * Takes evaluated fragments (energy and forces) and does evaluation of how sensible the BOSSANOVA
+ * approach was, e.g. in the decay of the many-body-contributions.
+ *    
+ */
+
+//============================ INCLUDES ===========================
+
+#include "helpers.hpp" 
+#include "parser.hpp"
+#include "datacreator.hpp"
+
+
+//============================== MAIN =============================
+
+int main(int argc, char **argv)
+{
+  EnergyMatrix Energy;
+  ForceMatrix Force;
+  MatrixContainer Time;
+  EnergyMatrix EnergyFragments;
+  ForceMatrix ForceFragments;
+  KeySetsContainer KeySet;  
+  stringstream prefix;
+  ofstream output;
+  ofstream output2;
+  ofstream output3;
+  ofstream output4;
+  stringstream filename;
+  stringstream line;
+  time_t t = time(NULL);
+  struct tm *ts = localtime(&t);
+  char *datum = asctime(ts);
+  stringstream Orderxrange;
+  stringstream Fragmentxrange;
+
+  cout << "ANOVA Analyzer" << endl;
+  cout << "==============" << endl;
+  
+  // Get the command line options
+  if (argc < 4) {
+    cout << "Usage: " << argv[0] << " <inputdir> <prefix> <outputdir>" << endl;
+    cout << "<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;
+    cout << "<prefix>\tprefix of energy and forces file." << endl;
+    cout << "<outputdir>\tcreated plotfiles and datafiles are placed into this directory " << endl;
+    return 1;
+  }
+  
+  // Test the given directory
+  if (!TestParams(argc, argv))
+    return 1;
+
+  // +++++++++++++++++ PARSING +++++++++++++++++++++++++++++++
+  
+  // ------------- Parse through all Fragment subdirs --------
+  if (!Energy.ParseMatrix(argv[1], argv[2], EnergySuffix,0,0)) return 1;
+  if (!Force.ParseMatrix(argv[1], argv[2], ForcesSuffix,0,0)) return 1;
+  if (!Time.ParseMatrix(argv[1], argv[2], TimeSuffix, 10,1)) return 1;
+
+  // ---------- Parse the TE Factors into an array -----------------
+  if (!Energy.ParseIndices()) return 1;
+  
+  // ---------- Parse the Force indices into an array ---------------
+  if (!Force.ParseIndices(argv[1])) return 1;
+
+  // ---------- Parse the KeySets into an array ---------------
+  if (!KeySet.ParseKeySets(argv[1], Force.RowCounter, Force.MatrixCounter)) return 1;
+  if (!KeySet.ParseManyBodyTerms()) return 1;
+  if (!EnergyFragments.ParseMatrix(argv[1], argv[2], EnergyFragmentSuffix,0,0)) return 1;
+  if (!ForceFragments.ParseMatrix(argv[1], argv[2], ForceFragmentSuffix,0,0)) return 1;
+
+  // +++++++++++++++ TESTING ++++++++++++++++++++++++++++++
+  
+  // print energy and forces to file
+  filename.str("");
+  filename << argv[3] << "/" << "energy-forces.all";
+  output.open(filename.str().c_str(), ios::out);
+  output << endl << "Total Energy" << endl << "==============" << endl << Energy.Header << endl;
+  for(int j=0;j<Energy.RowCounter[Energy.MatrixCounter];j++) {
+    for(int k=0;k<Energy.ColumnCounter;k++)
+      output << scientific << Energy.Matrix[ Energy.MatrixCounter ][j][k] << "\t";
+    output << endl;
+  }
+  output << endl;
+  
+  output << endl << "Total Forces" << endl << "===============" << endl << Force.Header << endl;
+  for(int j=0;j<Force.RowCounter[Force.MatrixCounter];j++) {
+    for(int k=0;k<Force.ColumnCounter;k++)
+      output << scientific << Force.Matrix[ Force.MatrixCounter ][j][k] << "\t";
+    output << endl;
+  }
+  output << endl;
+
+  output << endl << "Total Times" << endl << "===============" << endl << Time.Header << endl;
+  Time.SetLastMatrix(0., 0);
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++)
+    for(int i=0;i<KeySet.FragmentsPerOrder[BondOrder];i++)
+      for(int j=0;j<Time.RowCounter[Time.MatrixCounter];j++)
+        for(int k=0;k<Time.ColumnCounter;k++) {
+          Time.Matrix[ Time.MatrixCounter ][j][k] += Time.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+        }
+  for(int j=0;j<Time.RowCounter[Time.MatrixCounter];j++) {
+    for(int k=0;k<Time.ColumnCounter;k++)
+      output << scientific << Time.Matrix[ Time.MatrixCounter ][j][k] << "\t";
+    output << endl;
+  }
+  output << endl;
+  output.close();
+
+  // +++++++++++++++ ANALYZING ++++++++++++++++++++++++++++++
+  
+  cout << "Analyzing ..." << endl;
+
+  // ======================================= Creating the data files ==============================================================
+
+  // +++++++++++++++++++++++++++++++++++++++ Plotting Simtime vs Bond Order
+  if (!OpenOutputFile(output, argv[3], "SimTime-Order.dat" )) return false;
+  Time.SetLastMatrix(0., 0);
+  output << "#Order\tFrag.No.\t" << Time.Header << endl;
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    for(int i=0;i<KeySet.FragmentsPerOrder[BondOrder];i++)
+      for(int j=0;j<Time.RowCounter[Time.MatrixCounter];j++)
+        for(int k=0;k<Time.ColumnCounter;k++) {
+          Time.Matrix[ Time.MatrixCounter ][j][k] += Time.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+        }
+    output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
+    for(int k=0;k<Time.ColumnCounter;k++)
+      output << "\t" << scientific << Time.Matrix[ Time.MatrixCounter ][1][k];
+    output << endl;
+  }
+  output.close();
+
+  // +++++++++++++++++++++++++++++++++++++++ Plotting deviation in energy to full QM
+  if (!EnergyFragments.SetLastMatrix(Energy.Matrix[Energy.MatrixCounter],0)) return 1;
+  if (!CreateDataEnergyOrder(Energy, EnergyFragments, KeySet, argv[3], "DeltaEnergies-Order", "Plot of error between approximated and full energies energies versus the Bond Order", datum)) return 1;
+  
+  // +++++++++++++++++++++++++++++++++++Plotting Energies vs. Order
+  if (!EnergyFragments.SetLastMatrix(1.,0)) return 1;
+  if (!CreateDataEnergyOrder(Energy, EnergyFragments, KeySet, argv[3], "Energies-Order", "Plot of approximated energies versus the Bond Order", datum)) return 1;
+  
+  // +++++++++++++++++++++++++++++++++++++++ Plotting deviation in forces to full QM
+  if (!ForceFragments.SetLastMatrix(Force.Matrix[Force.MatrixCounter],0)) return 1;
+  if (!OpenOutputFile(output, argv[3], "DeltaForces-Order.dat" )) return false;
+  if (!OpenOutputFile(output2, argv[3], "DeltaMinForces-Order.dat" )) return false;
+  if (!OpenOutputFile(output3, argv[3], "DeltaMeanForces-Order.dat" )) return false;
+  if (!OpenOutputFile(output4, argv[3], "DeltaMaxForces-Order.dat" )) return false;
+  cout << "Plot of per atom and min/mean/max error between approximated forces and full forces versus the Bond Order ... " << endl;
+  output << "# Plot of error between approximated forces and full forces versus the Bond Order, created on " << datum;
+  output << "# AtomNo" << Force.Header << endl;
+  output2 << "# Plot of min error between approximated forces and full forces versus the Bond Order, created on " << datum;
+  output2 << "# Order\tFrag.No.\t" << Force.Header << endl;
+  output3 << "# Plot of mean error between approximated forces and full forces versus the Bond Order, created on " << datum;
+  output3 << "# Order\tFrag.No.\t" << Force.Header << endl;
+  output4 << "# Plot of max error between approximated forces and full forces versus the Bond Order, created on " << datum;
+  output4 << "# Order\tFrag.No.\t" << Force.Header << endl;
+  int FragmentCounter = 0;
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    for(int i=0;i<KeySet.FragmentsPerOrder[BondOrder];i++) {
+      for(int l=0;l<Force.RowCounter[ KeySet.OrderSet[BondOrder][i] ];l++) {
+        int j = Force.Indices[ KeySet.OrderSet[BondOrder][i] ][l];
+        if (j > Force.RowCounter[Force.MatrixCounter]) {
+          cerr << "Current force index " << j << " is greater than " << Force.RowCounter[Force.MatrixCounter] << "!" << endl;
+          return 1;
+        }
+        if (j != -1)
+          for(int k=0;k<Force.ColumnCounter;k++) {
+            Force.Matrix[Force.MatrixCounter][j][k] -= ForceFragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][l][k];
+          }
+      }
+      FragmentCounter++;
+    }
+    // errors per atom
+    output << "#Order\t" << BondOrder+1 << endl;
+    for(int j=0;j<Force.RowCounter[ Force.MatrixCounter ];j++) { 
+      output << Force.Indices[Force.MatrixCounter][j] << "\t";
+      for (int l=0;l<Force.ColumnCounter;l++)
+        if (fabs(ForceFragments.Matrix[ForceFragments.MatrixCounter][ j ][l]) < MYEPSILON)
+          output << scientific << Force.Matrix[Force.MatrixCounter][ j ][l] << "\t";
+        else
+          output << scientific << (Force.Matrix[Force.MatrixCounter][ j ][l] / ForceFragments.Matrix[ForceFragments.MatrixCounter][ j ][l]) << "\t";
+      output << endl;
+    }
+    output << endl;
+    
+    // min error
+    output2 << BondOrder+1 << "\t" << FragmentCounter;
+    CreateMinimumForce(Force, Force.MatrixCounter);
+    for (int l=0;l<Force.ColumnCounter;l++)
+      if (fabs(ForceFragments.Matrix[ForceFragments.MatrixCounter][ ForceFragments.RowCounter[ForceFragments.MatrixCounter] ][l]) < MYEPSILON)
+        output2 << scientific << "\t" << Force.Matrix[Force.MatrixCounter][ Force.RowCounter[Force.MatrixCounter] ][l];
+      else
+        output2 << scientific << "\t" << (Force.Matrix[Force.MatrixCounter][ Force.RowCounter[Force.MatrixCounter] ][l] / ForceFragments.Matrix[ForceFragments.MatrixCounter][ ForceFragments.RowCounter[ForceFragments.MatrixCounter] ][l]);
+    output2 << endl;
+    
+    // mean error
+    output3 << BondOrder+1 << "\t" << FragmentCounter;
+    CreateMeanForce(Force, Force.MatrixCounter);
+    for (int l=0;l<Force.ColumnCounter;l++)
+      if (fabs(ForceFragments.Matrix[ForceFragments.MatrixCounter][ ForceFragments.RowCounter[ForceFragments.MatrixCounter] ][l]) < MYEPSILON)
+        output3 << scientific << "\t" << Force.Matrix[Force.MatrixCounter][ Force.RowCounter[Force.MatrixCounter] ][l];
+      else
+        output3 << scientific << "\t" << (Force.Matrix[Force.MatrixCounter][ Force.RowCounter[Force.MatrixCounter] ][l] / ForceFragments.Matrix[ForceFragments.MatrixCounter][ ForceFragments.RowCounter[ForceFragments.MatrixCounter] ][l]);
+    output3 << endl;
+    
+    // max error
+    output4 << BondOrder+1 << "\t" << FragmentCounter;
+    CreateMaximumForce(Force, Force.MatrixCounter);
+    for (int l=0;l<Force.ColumnCounter;l++)
+      if (fabs(ForceFragments.Matrix[ForceFragments.MatrixCounter][ ForceFragments.RowCounter[ForceFragments.MatrixCounter] ][l]) < MYEPSILON)
+        output4 << scientific << "\t" << Force.Matrix[Force.MatrixCounter][ Force.RowCounter[Force.MatrixCounter] ][l];
+      else
+        output4 << scientific << "\t" << (Force.Matrix[Force.MatrixCounter][ Force.RowCounter[Force.MatrixCounter] ][l] / ForceFragments.Matrix[ForceFragments.MatrixCounter][ ForceFragments.RowCounter[ForceFragments.MatrixCounter] ][l]);
+    output4 << endl;
+  }
+  output.close();
+  output2.close();
+  output3.close();
+  output4.close();
+
+  // ++++++++++++++++++++++++++++++++++++++Plotting Forces vs. Order
+  if(!OpenOutputFile(output, argv[3], "Forces-Order.dat")) return 1;
+  cout << "Plot of approximated forces versus the Bond Order ... " << endl;
+  output << "# Plot of approximated forces versus the Bond Order, created on " << datum;
+  output << "# AtomNo" << Force.Header << endl;
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    for(int i=0;i<KeySet.FragmentsPerOrder[BondOrder];i++) {
+      for(int l=0;l<Force.RowCounter[ KeySet.OrderSet[BondOrder][i] ];l++) {
+        int j = Force.Indices[ KeySet.OrderSet[BondOrder][i] ][l];
+        if (j > Force.RowCounter[Force.MatrixCounter]) {
+          cerr << "Current force index " << j << " is greater than " << Force.RowCounter[Force.MatrixCounter] << "!" << endl;
+          return 1;
+        }
+        if (j != -1)
+          for(int k=0;k<Force.ColumnCounter;k++) {
+            Force.Matrix[Force.MatrixCounter][j][k] -= ForceFragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][l][k];
+          }
+      }
+    }
+    // errors per atom
+    output << "#Order\t" << BondOrder+1 << endl;
+    for(int j=0;j<Force.RowCounter[ Force.MatrixCounter ];j++) { 
+      output << Force.Indices[Force.MatrixCounter][j] << "\t";
+      for (int l=0;l<Force.ColumnCounter;l++)
+         output << Force.Matrix[Force.MatrixCounter][ j ][l] << "\t";
+      output << endl;
+    }
+    output << endl;
+  }
+  output.close();
+
+  // min force
+  if (!CreateDataForcesOrder(Force, ForceFragments, KeySet, argv[3], "MinForces-Order", "Plot of min approximated forces versus the Bond Order", datum, CreateMinimumForce)) return 1;
+
+  // mean force
+  if (!CreateDataForcesOrder(Force, ForceFragments, KeySet, argv[3], "MeanForces-Order", "Plot of mean approximated forces versus the Bond Order", datum, CreateMeanForce)) return 1;
+
+  // max force
+  if (!CreateDataForcesOrder(Force, ForceFragments, KeySet, argv[3], "MaxForces-Order", "Plot of max approximated forces versus the Bond Order", datum, CreateMaximumForce)) return 1;
+
+  // ++++++++++++++++++++++++++++++++++++++Plotting vector sum (should be 0) vs. bond order
+  if (!CreateDataForcesOrder(Force, ForceFragments, KeySet, argv[3], "VectorSum-Order", "Plot of vector sum of the approximated forces versus the Bond Order", datum, CreateVectorSumForce)) return 1;
+
+  // +++++++++++++++++++++++++++++++Plotting energyfragments vs. order
+  if (!CreateDataFragment(EnergyFragments, KeySet, argv[3], "Energies-Fragment", "Plot of fragment energy versus the Fragment No", datum, CreateEnergy)) return 1;
+  if (!CreateDataFragment(EnergyFragments, KeySet, argv[3], "Energies-FragmentOrder", "Plot of fragment energy of each Fragment No vs. Bond Order", datum, CreateEnergy)) return 1;
+  if (!CreateDataFragmentOrder(EnergyFragments, KeySet, argv[3], "MaxEnergies-FragmentOrder", "Plot of maximum of fragment energy vs. Bond Order", datum, CreateMaxFragmentOrder)) return 1;
+  if (!CreateDataFragmentOrder(EnergyFragments, KeySet, argv[3], "MinEnergies-FragmentOrder", "Plot of minimum of fragment energy vs. Bond Order", datum, CreateMinFragmentOrder)) return 1;
+
+  // +++++++++++++++++++++++++++++++Ploting min/mean/max forces for each fragment
+  // min force
+  if (!CreateDataFragment(ForceFragments, KeySet, argv[3], "MinForces-Fragment", "Plot of min approximated forces versus the Fragment No", datum, CreateMinimumForce)) return 1;
+
+  // mean force
+  if (!CreateDataFragment(ForceFragments, KeySet, argv[3], "MeanForces-Fragment", "Plot of mean approximated forces versus the Fragment No", datum, CreateMeanForce)) return 1;
+
+  // max force
+  if (!CreateDataFragment(ForceFragments, KeySet, argv[3], "MaxForces-Fragment", "Plot of max approximated forces versus the Fragment No", datum, CreateMaximumForce)) return 1;
+
+  // +++++++++++++++++++++++++++++++Ploting min/mean/max forces for each fragment per order
+  // min force
+  if (!CreateDataFragment(ForceFragments, KeySet, argv[3], "MinForces-FragmentOrder", "Plot of min approximated forces of each Fragment No vs. Bond Order", datum, CreateMinimumForce)) return 1;
+
+  // mean force
+  if (!CreateDataFragment(ForceFragments, KeySet, argv[3], "MeanForces-FragmentOrder", "Plot of mean approximated forces of each Fragment No vs. Bond Order", datum, CreateMeanForce)) return 1;
+
+  // max force
+  if (!CreateDataFragment(ForceFragments, KeySet, argv[3], "MaxForces-FragmentOrder", "Plot of max approximated forces of each Fragment No vs. Bond Order", datum, CreateMaximumForce)) return 1;
+
+  // ======================================= Creating the plot files ==============================================================
+ 
+  Orderxrange << "[1:" << KeySet.Order << "]";
+  Fragmentxrange << "[0:" << KeySet.FragmentCounter+1 << "]";
+  
+  // +++++++++++++++++++++++++++++++++++++++ Plotting Simtime vs Bond Order
+  if (!CreatePlotOrder(Time, KeySet, argv[3], "SimTime-Order", 1, "below", "y", "",  1, 1, "bond order k", "Evaluation time [s]", Orderxrange.str().c_str(), "", "1" , "with linespoints", EnergyPlotLine)) return 1;
+  
+  // +++++++++++++++++++++++++++++++++++++++ Plotting deviation in energy to full QM
+  if (!CreatePlotOrder(Energy, KeySet, argv[3], "DeltaEnergies-Order", 1, "outside", "y", "",  1, 1, "bond order k", "absolute error in energy [Ht]", Orderxrange.str().c_str(), "[1e-8:1e+1]", "1" , "with linespoints", AbsEnergyPlotLine)) return 1;
+  
+  // +++++++++++++++++++++++++++++++++++Plotting Energies vs. Order
+  if (!CreatePlotOrder(Energy, KeySet, argv[3], "Energies-Order", 1, "outside", "", "",  1, 1, "bond order k", "approximate energy [Ht]", Orderxrange.str().c_str(), "", "1" , "with linespoints", EnergyPlotLine)) return 1;
+
+  // +++++++++++++++++++++++++++++++++++++++ Plotting deviation in forces to full QM
+  // min force
+  if (!CreatePlotOrder(Force, KeySet, argv[3], "DeltaMinForces-Order", 2, "top right", "y", "",  1, 1, "bond order k", "absolute error in min force [Ht/a.u.]", Orderxrange.str().c_str(), "[1e-8:1e+0]", "1" , "with linespoints", ForceMagnitudePlotLine)) return 1;
+
+  // mean force
+  if (!CreatePlotOrder(Force, KeySet, argv[3], "DeltaMeanForces-Order", 2, "top right", "y", "",  1, 1, "bond order k", "absolute error in mean force [Ht/a.u.]", Orderxrange.str().c_str(), "[1e-8:1e+0]", "1" , "with linespoints", AbsFirstForceValuePlotLine)) return 1;
+
+  // max force
+  if (!CreatePlotOrder(Force, KeySet, argv[3], "DeltaMaxForces-Order", 2, "top right", "y", "",  1, 1, "bond order k", "absolute error in max force [Ht/a.u.]", Orderxrange.str().c_str(), "[1e-8:1e+0]", "1" , "with linespoints", ForceMagnitudePlotLine)) return 1;
+
+  // min/mean/max comparison for total force
+  if(!OpenOutputFile(output, argv[3], "DeltaMinMeanMaxTotalForce-Order.pyx")) return 1;
+  CreatePlotHeader(output, "DeltaMinMeanMaxTotalForce-Order", 1, "bottom left", "y", "",  1, 1, "bond order k", "absolute error in total forces [Ht/a.u.]");
+  output << "plot " << Orderxrange.str().c_str() << " [1e-8:1e+0] \\" << endl;  
+  output << "'DeltaMinForces-Order.dat' title 'minimum' using 1:(sqrt($" << 8 << "*$" << 8 << "+$" << 8+1 << "*$" << 8+1 << "+$" << 8+2 << "*$" << 8+2 << ")) with linespoints, \\" << endl;
+  output << "'DeltaMeanForces-Order.dat' title 'mean' using 1:(abs($" << 8 << ")) with linespoints, \\" << endl;
+  output << "'DeltaMaxForces-Order.dat' title 'maximum' using 1:(sqrt($" << 8 << "*$" << 8 << "+$" << 8+1 << "*$" << 8+1 << "+$" << 8+2 << "*$" << 8+2 << ")) with linespoints" << endl;
+  output.close();  
+
+  // ++++++++++++++++++++++++++++++++++++++Plotting Forces vs. Order
+  // min force
+  if (!CreatePlotOrder(Force, KeySet, argv[3], "MinForces-Order", 2, "bottom right", "y", "",  1, 1, "bond order k", "absolute approximated min force [Ht/a.u.]", Orderxrange.str().c_str(), "", "1" , "with linespoints", ForceMagnitudePlotLine)) return 1;
+
+  // mean force
+  if (!CreatePlotOrder(Force, KeySet, argv[3], "MeanForces-Order", 2, "bottom right", "y", "",  1, 1, "bond order k", "absolute approximated mean force [Ht/a.u.]", Orderxrange.str().c_str(), "", "1" , "with linespoints", AbsFirstForceValuePlotLine)) return 1;
+
+  // max force
+  if (!CreatePlotOrder(Force, KeySet, argv[3], "MaxForces-Order", 2, "bottom right", "y", "",  1, 1, "bond order k", "absolute approximated max force [Ht/a.u.]", Orderxrange.str().c_str(), "", "1" , "with linespoints", ForceMagnitudePlotLine)) return 1;
+
+  // min/mean/max comparison for total force
+  if(!OpenOutputFile(output, argv[3],"MinMeanMaxTotalForce-Order.pyx")) return 1;
+  CreatePlotHeader(output, "MinMeanMaxTotalForce-Order", 1, "bottom left", "y", "", 1, 1, "bond order k", "absolute total force [Ht/a.u.]");
+  output << "plot "<< Orderxrange.str().c_str() << " [1e-8:1e+0] \\" << endl;  
+  output << "'MinForces-Order.dat' title 'minimum' using 1:(sqrt($" << 8 << "*$" << 8 << "+$" << 8+1 << "*$" << 8+1 << "+$" << 8+2 << "*$" << 8+2 << ")) with linespoints, \\" << endl;
+  output << "'MeanForces-Order.dat' title 'mean' using 1:(abs($" << 8 << ")) with linespoints, \\" << endl;
+  output << "'MaxForces-Order.dat' title 'maximum' using 1:(sqrt($" << 8 << "*$" << 8 << "+$" << 8+1 << "*$" << 8+1 << "+$" << 8+2 << "*$" << 8+2 << ")) with linespoints" << endl;
+  output.close();  
+
+  // ++++++++++++++++++++++++++++++++++++++Plotting vector sum vs. Order
+
+  if (!CreatePlotOrder(Force, KeySet, argv[3], "VectorSum-Order", 2, "bottom right", "y" ,"", 1, 1, "bond order k", "vector sum of approximated forces [Ht/a.u.]", Orderxrange.str().c_str(), "", "1" , "with linespoints", ForceMagnitudePlotLine)) return 1;
+
+  // +++++++++++++++++++++++++++++++Plotting energyfragments vs. order
+  if (!CreatePlotOrder(EnergyFragments, KeySet, argv[3], "Energies-Fragment", 5, "below", "y", "", 1, 5, "fragment number", "Energies of each fragment [Ht]", Fragmentxrange.str().c_str(), "[1e-16:1e+1]", "2" , "with points", AbsEnergyPlotLine)) return 1;
+  if (!CreatePlotOrder(EnergyFragments, KeySet, argv[3], "Energies-FragmentOrder", 5, "below", "y", "", 1, 1, "bond order", "Energies of each fragment [Ht]", Orderxrange.str().c_str(), "[1e-10:1e+1]", "1" , "with points", AbsEnergyPlotLine)) return 1;
+  if (!CreatePlotOrder(EnergyFragments, KeySet, argv[3], "MaxEnergies-FragmentOrder", 5, "below", "y", "", 1, 1, "bond order", "Maximum fragment energy [Ht]", Orderxrange.str().c_str(), "[1e-6:1e+1]", "1" , "with linespoints", AbsEnergyPlotLine)) return 1;
+  if (!CreatePlotOrder(EnergyFragments, KeySet, argv[3], "MinEnergies-FragmentOrder", 5, "below", "y", "", 1, 1, "bond order", "Minimum fragment energy [Ht]", Orderxrange.str().c_str(), "[1e-6:1e+1]", "1" , "with linespoints", AbsEnergyPlotLine)) return 1;
+
+  // +++++++++++++++++++++++++++++++=Ploting min/mean/max forces for each fragment
+  // min
+  if (!CreatePlotOrder(ForceFragments, KeySet, argv[3], "MinForces-Fragment", 5, "below", "y", "set boxwidth 0.2", 1, 5, "fragment number", "minimum of approximated forces [Ht/a.u.]", Fragmentxrange.str().c_str(), "[1e-16:1e+1]", "2" , "with boxes fillcolor", BoxesForcePlotLine)) return 1;
+    
+  // mean
+  if (!CreatePlotOrder(ForceFragments, KeySet, argv[3], "MeanForces-Fragment", 5, "below", "y", "set boxwidth 0.2", 1, 5, "fragment number", "mean of approximated forces [Ht/a.u.]", Fragmentxrange.str().c_str(), "[1e-16:1e+1]", "2" , "with boxes fillcolor", BoxesFirstForceValuePlotLine)) return 1;
+    
+  // max
+  if (!CreatePlotOrder(ForceFragments, KeySet, argv[3], "MaxForces-Fragment", 5, "below", "y", "set boxwidth 0.2", 1, 5, "fragment number", "maximum of approximated forces [Ht/a.u.]", Fragmentxrange.str().c_str(), "[1e-16:1e+1]", "2" , "with boxes fillcolor", BoxesForcePlotLine)) return 1;
+
+  // +++++++++++++++++++++++++++++++=Ploting min/mean/max forces for each fragment per bond order
+  // min
+  if (!CreatePlotOrder(ForceFragments, KeySet, argv[3], "MinForces-FragmentOrder", 5, "below", "y", "set boxwidth 0.2", 1, 1, "bond order", "minimum of approximated forces [Ht/a.u.]", Orderxrange.str().c_str(), "[1e-16:1e+1]", "1" , "with boxes fillcolor", BoxesForcePlotLine)) return 1;
+    
+  // mean
+  if (!CreatePlotOrder(ForceFragments, KeySet, argv[3], "MeanForces-FragmentOrder", 5, "below", "y", "set boxwidth 0.2", 1, 1, "bond order", "mean of approximated forces [Ht/a.u.]", Orderxrange.str().c_str(), "[1e-16:1e+1]", "1" , "with boxes fillcolor", BoxesFirstForceValuePlotLine)) return 1;
+    
+  // max
+  if (!CreatePlotOrder(ForceFragments, KeySet, argv[3], "MaxForces-FragmentOrder", 5, "below", "y", "set boxwidth 0.2", 1, 1, "bond order", "maximum of approximated forces [Ht/a.u.]", Orderxrange.str().c_str(), "[1e-16:1e+1]", "1" , "with boxes fillcolor", BoxesForcePlotLine)) return 1;
+ 
+  // create Makefile
+  if(!OpenOutputFile(output, argv[3], "Makefile")) return 1;
+  output << "PYX = $(shell ls *.pyx)" << endl << endl;
+  output << "EPS = $(PYX:.pyx=.eps)" << endl << endl;
+  output << "%.eps: %.pyx" << endl;
+  output << "\t~/build/pyxplot/pyxplot $<" << endl << endl;
+  output << "all: $(EPS)" << endl << endl;
+  output << ".PHONY: clean" << endl;
+  output << "clean:" << endl;
+  output << "\trm -rf $(EPS)" << endl;
+  output.close();
+ 
+  // ++++++++++++++++ exit ++++++++++++++++++++++++++++++++++  
+  cout << "done." << endl;
+  return 0;
+};
+
+//============================ END ===========================
Index: molecuilder/src/atom.cpp
===================================================================
--- molecuilder/src/atom.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/atom.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,329 @@
+/** \file atom.cpp
+ * 
+ * Function implementations for the class atom.
+ * 
+ */
+
+#include "molecules.hpp"
+ 
+/************************************* Functions for class atom *************************************/
+
+/** Constructor of class atom.
+ */
+atom::atom() 
+{
+	Name = NULL;
+  previous = NULL;
+  next = NULL;
+  father = this;  // generally, father is itself
+  Ancestor = NULL;
+  type = NULL;
+  sort = NULL;
+  nr = -1;
+  GraphNr = -1;
+  ComponentNr = NULL;
+  SeparationVertex = false;
+  LowpointNr = -1;
+};
+
+/** Destructor of class atom.
+ */
+atom::~atom() 
+{
+	Free((void **)&Name, "atom::~atom: *Name");
+  Free((void **)&ComponentNr, "atom::~atom: *ComponentNr");
+};
+
+
+/** Climbs up the father list until NULL, last is returned.
+ * \return true father, i.e. whose father points to itself, NULL if it could not be found or has none (added hydrogen)
+ */
+atom *atom::GetTrueFather()
+{
+  atom *walker = this;
+  do {
+    if (walker == walker->father) // top most father is the one that points on itself
+      break;
+    walker = walker->father;
+  } while (walker != NULL);
+  return walker;
+};
+
+/** Output of a single atom.
+ * \param ElementNo cardinal number of the element
+ * \param AtomNo cardinal number among these atoms of the same element
+ * \param *out stream to output to
+ */
+bool atom::Output(int ElementNo, int AtomNo, ofstream *out) const
+{
+  if (out != NULL) {
+    *out << "Ion_Type" << ElementNo << "_" << AtomNo << "\t"  << fixed << setprecision(9) << showpoint;
+    *out << x.x[0] << "\t" << x.x[1] << "\t" << x.x[2] << "\t";
+    *out << "\t" << "0\t# Number in molecule " << nr << endl;
+    return true;
+  } else
+    return false;
+};
+
+/** Output of a single atom as one lin in xyz file.
+ * \param *out stream to output to
+ */
+bool atom::OutputXYZLine(ofstream *out) const
+{
+  if (out != NULL) {
+    *out << type->symbol << "\t" << x.x[0] << "\t" << x.x[1] << "\t" << x.x[2] << "\t" << endl;
+    return true;
+  } else
+    return false;
+};
+
+ostream & operator << (ostream &ost, atom &a) 
+{
+  ost << "[" << a.Name << "|" << &a << "]";
+  return ost;
+};
+
+/** Compares the indices of \a this atom with a given \a ptr.
+ * \param ptr atom to compare index against
+ * \return true - this one's is smaller, false - not
+ */ 
+bool atom::Compare(atom &ptr)
+{
+  if (nr < ptr.nr)
+    return true;
+  else
+    return false;
+};
+
+bool operator < (atom &a, atom &b) 
+{
+  return a.Compare(b);
+};
+
+/******************************** Functions for class AtomStackClass ********************************/
+
+/** Constructor of class AtomStackClass.
+ */
+AtomStackClass::AtomStackClass(int dimension)
+{
+  CurrentLastEntry = 0;
+  CurrentFirstEntry = 0;
+  NextFreeField = 0;
+  EntryCount = dimension;
+  StackList = (atom **) Malloc(sizeof(atom *)*EntryCount, "AtomStackClass::AtomStackClass: **StackList");
+};
+
+/** Destructor of class AtomStackClass.
+ */
+AtomStackClass::~AtomStackClass()
+{
+  Free((void **)&StackList, "AtomStackClass::AtomStackClass: **StackList");
+};
+
+/** Pushes an object onto the stack.
+ * \param *object atom to be pushed on stack
+ * \return true - sucess, false - failure, meaning stack field was occupied
+ */
+bool AtomStackClass::Push(atom *object)
+{
+  if (!IsFull()) {    // check whether free field is really not occupied
+    StackList[NextFreeField] = object;
+    CurrentLastEntry = NextFreeField;
+    NextFreeField = (NextFreeField + 1) % EntryCount; // step on to next free field
+    return true;
+  } else {
+    cerr << "ERROR: Stack is full, " << "Stack: CurrentLastEntry " << CurrentLastEntry<< "\tCurrentFirstEntry " << CurrentFirstEntry << "\tNextFreeField " << NextFreeField << "\tEntryCount " << EntryCount << "!" << endl;
+    return false;
+  }
+};
+
+/** Pops first/oldest atom from stack.
+ * First in, last out.
+ * \return atom pointer from stack, NULL - if failure (no atom pointer in field)
+ */
+atom *AtomStackClass::PopFirst()
+{
+  atom *Walker = NULL;
+  if (!IsEmpty()) {
+    Walker = StackList[CurrentFirstEntry];
+    if (Walker == NULL)
+      cerr << "ERROR: Stack's field is empty!" << endl;
+    StackList[CurrentFirstEntry] = NULL;
+    if (CurrentFirstEntry != CurrentLastEntry) { // hasn't last item been popped as well?
+      CurrentFirstEntry = (CurrentFirstEntry + 1) % EntryCount; // step back from current free field to last used (somehow modulo does not work in -1)
+    } else {
+      CurrentFirstEntry = (CurrentFirstEntry + 1) % EntryCount; // step back from current free field to last used (somehow modulo does not work in -1)
+      CurrentLastEntry = CurrentFirstEntry;
+    }
+  } else
+    cerr << "ERROR: Stack is empty!" << endl; 
+  return Walker;
+};
+
+/** Pops last atom from stack.
+ * First in, first out.
+ * \return atom pointer from stack, NULL - if failure (no atom pointer in field)
+ */
+atom *AtomStackClass::PopLast()
+{
+  atom *Walker = NULL;
+  if (!IsEmpty()) {
+    Walker = StackList[CurrentLastEntry];
+    StackList[CurrentLastEntry] = NULL;
+    if (Walker == NULL)
+      cerr << "ERROR: 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 {
+    cerr << "ERROR: Stack is empty!" << endl;
+  } 
+  return Walker;
+};
+
+/** Removes a certain item from the stack.
+ * Item is seeked between \a CurrentFirstEntry and \a CurrentLastEntry, if found, place in stack is NULL'd and
+ * all subsequent items shifted by one position downward (with wrapping taken into account).
+ * \param *ptr adress of item
+ * \return true - item was removed, false - item was not found
+ */
+bool AtomStackClass::RemoveItem(atom *ptr)
+{
+  bool found = false;
+  cout << 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
+        cout << Verbose(5) << "Item " << *ptr << " was number " << i << " on stack, removing it." << endl;
+        found = true;
+        StackList[i] = NULL;
+      }
+      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
+          cout << Verbose(5) << "Shifting item 0 to place " << EntryCount-1 << "." << endl;
+          StackList[EntryCount-1] = StackList[0];
+        } else {
+          cout << Verbose(5) << "Shifting item " << i << " to place " << i-1 << "." << endl;
+          StackList[i-1] = StackList[i];
+        }
+      }
+      i=((i + 1) % EntryCount); // step on
+    } while (i!=NextFreeField);
+  else
+    cerr << "ERROR: Stack is already empty!" << endl;
+  if (found) {
+    NextFreeField = CurrentLastEntry;
+    if (CurrentLastEntry != CurrentFirstEntry)  // has there been more than one item on stack
+      CurrentLastEntry = (CurrentLastEntry + (EntryCount-1)) % EntryCount;
+  }
+  return found;
+};
+
+/** Test the functionality of the stack.
+ * \param *out ofstream for debugging
+ * \param *test one item to put on stack  
+ * \return true - all tests worked correctly
+ */
+void AtomStackClass::TestImplementation(ofstream *out, atom *test)
+{
+  atom *Walker = test;
+  *out << Verbose(1) << "Testing the snake stack..." << endl;
+  for (int i=0;i<EntryCount;i++) {
+    *out << Verbose(2) << "Filling " << i << "th element of stack." << endl; 
+    Push(Walker);
+    Walker=Walker->next;
+  }
+  *out << endl;
+  Output(out);
+  if (IsFull())
+    *out << "Stack is full as supposed to be!" << endl;
+  else
+    *out << "ERROR: Stack is not as full as supposed to be!" << endl;
+  //if (StackList[(EntryCount+1)/2] != NULL) {
+    *out << "Removing element in the middle ..." << endl;
+    RemoveItem(StackList[(EntryCount+1)/2]);
+    Output(out);
+  //}
+  //if (StackList[CurrentFirstEntry] != NULL) {
+    *out << "Removing first element  ..." << endl;
+    RemoveItem(StackList[CurrentFirstEntry]);
+    Output(out);
+  //}
+  //if (StackList[CurrentLastEntry] != NULL) {
+    *out << "Removing last element ..." << endl;
+    RemoveItem(StackList[CurrentLastEntry]);
+    Output(out);
+  //}
+  *out << "Clearing stack ... " << endl;  
+  ClearStack();
+  Output(out);
+  if (IsEmpty())
+    *out << "Stack is empty as supposed to be!" << endl;
+  else
+    *out << "ERROR: Stack is not as empty as supposed to be!" << endl;
+  *out << "done." << endl;
+};
+
+/** Puts contents of stack into ofstream \a *out.
+ * \param *out ofstream for output
+ */
+void AtomStackClass::Output(ofstream *out) const
+{
+  *out << "Contents of Stack: ";
+  for(int i=0;i<EntryCount;i++) {
+    *out << "\t";
+    if (i == CurrentFirstEntry)
+      *out << " 1";
+    if  (i == CurrentLastEntry)
+      *out << " "<< EntryCount;
+    if (i ==  NextFreeField)
+      *out << " F";
+    *out << ": " << StackList[i];
+  }
+  *out << endl;
+};
+
+/** Checks whether stack is empty.
+ * Simply checks whether AtomStackClass::NextFreeField is equal to AtomStackClass::CurrentFirstEntry and
+ * AtomStackClass::CurrentFirstEntry is equal to AtomStackClass::CurrentLastEntry.
+ * \return true - empty, false - not
+ */
+bool AtomStackClass::IsEmpty()
+{
+  return((NextFreeField == CurrentFirstEntry) && (CurrentLastEntry == CurrentFirstEntry));
+};
+
+/** Checks whether stack is full.
+ * Simply checks whether AtomStackClass::NextFreeField is equal to AtomStackClass::CurrentFirstEntry and
+ * AtomStackClass::CurrentFirstEntry is _not_ equal to AtomStackClass::CurrentLastEntry.
+ * \return true - full, false - not
+ */
+bool AtomStackClass::IsFull()
+{
+  return((NextFreeField == CurrentFirstEntry) && (CurrentLastEntry != CurrentFirstEntry));
+};
+
+/** Returns number of items on stack.
+ * Simply returns difference between AtomStackClass::Stacklist entry AtomStackClass::CurrentEntry-1.
+ * \return number of items on stack
+ * \warning will never return correct item count if stack is full, i.e. count would be AtomStackClass::EntryCount.
+ */
+int AtomStackClass::ItemCount()
+{
+  //cout << "Stack: CurrentLastEntry " << CurrentLastEntry<< "\tCurrentFirstEntry " << CurrentFirstEntry << "\tEntryCount " << EntryCount << "." << endl;
+  return((NextFreeField + (EntryCount - CurrentFirstEntry)) % EntryCount);
+};
+
+/** Clears the stack from all atoms.
+ * \return true - sucess, false - failure
+ */
+void AtomStackClass::ClearStack()
+{
+  for(int i=0;i<EntryCount; i++)
+    StackList[i] = NULL;
+  CurrentFirstEntry = 0;
+  CurrentLastEntry = 0;
+  NextFreeField = 0;
+};
+
Index: molecuilder/src/bond.cpp
===================================================================
--- molecuilder/src/bond.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/bond.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,165 @@
+/** \file bond.cpp
+ * 
+ * Function implementations for the classes BondLeaf, BondTree and bond.
+ * 
+ */
+
+#include "molecules.hpp"
+
+
+/***************************************** Functions for class bond ********************************/
+
+/** Empty Constructor for class bond.
+ */
+bond::bond()
+{
+	leftatom = NULL;
+	rightatom = NULL;
+  previous = NULL;
+  next = NULL;
+	nr = -1;
+	HydrogenBond = 0;
+	BondDegree = 0;
+  Used = white;
+  Cyclic = false;
+  Type = Undetermined;
+};
+
+/** Constructor for class bond, taking right and left bond partner
+ * \param *left left atom
+ * \param *right right atom
+ * \param degree bond degree
+ * \param number increasing index
+ */
+bond::bond(atom *left, atom *right, int degree=1, int number=0)
+{
+	leftatom = left;
+	rightatom = right;
+  previous = NULL;
+  next = NULL;
+	HydrogenBond = 0;
+  if ((left != NULL) && (right != NULL)) {
+  	if ((left->type != NULL) && (left->type->Z == 1))
+  		HydrogenBond++;
+  	if ((right->type != NULL) && (right->type->Z == 1))
+  		HydrogenBond++;
+  }
+  BondDegree = degree;
+  nr = number;
+  Used = white;
+  Cyclic = false;
+};
+bond::bond(atom *left, atom *right)
+{
+  leftatom = left;
+  rightatom = right;
+  previous = NULL;
+  next = NULL;
+  HydrogenBond = 0;
+  if ((left != NULL) && (right != NULL)) {
+    if ((left->type != NULL) && (left->type->Z == 1))
+      HydrogenBond++;
+    if ((right->type != NULL) && (right->type->Z == 1))
+      HydrogenBond++;
+  }
+  BondDegree = 1;
+  nr = 0;
+  Used = white;
+  Cyclic = false;
+};
+
+/** Empty Destructor for class bond.
+ */
+bond::~bond()
+{
+  // remove this node from the list structure
+  if (previous != NULL) {
+    previous->next = next;
+  }
+  if (next != NULL) {
+    next->previous = previous;
+  }
+};
+
+ostream & operator << (ostream &ost, bond &b) 
+{
+  ost << "[" << b.leftatom->Name << " <" << b.BondDegree << "(H" << b.HydrogenBond << ")>" << b.rightatom->Name << "]";
+  return ost;
+};
+
+/** Get the other atom in a bond if one is specified.
+ * \param *Atom the pointer to the one atom
+ * \return pointer to the other atom in the bond, NULL if no match (indicates something's wrong with the bond) 
+ */
+atom * bond::GetOtherAtom(atom *Atom) const
+{
+  if(leftatom == Atom) 
+    return rightatom;
+  if(rightatom == Atom) 
+    return leftatom;
+  return NULL;
+};
+
+/** Get the other atom in a bond if one is specified.
+ * \param *Atom the pointer to the one atom
+ * \return pointer to the other atom in the bond, NULL if no match (indicates something's wrong with the bond) 
+ */
+bond * bond::GetFirstBond()
+{
+  return GetFirst(this);
+};
+
+/** Get the other atom in a bond if one is specified.
+ * \param *Atom the pointer to the one atom
+ * \return pointer to the other atom in the bond, NULL if no match (indicates something's wrong with the bond) 
+ */
+bond * bond::GetLastBond()
+{
+  return GetLast(this);
+};
+
+/** Returns whether vertex was used in DFS.
+ * \return bond::Used
+ */
+enum Shading bond::IsUsed() 
+{
+  return Used;
+};
+
+/** Checks if an atom exists in a bond.
+ * \param *ptr pointer to atom
+ * \return true if it is either bond::leftatom or bond::rightatom, false otherwise
+ */
+bool bond::Contains(const atom *ptr)
+{
+  return ((leftatom == ptr) || (rightatom == ptr));
+};
+
+/** Checks if an atom exists in a bond.
+ * \param nr index of atom
+ * \return true if it is either bond::leftatom or bond::rightatom, false otherwise
+ */
+bool bond::Contains(const int nr)
+{
+  return ((leftatom->nr == nr) || (rightatom->nr == nr));
+};
+
+/** Masks vertex as used in DFS.
+ * \return bond::Used, false if bond was already marked used
+ */
+bool bond::MarkUsed(enum Shading color) {
+  if (Used == black) {
+    cerr << "ERROR: Bond " << this << " was already marked black!." << endl;
+    return false;
+  } else {
+    Used = color;
+    return true;
+  }
+};
+
+/** Resets used flag in DFS.
+ * \return bond::Used
+ */
+void bond::ResetUsed() {
+  Used = white;
+};
Index: molecuilder/src/builder.cpp
===================================================================
--- molecuilder/src/builder.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/builder.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,1170 @@
+/** \file builder.cpp
+ * 
+ * By stating absolute positions or binding angles and distances atomic positions of a molecule can be constructed.
+ * The output is the complete configuration file for PCP for direct use.
+ * Features:
+ * -# Atomic data is retrieved from a file, if not found requested and stored there for later re-use
+ * -# step-by-step construction of the molecule beginning either at a centre of with a certain atom
+ *    
+ */
+
+/*! \mainpage Molecuilder - a molecular set builder
+ * 
+ * This introductory shall briefly make aquainted with the program, helping in installing and a first run.
+ * 
+ * \section about About the Program
+ * 
+ *  Molecuilder is a short program, written in C++, that enables the construction of a coordinate set for the
+ *  atoms making up an molecule by the successive statement of binding angles and distances and referencing to
+ *  already constructed atoms.
+ * 
+ *  A configuration file may be written that is compatible to the format used by PCP - a parallel Car-Parrinello
+ *  molecular dynamics implementation.
+ * 
+ * \section install Installation
+ * 
+ *  Installation should without problems succeed as follows:
+ *  -# ./configure (or: mkdir build;mkdir run;cd build; ../configure --bindir=../run)
+ *  -# make
+ *  -# make install
+ * 
+ *  Further useful commands are
+ *  -# make clean uninstall: deletes .o-files and removes executable from the given binary directory\n
+ *  -# make doxygen-doc: Creates these html pages out of the documented source 
+ * 
+ * \section run Running
+ * 
+ *  The program can be executed by running: ./molecuilder
+ * 
+ *  Note, that it uses a database, called "elements.db", in the executable's directory. If the file is not found,
+ *  it is created and any given data on elements of the periodic table will be stored therein and re-used on
+ *  later re-execution. 
+ * 
+ * \section ref References
+ *  
+ *  For the special configuration file format, see the documentation of pcp.
+ * 
+ */
+
+
+using namespace std;
+
+#include "helpers.hpp"
+#include "molecules.hpp"
+
+/********************************************** Submenu routine **************************************/
+
+/** Submenu for adding atoms to the molecule.
+ * \param *periode periodentafel
+ * \param *mol the molecule to add to
+ */
+void AddAtoms(periodentafel *periode, molecule *mol)
+{
+  atom *first, *second, *third, *fourth;
+  vector **atoms;
+  vector x,y,z,n;  // coordinates for absolute point in cell volume
+  double a,b,c;
+  char choice;  // menu choice char
+  bool valid;
+
+  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) {
+      case 'a': // absolute coordinates of atom
+        cout << Verbose(0) << "Enter absolute coordinates." << endl;
+        first = new atom;
+        first->x.AskPosition(mol->cell_size, false);
+        first->type = periode->AskElement();  // give type
+        mol->AddAtom(first);  // add to molecule
+        break;
+        
+      case 'b': // relative coordinates of atom wrt to reference point
+        first = new atom;
+        valid = true;
+        do {
+          if (!valid) cout << Verbose(0) << "Resulting position out of cell." << endl;
+          cout << Verbose(0) << "Enter reference coordinates." << endl;
+          x.AskPosition(mol->cell_size, true);
+          cout << Verbose(0) << "Enter relative coordinates." << endl;
+          first->x.AskPosition(mol->cell_size, false);
+          first->x.AddVector((const vector *)&x);
+          cout << Verbose(0) << "\n";
+        } while (!(valid = mol->CheckBounds((const vector *)&first->x)));
+        first->type = periode->AskElement();  // give type
+        mol->AddAtom(first);  // add to molecule
+        break;
+        
+      case 'c': // relative coordinates of atom wrt to already placed atom
+        first = new atom;
+        valid = true;
+        do {
+          if (!valid) cout << Verbose(0) << "Resulting position out of cell." << endl;
+          second = mol->AskAtom("Enter atom number: ");                
+          cout << Verbose(0) << "Enter relative coordinates." << endl;
+          first->x.AskPosition(mol->cell_size, false);
+          for (int i=0;i<3;i++) {
+            first->x.x[i] += second->x.x[i];
+          }
+        } while (!(valid = mol->CheckBounds((const vector *)&first->x)));
+        first->type = periode->AskElement();  // give type
+        mol->AddAtom(first);  // add to molecule
+        break;
+      
+      case 'd': // two atoms, two angles and a distance
+        first = new atom;
+        valid = true;
+        do {
+          if (!valid) {
+            cout << Verbose(0) << "Resulting coordinates out of cell - ";
+            first->x.Output((ofstream *)&cout);
+            cout << Verbose(0) << 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): ");
+          fourth = mol->AskAtom("Enter third atom (specifying a plane for second angle): ");
+          a = ask_value("Enter distance between central (first) and new atom: ");
+          b = ask_value("Enter angle between new, first and second atom (degrees): ");
+          b *= M_PI/180.;
+          bound(&b, 0., 2.*M_PI);
+          c = ask_value("Enter second angle between new and normal vector of plane defined by first, second and third atom (degrees): ");
+          c *= M_PI/180.;
+          bound(&c, -M_PI, M_PI);
+          cout << Verbose(0) << "radius: " << a << "\t phi: " << b*180./M_PI << "\t theta: " << c*180./M_PI << endl;
+/*
+          second->Output(1,1,(ofstream *)&cout);
+          third->Output(1,2,(ofstream *)&cout);
+          fourth->Output(1,3,(ofstream *)&cout);
+          n.MakeNormalVector((const vector *)&second->x, (const vector *)&third->x, (const vector *)&fourth->x);
+          x.CopyVector(&second->x);
+          x.SubtractVector(&third->x);
+          x.CopyVector(&fourth->x);
+          x.SubtractVector(&third->x);
+          
+          if (!z.SolveSystem(&x,&y,&n, b, c, a)) {
+            cout << Verbose(0) << "Failure solving self-dependent linear system!" << endl;
+            continue;
+          }
+          cout << Verbose(0) << "resulting relative coordinates: ";
+          z.Output((ofstream *)&cout);
+          cout << Verbose(0) << endl;
+          */
+          // calc axis vector
+          x.CopyVector(&second->x);
+          x.SubtractVector(&third->x);
+          x.Normalize();
+          cout << "x: ",
+          x.Output((ofstream *)&cout);
+          cout << endl;          
+          z.MakeNormalVector(&second->x,&third->x,&fourth->x);
+          cout << "z: ",
+          z.Output((ofstream *)&cout);
+          cout << endl;          
+          y.MakeNormalVector(&x,&z);
+          cout << "y: ",
+          y.Output((ofstream *)&cout);
+          cout << endl;          
+         
+          // rotate vector around first angle
+          first->x.CopyVector(&x);
+          first->x.RotateVector(&z,b - M_PI);
+          cout << "Rotated vector: ",
+          first->x.Output((ofstream *)&cout);
+          cout << endl;          
+          // remove the projection onto the rotation plane of the second angle
+          n.CopyVector(&y);
+          n.Scale(first->x.Projection(&y));
+          cout << "N1: ",
+          n.Output((ofstream *)&cout);
+          cout << endl;          
+          first->x.SubtractVector(&n);
+          cout << "Subtracted vector: ",
+          first->x.Output((ofstream *)&cout);
+          cout << endl;          
+          n.CopyVector(&z);
+          n.Scale(first->x.Projection(&z));
+          cout << "N2: ",
+          n.Output((ofstream *)&cout);
+          cout << endl;          
+          first->x.SubtractVector(&n);
+          cout << "2nd subtracted vector: ",
+          first->x.Output((ofstream *)&cout);
+          cout << endl;          
+          
+          // rotate another vector around second angle
+          n.CopyVector(&y);
+          n.RotateVector(&x,c - M_PI);
+          cout << "2nd Rotated vector: ",
+          n.Output((ofstream *)&cout);
+          cout << endl;          
+          
+          // add the two linear independent vectors
+          first->x.AddVector(&n);
+          first->x.Normalize();         
+          first->x.Scale(a);
+          first->x.AddVector(&second->x);
+          
+          cout << Verbose(0) << "resulting coordinates: ";
+          first->x.Output((ofstream *)&cout);
+          cout << Verbose(0) << endl;
+        } while (!(valid = mol->CheckBounds((const vector *)&first->x)));
+        first->type = periode->AskElement();  // give type
+        mol->AddAtom(first);  // add to molecule
+        break;
+
+      case 'e': // least square distance position to a set of atoms
+        first = new atom;
+        atoms = new (vector*[128]);
+        valid = true;
+        for(int i=0;i<128;i++)
+          atoms[i] = NULL;
+        int i=0, j=0;
+        cout << Verbose(0) << "Now we need at least three molecules.\n";
+        do {
+          cout << Verbose(0) << "Enter " << i+1 << "th atom: ";
+          cin >> j;
+          if (j != -1) {
+            second = mol->FindAtom(j);
+            atoms[i++] = &(second->x);
+          }
+        } while ((j != -1) && (i<128));
+        if (i >= 2) {
+          first->x.LSQdistance(atoms, i);             
+
+          first->x.Output((ofstream *)&cout);
+          first->type = periode->AskElement();  // give type
+          mol->AddAtom(first);  // add to molecule
+        } else {
+          delete first;
+          cout << Verbose(0) << "Please enter at least two vectors!\n";
+        }
+        break;
+  };
+};
+
+/** Submenu for centering the atoms in the molecule.
+ * \param *mol the molecule with all the atoms
+ */
+void CenterAtoms(molecule *mol)
+{
+  vector x;
+  char choice;  // menu choice char
+  double min[3];
+  int j;
+  
+  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) << "all else - go back" << endl;
+  cout << Verbose(0) << "===============================================" << endl;
+  cout << Verbose(0) << "INPUT: ";
+  cin >> choice;
+  
+  switch (choice) {
+    default:
+      cout << Verbose(0) << "Not a valid choice." << endl;
+      break;
+    case 'a':
+      cout << Verbose(0) << "Centering atoms in config file on origin." << endl;
+      mol->CenterOrigin((ofstream *)&cout, &x);
+      break;
+    case 'b':
+      cout << Verbose(0) << "Centering atoms in config file on center of gravity." << endl;
+      mol->CenterGravity((ofstream *)&cout, &x);
+      break;
+    case 'c':
+      cout << Verbose(0) << "Centering atoms in config file within given additional boundary." << endl;
+      for (int i=0;i<3;i++) {
+        cout << Verbose(0) << "Enter axis " << i << " boundary: ";
+        cin >> min[i];
+      }
+      mol->CenterEdge((ofstream *)&cout, &x);  // make every coordinate positive
+      mol->SetBoxDimension(&x);  // update Box of atoms by boundary
+      // translate each coordinate by boundary
+      j=-1;
+      for (int i=0;i<NDIM;i++) {
+        j += i+1;
+        x.x[i] = min[i];
+        mol->cell_size[j] += x.x[i]*2.;
+      }
+      mol->Translate(&x);
+      break;
+  }
+};
+
+/** Submenu for aligning the atoms in the molecule.
+ * \param *periode periodentafel
+ * \param *mol the molecule with all the atoms
+ */
+void AlignAtoms(periodentafel *periode, molecule *mol)
+{
+  atom *first, *second, *third;
+  vector x,n;
+  char choice;  // menu choice char
+
+  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;
+  
+  switch (choice) {
+    default:
+    case 'a': // three atoms defining mirror plane
+      first = mol->AskAtom("Enter first atom: ");
+      second = mol->AskAtom("Enter second atom: ");
+      third = mol->AskAtom("Enter third atom: ");
+
+      n.MakeNormalVector((const vector *)&first->x,(const vector *)&second->x,(const vector *)&third->x);
+      break;
+    case 'b': // normal vector of mirror plane
+      cout << Verbose(0) << "Enter normal vector of mirror plane." << endl;
+      n.AskPosition(mol->cell_size,0);
+      n.Normalize();
+      break;
+    case 'c': // three atoms defining mirror plane
+      first = mol->AskAtom("Enter first atom: ");
+      second = mol->AskAtom("Enter second atom: ");
+
+      n.CopyVector((const vector *)&first->x);  
+      n.SubtractVector((const vector *)&second->x);  
+      n.Normalize();
+      break;        
+    case 'd':
+      char shorthand[4];
+      vector a;
+      struct lsq_params param;
+      do {
+        fprintf(stdout, "Enter the element of atoms to be chosen: ");
+        fscanf(stdin, "%3s", shorthand);
+      } while ((param.type = periode->FindElement(shorthand)) == NULL);
+      cout << Verbose(0) << "Element is " << param.type->name << endl;
+      mol->GetAlignVector(&param);
+      for (int i=0;i<3;i++) {
+        x.x[i] = gsl_vector_get(param.x,i);
+        n.x[i] = gsl_vector_get(param.x,i+3);
+      } 
+      gsl_vector_free(param.x);
+      cout << Verbose(0) << "Offset vector: ";
+      x.Output((ofstream *)&cout);
+      cout << Verbose(0) << endl;
+      n.Normalize();
+      break;       
+  };
+  cout << Verbose(0) << "Alignment vector: ";
+  n.Output((ofstream *)&cout);
+  cout << Verbose(0) << endl;
+  mol->Align(&n);
+};
+
+/** Submenu for mirroring the atoms in the molecule.
+ * \param *mol the molecule with all the atoms
+ */
+void MirrorAtoms(molecule *mol)
+{
+  atom *first, *second, *third;
+  vector n;
+  char choice;  // menu choice char
+  
+  cout << Verbose(0) << "===========MIRROR ATOMS=========================" << endl;
+  cout << Verbose(0) << " a - state three atoms defining mirror plane" << endl;
+  cout << Verbose(0) << " b - state normal vector of mirror plane" << endl;
+  cout << Verbose(0) << " c - state two atoms in normal direction" << endl;
+  cout << Verbose(0) << "all else - go back" << endl;
+  cout << Verbose(0) << "===============================================" << endl;
+  cout << Verbose(0) << "INPUT: ";
+  cin >> choice;
+  
+  switch (choice) {
+    default:
+    case 'a': // three atoms defining mirror plane
+      first = mol->AskAtom("Enter first atom: ");
+      second = mol->AskAtom("Enter second atom: ");
+      third = mol->AskAtom("Enter third atom: ");
+
+      n.MakeNormalVector((const vector *)&first->x,(const vector *)&second->x,(const vector *)&third->x);
+      break;
+    case 'b': // normal vector of mirror plane
+      cout << Verbose(0) << "Enter normal vector of mirror plane." << endl;
+      n.AskPosition(mol->cell_size,0);
+      n.Normalize();
+      break;
+    case 'c': // three atoms defining mirror plane
+      first = mol->AskAtom("Enter first atom: ");
+      second = mol->AskAtom("Enter second atom: ");
+
+      n.CopyVector((const vector *)&first->x);  
+      n.SubtractVector((const vector *)&second->x);  
+      n.Normalize();
+      break;          
+  };
+  cout << Verbose(0) << "Normal vector: ";
+  n.Output((ofstream *)&cout);
+  cout << Verbose(0) << endl;
+  mol->Mirror((const vector *)&n);
+};
+
+/** Submenu for removing the atoms from the molecule.
+ * \param *mol the molecule with all the atoms
+ */
+void RemoveAtoms(molecule *mol)
+{
+  atom *first, *second;
+  int axis;
+  double tmp1, tmp2;
+  char choice;  // menu choice char
+  
+  cout << Verbose(0) << "===========REMOVE ATOMS=========================" << endl;
+  cout << Verbose(0) << " a - state atom for removal by number" << endl;
+  cout << Verbose(0) << " b - keep only in radius around atom" << endl;
+  cout << Verbose(0) << " c - remove this with one axis greater value" << endl;
+  cout << Verbose(0) << "all else - go back" << endl;
+  cout << Verbose(0) << "===============================================" << endl;
+  cout << Verbose(0) << "INPUT: ";
+  cin >> choice;
+  
+  switch (choice) {
+    default:
+    case 'a':
+      if (mol->RemoveAtom(mol->AskAtom("Enter number of atom within molecule: ")))
+        cout << Verbose(1) << "Atom removed." << endl;
+      else
+        cout << Verbose(1) << "Atom not found." << endl;
+      break;
+    case 'b':
+      second = mol->AskAtom("Enter number of atom as reference point: ");
+      cout << Verbose(0) << "Enter radius: ";
+      cin >> tmp1;
+      first = mol->start;
+      while(first->next != mol->end) {
+        first = first->next;
+        if (first->x.Distance((const vector *)&second->x) > tmp1*tmp1) // distance to first above radius ...
+          mol->RemoveAtom(first);
+      }
+      break;
+    case 'c':
+      cout << Verbose(0) << "Which axis is it: ";
+      cin >> axis;
+      cout << Verbose(0) << "Left inward boundary: ";
+      cin >> tmp1;
+      cout << Verbose(0) << "Right inward boundary: ";
+      cin >> tmp2;
+      first = mol->start;
+      while(first->next != mol->end) {
+        first = first->next;
+        if ((first->x.x[axis] > tmp2) || (first->x.x[axis] < tmp1)) // out of boundary ...
+          mol->RemoveAtom(first);
+      }
+      break;          
+  };
+  //mol->Output((ofstream *)&cout);
+  choice = 'r';
+};
+
+/** Submenu for measuring out the atoms in the molecule.
+ * \param *periode periodentafel
+ * \param *mol the molecule with all the atoms
+ */
+void MeasureAtoms(periodentafel *periode, molecule *mol)
+{
+  atom *first, *second, *third;
+  vector x,y;
+  double min[256], tmp1, tmp2, tmp3;
+  int Z;
+  char choice;  // menu choice char
+  
+  cout << Verbose(0) << "===========MEASURE ATOMS=========================" << endl;
+  cout << Verbose(0) << " a - calculate bond length between one atom and all others" << endl;
+  cout << Verbose(0) << " b - calculate bond length between two atoms" << endl;
+  cout << Verbose(0) << " c - calculate bond angle" << endl;
+  cout << Verbose(0) << "all else - go back" << endl;
+  cout << Verbose(0) << "===============================================" << endl;
+  cout << Verbose(0) << "INPUT: ";
+  cin >> choice;
+
+  switch(choice) {
+    default:
+      cout << Verbose(1) << "Not a valid choice." << endl;
+      break;
+    case 'a':
+      first = mol->AskAtom("Enter first atom: ");
+      for (int i=0;i<256;i++)
+        min[i] = 0.;
+        
+      second = mol->start;   
+      while ((second->next != mol->end)) {
+        second = second->next; // advance
+        Z = second->type->Z;
+        tmp1 = 0.;
+        if (first != second) {
+          x.CopyVector((const vector *)&first->x);
+          x.SubtractVector((const vector *)&second->x);
+          tmp1 = x.Norm();
+        }
+        if ((tmp1 != 0.) && ((min[Z] == 0.) || (tmp1 < min[Z]))) min[Z] = tmp1;
+        //cout << Verbose(0) << "Bond length between Atom " << first->nr << " and " << second->nr << ": " << tmp1 << " a.u." << endl;         
+      }
+      for (int i=0;i<256;i++)
+        if (min[i] != 0.) cout << Verbose(0) << "Minimum Bond length between " << first->type->name << " Atom " << first->nr << " and next Ion of type " << (periode->FindElement(i))->name << ": " << min[i] << " a.u." << endl;
+      break;
+      
+    case 'b':
+      first = mol->AskAtom("Enter first atom: ");
+      second = mol->AskAtom("Enter second atom: ");
+      for (int i=0;i<NDIM;i++)
+        min[i] = 0.;
+      x.CopyVector((const vector *)&first->x);
+      x.SubtractVector((const vector *)&second->x);
+      tmp1 = x.Norm();
+      cout << Verbose(1) << "Distance vector is ";
+      x.Output((ofstream *)&cout);
+      cout << "." << endl << "Norm of distance is " << tmp1 << "." << endl;
+      break;
+
+    case 'c':
+      cout << Verbose(0) << "Evaluating bond angle between three - first, central, last - atoms." << endl;
+      first = mol->AskAtom("Enter first atom: ");
+      second = mol->AskAtom("Enter central atom: ");
+      third  = mol->AskAtom("Enter last atom: ");
+      tmp1 = tmp2 = tmp3 = 0.;
+      x.CopyVector((const vector *)&first->x);
+      x.SubtractVector((const vector *)&second->x);
+      y.CopyVector((const vector *)&third->x);
+      y.SubtractVector((const vector *)&second->x);
+      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) << (acos(x.ScalarProduct((const vector *)&y)/(y.Norm()*x.Norm()))/M_PI*180.) << " degrees" << endl;         
+      break;
+  }
+};
+
+/** Submenu for measuring out the atoms in the molecule.
+ * \param *mol the molecule with all the atoms
+ * \param *configuration configuration structure for the to be written config files of all fragments
+ */
+void FragmentAtoms(molecule *mol, config *configuration)
+{
+  enum BondOrderScheme Scheme = NoScheme;
+  enum CutCyclicBond CutCyclic;
+  char schema;
+  int Order1, Order2;
+  clock_t start, end;
+  
+  cout << Verbose(0) << "Fragmenting molecule with current connection matrix ..." << endl;
+  cout << Verbose(0) << "What's the desired bond order: ";
+  cin >> Order1;
+  cout << Verbose(0) << "What's the desired bond scheme [(B)ottomUp/(T)opDown/(A)NOVA/(C)ombined]: ";
+  cin >> schema;
+  CutCyclic = SaturateBond;
+  switch (schema) {
+    default:
+        Scheme = NoScheme;
+      break;
+    case 'B':
+        CutCyclic = KeepBond;
+    case 'b':
+        Scheme = BottomUp;
+        Order2 = 0;
+      break;
+    case 'T':
+        CutCyclic = KeepBond;
+    case 't':
+        Scheme = TopDown;
+        Order2 = Order1;
+        Order1 = 0;
+      break;
+    case 'A':
+        CutCyclic = KeepBond;
+    case 'a':
+        Scheme = ANOVA;
+        Order2 = 0;
+      break;
+    case 'C':
+        CutCyclic = KeepBond;
+    case 'c':
+        cout << Verbose(0) << "Combined first selects subgraphs by BottomUp of bond order " << Order1 << " then TopDown to fragment these." << endl;
+        cout << Verbose(0) << "What's the desired bond order for TopDown: ";
+        cin >> Order2;
+        Scheme = Combined;
+      break;
+  };
+  if (mol->first->next != mol->last) {  // there are bonds
+    start = clock();
+    mol->FragmentMolecule((ofstream *)&cout, Order1, Order2, Scheme, configuration, CutCyclic);
+    end = clock();
+    cout << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+  } else 
+    cout << Verbose(0) << "Connection matrix has not yet been generated!" << endl;
+};
+
+/********************************************** Test routine **************************************/
+
+/** Is called always as option 'T' in the menu.
+ */
+void testroutine(molecule *mol)
+{
+  // the current test routine checks the functionality of the KeySet&Graph concept:
+  // We want to have a multiindex (the KeySet) describing a unique subgraph
+  atom *Walker = mol->start;
+  int i, comp, counter=0;
+  
+  // generate some KeySets
+  cout << "Generating KeySets." << endl;
+  KeySet TestSets[mol->AtomCount+1];
+  i=1;
+  while (Walker->next != mol->end) {
+    Walker = Walker->next;
+    for (int j=0;j<i;j++) {
+      TestSets[j].insert(Walker->nr);
+    }
+    i++;
+  }
+  cout << "Testing insertion of already present item in KeySets." << endl;
+  KeySetTestPair test;
+  test = TestSets[mol->AtomCount-1].insert(Walker->nr); 
+  if (test.second) {
+    cout << Verbose(1) << "Insertion worked?!" << endl;
+  } else {
+    cout << Verbose(1) << "Insertion rejected: Present object is " << (*test.first) << "." << endl;
+  }
+  TestSets[mol->AtomCount].insert(mol->end->previous->nr);
+  TestSets[mol->AtomCount].insert(mol->end->previous->previous->previous->nr);
+
+  // constructing Graph structure  
+  cout << "Generating Subgraph class." << endl;
+  Graph Subgraphs;
+
+  // insert KeySets into Subgraphs
+  cout << "Inserting KeySets into Subgraph class." << endl;
+  for (int j=0;j<mol->AtomCount;j++) {
+    Subgraphs.insert(GraphPair (TestSets[j],pair<int, double>(counter++, 1.)));
+  }
+  cout << "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) {
+    cout << Verbose(1) << "Insertion worked?!" << endl;
+  } else {
+    cout << Verbose(1) << "Insertion rejected: Present object is " << (*(test2.first)).second.first << "." << endl;
+  }
+  
+  // show graphs
+  cout << "Showing Subgraph's contents, checking that it's sorted." << endl;
+  Graph::iterator A = Subgraphs.begin();
+  while (A !=  Subgraphs.end()) {
+    cout << (*A).second.first << ": ";
+    KeySet::iterator key = (*A).first.begin();
+    comp = -1;
+    while (key != (*A).first.end()) {
+      if ((*key) > comp)
+        cout << (*key) << " ";
+      else 
+        cout << (*key) << "! ";
+      comp = (*key);
+      key++;
+    }
+    cout << endl;
+    A++;
+  }
+};
+
+/********************************************** Main routine **************************************/
+ 
+int main(int argc, char **argv)
+{
+  periodentafel *periode = new periodentafel; // and a period table of all elements
+  molecule *mol = new molecule(periode);    // first we need an empty molecule
+  double tmp1;
+  double bond, min_bond;
+  atom *first, *second;
+  element *finder;
+  char choice;  // menu choice char
+  vector x,y,z,n;  // coordinates for absolute point in cell volume
+	double *factor;	// unit factor if desired
+  bool valid; // flag if input was valid or not
+  config configuration;
+  ifstream test;
+  ofstream output;
+  string line;
+  char filename[255];
+  int flag = 1;
+  int Z;
+  int j, axis, count, faktor;
+  int MinimumRingSize = -1;
+  enum BondOrderScheme Scheme = NoScheme;
+  enum CutCyclicBond CutCyclic;
+  MoleculeLeafClass *Subgraphs = NULL;
+  clock_t start,end;
+  element **Elements;
+  vector **Vectors;
+
+  // Greetings
+  cout << Verbose(0) << "Molecuilder v1" << endl << endl;
+  cout << Verbose(0) << "Build your own molecule position set." << endl;
+
+  // load element list
+  periode->LoadPeriodentafel();
+  cout << Verbose(1) << "Element list loaded." << endl;  
+  
+  // parse config file if given
+  if (argc >= 2) { // config file specified as option
+  	cout << Verbose(0) << "Config file given." << endl;
+    test.open(argv[1], ios::in);
+    if (test == NULL) {
+      cout << Verbose(1) << "Specified config file not found." << endl;
+      //return (1);
+    } else {
+      cout << Verbose(1) << "Specified config file found, parsing ...";
+      switch (configuration.TestSyntax(&test, periode, mol)) {
+        case 1:
+          cout << "new syntax." << endl;
+          configuration.Load(&test, periode, mol);
+          break;
+        case 0:
+          cout << "old syntax." << endl;
+          configuration.LoadOld(&test, periode, mol);
+          break;
+        default:
+          cout << "unknown syntax or empty configuration file." << endl;
+          //return(1);
+      }
+      test.close();
+    }
+  }
+  // command line stuff
+  if (argc > 2) {
+    cout << Verbose(0) << "Recognized command line argument: " << argv[2][1] << ".\n";
+    switch(argv[2][1]) {
+      case 't':
+        cout << Verbose(1) << "Translating all ions to new origin." << endl;
+        for (int i=0;i<3;i++)
+          x.x[i] = atof(argv[3+i]);
+        mol->Translate((const vector *)&x);
+        break;
+      case 'a':
+        cout << Verbose(1) << "Adding new atom." << endl;
+        first = new atom;
+        for (int i=0;i<3;i++)
+          first->x.x[i] = atof(argv[4+i]);
+        finder = periode->start;
+        while (finder != periode->end) {
+          finder = finder->next;
+          if (strncmp(finder->symbol,argv[3],3) == 0) {
+            first->type = finder;
+            break;
+          }
+        }
+        mol->AddAtom(first);  // add to molecule
+        break;
+      case 's':
+        j = -1;
+        cout << Verbose(1) << "Scaling all ion positions by factor." << endl;
+        factor = (double *) Malloc(sizeof(double)*NDIM, "main: *factor");
+        factor[0] = atof(argv[3]);
+        factor[1] = (argc >=4) ? atof(argv[4]) : atof(argv[3]); 
+        factor[2] = (argc >=5) ? atof(argv[5]) : atof(argv[3]); 
+        mol->Scale(&factor);
+        for (int i=0;i<3;i++) {
+          j += i+1;
+          x.x[i] = atof(argv[3+i]);
+          mol->cell_size[j]*=factor[i];
+        }
+        Free((void **)&factor, "main: *factor");
+        break;
+      case 'c':
+        j = -1;
+        cout << Verbose(1) << "Centering atoms in config file within given additional boundary." << endl;
+        // make every coordinate positive
+        mol->CenterEdge((ofstream *)&cout, &x);
+        // update Box of atoms by boundary
+        mol->SetBoxDimension(&x);
+        // translate each coordinate by boundary
+        j=-1;
+        for (int i=0;i<3;i++) {
+          j += i+1;
+          x.x[i] = atof(argv[3+i]);
+          mol->cell_size[j] += x.x[i]*2.;
+        }
+        mol->Translate((const vector *)&x);
+        break;
+      case 'r':
+        cout << Verbose(1) << "Converting config file from supposed old to new syntax." << endl;
+        break;
+      case 'p':
+        cout << Verbose(1) << "Parsing xyz file for new atoms." << endl;
+        if (!mol->AddXYZFile(argv[3]))
+          cout << Verbose(2) << "File not found." << endl;
+        else
+          cout << Verbose(2) << "File found and parsed." << endl;
+        break;
+      case 'f':
+        int i,j;
+        flag = 0;
+        if (argc > 4) {
+          cout << Verbose(0) << "Creating connection matrix..." << endl;
+          start = clock();
+          mol->CreateAdjacencyList((ofstream *)&cout, atof(argv[3]));
+          cout << Verbose(0) << "Fragmenting molecule with current connection matrix ..." << endl;
+          cout << Verbose(0) << "What's the desired bond scheme [(B)ottomUp/(T)opDown/(A)NOVA/(C)ombined]: ";
+          CutCyclic = SaturateBond;
+          switch (argv[5][0]) {
+            default:
+                Scheme = NoScheme;
+              break;
+            case 'B':
+              CutCyclic = KeepBond;
+            case 'b':
+                Scheme = BottomUp;
+                i = atoi(argv[4]);
+                j = 0;
+              break;
+            case 'T':
+              CutCyclic = KeepBond;
+            case 't':
+                Scheme = TopDown;
+                i = 0;
+                j = atoi(argv[4]);
+              break;
+            case 'A':
+              CutCyclic = KeepBond;
+            case 'a':
+                Scheme = ANOVA;
+                i = atoi(argv[4]);
+                j = 0;
+              break;
+            case 'C':
+              CutCyclic = KeepBond;
+            case 'c':
+                if (argc > 5) {
+                  i = atoi(argv[4]);
+                  j = atoi(argv[6]);
+                  Scheme = Combined;
+                }
+                else
+                  cerr << "Missing second bond order for TopDown fragmentation in combined approach." << endl;
+              break;
+          };
+          if (mol->first->next != mol->last) {
+            mol->FragmentMolecule((ofstream *)&cout, i, j, Scheme, &configuration, CutCyclic);
+          }
+          end = clock();
+          cout << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+        }
+        break;                
+      default:
+        break;
+    }
+    if (flag) {
+      mol->CountElements();  // this is a bugfix, atoms should should actually be added correctly to this fragment 
+      mol->CalculateOrbitals(configuration);
+      configuration.InitMaxMinStopStep = configuration.MaxMinStopStep = configuration.MaxPsiDouble;
+      if (argc >= 1)
+        output.open(argv[1], ios::trunc);
+      if (!output)
+        output.open("main_pcp_linux", ios::trunc);
+      if (configuration.Save(&output, periode, mol))
+        cout << Verbose(1) << "Saving of config file successful." << endl;
+      else
+        cout << Verbose(1) << "Saving of config file failed." << endl;
+      output.close();
+      output.clear();
+      // and save to xyz file
+      if (argc >= 1) {
+        strcpy(filename, argv[1]);
+        strcat(filename, ".xyz");
+        output.open(filename, ios::trunc);
+      }
+      if (output == NULL) {
+        strcpy(filename,"main_pcp_linux");
+        strcat(filename, ".xyz");
+        output.open(filename, ios::trunc);
+      } 
+      if (mol->OutputXYZ(&output))
+        cout << Verbose(0) << "Saving of XYZ file successful." << endl;
+      else
+        cout << Verbose(0) << "Saving of XYZ file failed." << endl;
+      output.close();
+      output.clear();
+    }
+    delete(mol);
+    delete(periode);
+    return (0);
+  }
+
+  
+  // General stuff
+  if (mol->cell_size[0] == 0.) {
+    cout << Verbose(0) << "enter lower triadiagonal form of basis matrix" << endl << endl;
+    for (int i=0;i<6;i++) {
+      cout << Verbose(1) << "Cell size" << i << ": ";
+      cin >> mol->cell_size[i];
+    }
+  }
+
+  // now the main construction loop
+  cout << Verbose(0) << endl << "Now comes the real construction..." << endl;
+  do {    
+    cout << Verbose(0) << endl << endl;
+    cout << Verbose(0) << "============Element list=======================" << endl;
+    mol->Checkout((ofstream *)&cout);
+    cout << Verbose(0) << "============Atom list==========================" << endl;
+    mol->Output((ofstream *)&cout);
+    cout << Verbose(0) << "============Menu===============================" << endl;
+    cout << Verbose(0) << "a - add an atom" << endl;
+    cout << Verbose(0) << "r - remove an atom" << endl;
+    cout << Verbose(0) << "b - scale a bond between atoms" << endl;
+    cout << Verbose(0) << "u - change an atoms element" << endl;
+    cout << Verbose(0) << "l - measure lengths, angles, ... for an atom" << endl;
+    cout << Verbose(0) << "-----------------------------------------------" << endl;
+    cout << Verbose(0) << "p - Parse xyz file" << endl;
+    cout << Verbose(0) << "e - edit the current configuration" << endl;
+    cout << Verbose(0) << "o - create connection matrix" << endl;
+    cout << Verbose(0) << "f - fragment molecule many-body bond order style" << endl;
+    cout << Verbose(0) << "-----------------------------------------------" << endl;
+    cout << Verbose(0) << "d - duplicate molecule/periodic cell" << endl;
+    cout << Verbose(0) << "i - realign molecule" << endl; 
+    cout << Verbose(0) << "m - mirror all molecules" << endl; 
+    cout << Verbose(0) << "t - translate molecule by vector" << endl;
+    cout << Verbose(0) << "c - scale by unit transformation" << endl;
+    cout << Verbose(0) << "g - center atoms in box" << endl;
+    cout << Verbose(0) << "-----------------------------------------------" << endl;
+    cout << Verbose(0) << "s - save current setup to config file" << endl;
+    cout << Verbose(0) << "T - call the current test routine" << endl;
+    cout << Verbose(0) << "q - quit" << endl;
+    cout << Verbose(0) << "===============================================" << endl;
+    cout << Verbose(0) << "Input: ";
+    cin >> choice;
+    
+    switch (choice) {
+      default:
+      case 'q': // quit 
+        break;
+        
+      case 'a': // add atom
+        AddAtoms(periode, mol);
+        choice = 'a'; 
+        break;
+      
+      case 'd': // duplicate the periodic cell along a given axis, given times
+        cout << Verbose(0) << "State the axis [(+-)123]: ";
+        cin >> axis;
+        cout << Verbose(0) << "State the factor: ";
+        cin >> faktor;
+        
+        mol->CountAtoms((ofstream *)&cout);  // recount atoms
+        if (mol->AtomCount != 0) {  // if there is more than none
+          count = mol->AtomCount;   // is changed becausing of adding, thus has to be stored away beforehand
+          Elements = (element **) Malloc(sizeof(element *)*count, "main: duplicateCell - **Elements");
+          Vectors = (vector **) Malloc(sizeof(vector *)*count, "main: duplicateCell - **Vectors");
+          j = 0;
+          first = mol->start;
+          while (first->next != mol->end) {  // make a list of all atoms with coordinates and element
+            first = first->next;
+            Elements[j] = first->type;
+            Vectors[j] = &first->x;
+            j++;
+          }
+          if (count != j)
+            cout << Verbose(0) << "ERROR: 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
+          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
+            for (int k=0;k<count;k++) { // go through every atom of the original cell
+              first = new atom(); // create a new body
+              first->x.CopyVector(Vectors[k]);  // use coordinate of original atom
+              first->x.AddVector(&x);      // translate the coordinates
+              first->type = Elements[k];  // insert original element
+              mol->AddAtom(first);        // and add to the molecule (which increments ElementsInMolecule, AtomCount, ...)
+            }
+          }
+          if (mol->first->next != mol->last) // if connect matrix is present already, redo it
+            mol->CreateAdjacencyList((ofstream *)&cout, mol->BondDistance);
+          // free memory
+          Free((void **)&Elements, "main: duplicateCell - **Elements");
+          Free((void **)&Vectors, "main: duplicateCell - **Vectors");
+          // correct cell size
+          if (axis < 0) { // if sign was negative, we have to translate everything
+            x.Zero();
+            x.AddVector(&y);
+            x.Scale(-(faktor-1));
+            mol->Translate(&x);
+          }
+          mol->cell_size[(abs(axis) == 2) ? 2 : ((abs(axis) == 3) ? 5 : 0)] *= faktor; 
+        }
+        break;
+      
+      case 'g': // center the atoms
+        CenterAtoms(mol);
+        break;
+        
+      case 'b': // scale a bond
+        cout << Verbose(0) << "Scaling bond length between two atoms." << endl;
+        first = mol->AskAtom("Enter first (fixed) atom: ");
+        second = mol->AskAtom("Enter second (shifting) atom: ");
+        min_bond = 0.;
+        for (int i=0;i<3;i++)
+          min_bond += (first->x.x[i]-second->x.x[i])*(first->x.x[i] - second->x.x[i]);
+        min_bond = sqrt(min_bond);
+        cout << Verbose(0) << "Current Bond length between " << first->type->name << " Atom " << first->nr << " and " << second->type->name << " Atom " << second->nr << ": " << min_bond << " a.u." << endl;
+        cout << Verbose(0) << "Enter new bond length [a.u.]: ";
+        cin >> bond;
+        for (int i=0;i<3;i++) {
+          second->x.x[i] -= (second->x.x[i]-first->x.x[i])/min_bond*(min_bond-bond);
+        }
+        //cout << Verbose(0) << "New coordinates of Atom " << second->nr << " are: ";
+        //second->Output(second->type->No, 1, (ofstream *)&cout);       
+        break;
+
+      case 'i': // align all atoms 
+        AlignAtoms(periode, mol);
+        break;
+
+      case 'm': // mirror atoms along a given axis
+        MirrorAtoms(mol);
+        break;
+       
+      case 't': // translate all atoms
+	     cout << Verbose(0) << "Enter translation vector." << endl;       
+	     x.AskPosition(mol->cell_size,0);
+       mol->Translate((const vector *)&x);
+	     break;
+  
+      case 'e': // edit each field of the configuration
+       configuration.Edit(mol);
+       break;
+	
+      case 'c': // unit scaling of the metric 
+    	 cout << Verbose(0) << "Enter three factors: ";
+       factor = (double *) Malloc(sizeof(double)*NDIM, "main: *factor");
+       cin >> factor[0];
+       cin >> factor[1];
+       cin >> factor[2];
+       valid = true;
+       mol->Scale(&factor);
+	     Free((void **)&factor, "main: *factor");
+       break;
+			 
+      case 'r': // remove atom
+        RemoveAtoms(mol);        
+        break;
+        
+      case 'l': // measure distances or angles
+        MeasureAtoms(periode, mol);
+        break;
+
+      case 'p': // parse and XYZ file
+        cout << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
+        do {
+          cout << Verbose(0) << "Enter file name: ";
+          cin >> filename;
+        } while (!mol->AddXYZFile(filename));
+        break;
+
+      case 'o': // create the connection matrix
+        cout << Verbose(0) << "What's the maximum bond distance: ";
+        cin >> tmp1;
+        start = clock();
+        mol->CreateAdjacencyList((ofstream *)&cout, tmp1);
+        //mol->CreateListOfBondsPerAtom((ofstream *)&cout);
+        Subgraphs = mol->DepthFirstSearchAnalysis((ofstream *)&cout, false, MinimumRingSize);
+        while (Subgraphs->next != NULL) {
+          Subgraphs = Subgraphs->next;
+          delete(Subgraphs->previous);
+        }
+        delete(Subgraphs);    // we don't need the list here, so free everything
+        Subgraphs = NULL;
+        end = clock();
+        cout << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+        break;
+        
+      case 'f':
+        FragmentAtoms(mol, &configuration);
+      	break;
+        
+      case 'u': // change an atom's element
+        first = NULL;
+        do {
+          cout << Verbose(0) << "Change the element of which atom: ";
+          cin >> Z;
+        } while ((first = mol->FindAtom(Z)) == NULL);
+        cout << Verbose(0) << "New element by atomic number Z: ";        
+        cin >> Z;
+        first->type = periode->FindElement(Z);
+        cout << Verbose(0) << "Atom " << first->nr << "'s element is " << first->type->name << "." << endl;    
+        break;
+        
+      case 'T':
+        testroutine(mol);
+        break;
+      
+      case 's': // save to config file
+        // get correct valence orbitals
+        mol->CalculateOrbitals(configuration);
+        configuration.InitMaxMinStopStep = configuration.MaxMinStopStep = configuration.MaxPsiDouble;
+        if (argc >= 1)
+          output.open(argv[1], ios::trunc);
+        if (output == NULL)
+          output.open("main_pcp_linux", ios::trunc);
+        if (configuration.Save(&output, periode, mol))
+          cout << Verbose(0) << "Saving of config file successful." << endl;
+        else
+          cout << Verbose(0) << "Saving of config file failed." << endl;
+        output.close();
+        output.clear();
+        // and save to xyz file
+        if (argc >= 1) {
+          strcpy(filename, argv[1]);
+          strcat(filename, ".xyz");
+          output.open(filename, ios::trunc);
+        }
+        if (output == NULL) {
+          strcpy(filename,"main_pcp_linux");
+          strcat(filename, ".xyz");
+          output.open(filename, ios::trunc);
+        } 
+        if (mol->OutputXYZ(&output))
+          cout << Verbose(0) << "Saving of XYZ file successful." << endl;
+        else
+          cout << Verbose(0) << "Saving of XYZ file failed." << endl;
+        output.close();
+        output.clear();
+        break;
+    };
+  } while (choice != 'q');
+  
+  // save element data base
+  if (periode->StorePeriodentafel())
+    cout << Verbose(0) << "Saving of elements.db successful." << endl;
+  else
+    cout << Verbose(0) << "Saving of elements.db failed." << endl;
+
+  // Free all
+  if (Subgraphs != NULL) {  // free disconnected subgraph list of DFS analysis was performed
+    while (Subgraphs->next != NULL) {
+      Subgraphs = Subgraphs->next;
+      delete(Subgraphs->previous);
+    }
+    delete(Subgraphs);
+  }
+  delete(mol);
+  delete(periode);
+  return (0);
+}
+
+/********************************************** E N D **************************************************/
Index: molecuilder/src/config.cpp
===================================================================
--- molecuilder/src/config.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/config.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,1134 @@
+/** \file config.cpp
+ * 
+ * Function implementations for the class config.
+ * 
+ */
+
+#include "molecules.hpp"
+
+/************************************* Functions for class config ***************************/
+
+/** Constructor for config file class.
+ */
+config::config()
+{
+  mainname = (char *) MallocString(sizeof(char)*255,"config constructor: mainname");
+  defaultpath = (char *) MallocString(sizeof(char)*255,"config constructor: mainname");
+  pseudopotpath = (char *) MallocString(sizeof(char)*255,"config constructor: mainname");
+  strcpy(mainname,"pcp");
+  strcpy(defaultpath,"not specified                                                                                                                                                                                                                                               ");
+  strcpy(pseudopotpath,"not specified                                                                                                                                                                                                                                               ");
+  
+  ProcPEGamma=8;
+  ProcPEPsi=1;
+  DoOutVis=0;
+  DoOutMes=1;
+  DoOutNICS=0;
+  DoOutOrbitals=0;
+  DoOutCurrent=0;
+  DoPerturbation=0;
+  DoFullCurrent=0;
+  CommonWannier=0;
+  SawtoothStart=0.01;
+  VectorPlane=0;
+  VectorCut=0;
+  UseAddGramSch=1;
+  Seed=1;
+  
+  MaxOuterStep=0;
+  Deltat=0;
+  OutVisStep=10;
+  OutSrcStep=5;
+  TargetTemp=0.00095004455;
+  ScaleTempStep=25;
+  MaxPsiStep=0;
+  EpsWannier=1e-7;
+  
+  MaxMinStep=100;
+  RelEpsTotalEnergy=1e-7;
+  RelEpsKineticEnergy=1e-5;
+  MaxMinStopStep=1;
+  MaxMinGapStopStep=0;
+  MaxInitMinStep=100;
+  InitRelEpsTotalEnergy=1e-5;
+  InitRelEpsKineticEnergy=1e-4;
+  InitMaxMinStopStep=1;
+  InitMaxMinGapStopStep=0;
+  
+  //BoxLength[NDIM*NDIM];
+  
+  ECut=128.;
+  MaxLevel=5;
+  RiemannTensor=0;
+  LevRFactor=0;
+  RiemannLevel=0;
+  Lev0Factor=2;
+  RTActualUse=0;
+  PsiType=0;
+  MaxPsiDouble=0;
+  PsiMaxNoUp=0;
+  PsiMaxNoDown=0;
+  AddPsis=0;
+  
+  RCut=20.;
+  StructOpt=0;
+  IsAngstroem=1;
+  RelativeCoord=0;
+  MaxTypes=0;
+};
+
+
+/** Destructor for config file class.
+ */
+config::~config()
+{
+  Free((void **)&mainname, "config::~config: *mainname");
+  Free((void **)&defaultpath, "config::~config: *defaultpath");
+  Free((void **)&pseudopotpath, "config::~config: *pseudopotpath");
+};
+
+/** Displays menu for editing each entry of the config file.
+ * Nothing fancy here, just lots of cout << Verbose(0)s for the menu and a switch/case
+ * for each entry of the config file structure.
+ */
+void config::Edit(molecule *mol)
+{
+  char choice;
+  
+  do {
+    cout << Verbose(0) << "===========EDIT CONFIGURATION============================" << endl;
+    cout << Verbose(0) << " A - mainname (prefix for all runtime files)" << endl;
+    cout << Verbose(0) << " B - Default path (for runtime files)" << endl;
+    cout << Verbose(0) << " C - Path of pseudopotential files" << endl;
+    cout << Verbose(0) << " D - Number of coefficient sharing processes" << endl;
+    cout << Verbose(0) << " E - Number of wave function sharing processes" << endl;
+    cout << Verbose(0) << " F - 0: Don't output density for OpenDX, 1: do" << endl;
+    cout << Verbose(0) << " G - 0: Don't output physical data, 1: do" << endl;
+    cout << Verbose(0) << " H - 0: Don't output densities of each unperturbed orbital for OpenDX, 1: do" << endl;
+    cout << Verbose(0) << " I - 0: Don't output current density for OpenDX, 1: do" << endl;
+    cout << Verbose(0) << " J - 0: Don't do the full current calculation, 1: do" << endl;
+    cout << Verbose(0) << " K - 0: Don't do perturbation calculation to obtain susceptibility and shielding, 1: do" << endl;
+    cout << 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;
+    cout << Verbose(0) << " M - Absolute begin of unphysical sawtooth transfer for position operator within cell" << endl;
+    cout << Verbose(0) << " N - (0,1,2) x,y,z-plane to do two-dimensional current vector cut" << endl;
+    cout << Verbose(0) << " O - Absolute position along vector cut axis for cut plane" << endl;
+    cout << Verbose(0) << " P - Additional Gram-Schmidt-Orthonormalization to stabilize numerics" << endl;
+    cout << Verbose(0) << " Q - Initial integer value of random number generator" << endl;
+    cout << Verbose(0) << " R - for perturbation 0, for structure optimization defines upper limit of iterations" << endl;
+    cout << Verbose(0) << " T - Output visual after ...th step" << endl;
+    cout << Verbose(0) << " U - Output source densities of wave functions after ...th step" << endl;
+    cout << Verbose(0) << " X - minimization iterations per wave function, if unsure leave at default value 0" << endl;
+    cout << Verbose(0) << " Y - tolerance value for total spread in iterative Jacobi diagonalization" << endl;
+    cout << Verbose(0) << " Z - Maximum number of minimization iterations" << endl;
+    cout << Verbose(0) << " a - Relative change in total energy to stop min. iteration" << endl;
+    cout << Verbose(0) << " b - Relative change in kinetic energy to stop min. iteration" << endl;
+    cout << Verbose(0) << " c - Check stop conditions every ..th step during min. iteration" << endl;
+    cout << Verbose(0) << " e - Maximum number of minimization iterations during initial level" << endl;
+    cout << Verbose(0) << " f - Relative change in total energy to stop min. iteration during initial level" << endl;
+    cout << Verbose(0) << " g - Relative change in kinetic energy to stop min. iteration during initial level" << endl;
+    cout << Verbose(0) << " h - Check stop conditions every ..th step during min. iteration during initial level" << endl;
+    cout << Verbose(0) << " j - six lower diagonal entries of matrix, defining the unit cell" << endl;
+    cout << Verbose(0) << " k - Energy cutoff of plane wave basis in Hartree" << endl;
+    cout << Verbose(0) << " l - Maximum number of levels in multi-level-ansatz" << endl;
+    cout << Verbose(0) << " m - Factor by which grid nodes increase between standard and upper level" << endl;
+    cout << Verbose(0) << " n - 0: Don't use RiemannTensor, 1: Do" << endl;
+    cout << Verbose(0) << " o - Factor by which grid nodes increase between Riemann and standard(?) level" << endl;
+    cout << Verbose(0) << " p - Number of Riemann levels" << endl;
+    cout << Verbose(0) << " r - 0: Don't Use RiemannTensor, 1: Do" << endl;
+    cout << Verbose(0) << " s - 0: Doubly occupied orbitals, 1: Up-/Down-Orbitals" << endl;
+    cout << Verbose(0) << " t - Number of orbitals (depends pn SpinType)" << endl;
+    cout << Verbose(0) << " u - Number of SpinUp orbitals (depends on SpinType)" << endl;
+    cout << Verbose(0) << " v - Number of SpinDown orbitals (depends on SpinType)" << endl;
+    cout << Verbose(0) << " w - Number of additional, unoccupied orbitals" << endl;
+    cout << Verbose(0) << " x - radial cutoff for ewald summation in Bohrradii" << endl;
+    cout << Verbose(0) << " y - 0: Don't do structure optimization beforehand, 1: Do" << endl;
+    cout << Verbose(0) << " z - 0: Units are in Bohr radii, 1: units are in Aengstrom" << endl;
+    cout << Verbose(0) << " i - 0: Coordinates given in file are absolute, 1: ... are relative to unit cell" << endl;
+    cout << Verbose(0) << "=========================================================" << endl;
+    cout << Verbose(0) << "INPUT: ";
+    cin >> choice;
+    
+    switch (choice) {
+        case 'A': // mainname
+          cout << Verbose(0) << "Old: " << config::mainname << "\t new: ";
+          cin >> config::mainname;
+          break;
+        case 'B': // defaultpath
+          cout << Verbose(0) << "Old: " << config::defaultpath << "\t new: ";
+          cin >> config::defaultpath;
+          break;
+        case 'C': // pseudopotpath
+          cout << Verbose(0) << "Old: " << config::pseudopotpath << "\t new: ";
+          cin >> config::pseudopotpath;
+          break;
+
+        case 'D': // ProcPEGamma
+          cout << Verbose(0) << "Old: " << config::ProcPEGamma << "\t new: ";
+          cin >> config::ProcPEGamma;
+          break;
+        case 'E': // ProcPEPsi
+          cout << Verbose(0) << "Old: " << config::ProcPEPsi << "\t new: ";
+          cin >> config::ProcPEPsi;
+          break;
+        case 'F': // DoOutVis
+          cout << Verbose(0) << "Old: " << config::DoOutVis << "\t new: ";
+          cin >> config::DoOutVis;
+          break;
+        case 'G': // DoOutMes
+          cout << Verbose(0) << "Old: " << config::DoOutMes << "\t new: ";
+          cin >> config::DoOutMes;
+          break;
+        case 'H': // DoOutOrbitals
+          cout << Verbose(0) << "Old: " << config::DoOutOrbitals << "\t new: ";
+          cin >> config::DoOutOrbitals;
+          break;
+        case 'I': // DoOutCurrent
+          cout << Verbose(0) << "Old: " << config::DoOutCurrent << "\t new: ";
+          cin >> config::DoOutCurrent;
+          break;
+        case 'J': // DoFullCurrent
+          cout << Verbose(0) << "Old: " << config::DoFullCurrent << "\t new: ";
+          cin >> config::DoFullCurrent;
+          break;
+        case 'K': // DoPerturbation
+          cout << Verbose(0) << "Old: " << config::DoPerturbation << "\t new: ";
+          cin >> config::DoPerturbation;
+          break;
+        case 'L': // CommonWannier
+          cout << Verbose(0) << "Old: " << config::CommonWannier << "\t new: ";
+          cin >> config::CommonWannier;
+          break;
+        case 'M': // SawtoothStart
+          cout << Verbose(0) << "Old: " << config::SawtoothStart << "\t new: ";
+          cin >> config::SawtoothStart;
+          break;
+        case 'N': // VectorPlane
+          cout << Verbose(0) << "Old: " << config::VectorPlane << "\t new: ";
+          cin >> config::VectorPlane;
+          break;
+        case 'O': // VectorCut
+          cout << Verbose(0) << "Old: " << config::VectorCut << "\t new: ";
+          cin >> config::VectorCut;
+          break;
+        case 'P': // UseAddGramSch
+          cout << Verbose(0) << "Old: " << config::UseAddGramSch << "\t new: ";
+          cin >> config::UseAddGramSch;
+          break;
+        case 'Q': // Seed
+          cout << Verbose(0) << "Old: " << config::Seed << "\t new: ";
+          cin >> config::Seed;
+          break;
+
+        case 'R': // MaxOuterStep
+          cout << Verbose(0) << "Old: " << config::MaxOuterStep << "\t new: ";
+          cin >> config::MaxOuterStep;
+          break;
+        case 'T': // OutVisStep
+          cout << Verbose(0) << "Old: " << config::OutVisStep << "\t new: ";
+          cin >> config::OutVisStep;
+          break;
+        case 'U': // OutSrcStep
+          cout << Verbose(0) << "Old: " << config::OutSrcStep << "\t new: ";
+          cin >> config::OutSrcStep;
+          break;
+        case 'X': // MaxPsiStep
+          cout << Verbose(0) << "Old: " << config::MaxPsiStep << "\t new: ";
+          cin >> config::MaxPsiStep;
+          break;
+        case 'Y': // EpsWannier
+          cout << Verbose(0) << "Old: " << config::EpsWannier << "\t new: ";
+          cin >> config::EpsWannier;
+          break;
+
+        case 'Z': // MaxMinStep
+          cout << Verbose(0) << "Old: " << config::MaxMinStep << "\t new: ";
+          cin >> config::MaxMinStep;
+          break;
+        case 'a': // RelEpsTotalEnergy
+          cout << Verbose(0) << "Old: " << config::RelEpsTotalEnergy << "\t new: ";
+          cin >> config::RelEpsTotalEnergy;
+          break;
+        case 'b': // RelEpsKineticEnergy
+          cout << Verbose(0) << "Old: " << config::RelEpsKineticEnergy << "\t new: ";
+          cin >> config::RelEpsKineticEnergy;
+          break;
+        case 'c': // MaxMinStopStep
+          cout << Verbose(0) << "Old: " << config::MaxMinStopStep << "\t new: ";
+          cin >> config::MaxMinStopStep;
+          break;
+        case 'e': // MaxInitMinStep
+          cout << Verbose(0) << "Old: " << config::MaxInitMinStep << "\t new: ";
+          cin >> config::MaxInitMinStep;
+          break;
+        case 'f': // InitRelEpsTotalEnergy
+          cout << Verbose(0) << "Old: " << config::InitRelEpsTotalEnergy << "\t new: ";
+          cin >> config::InitRelEpsTotalEnergy;
+          break;
+        case 'g': // InitRelEpsKineticEnergy
+          cout << Verbose(0) << "Old: " << config::InitRelEpsKineticEnergy << "\t new: ";
+          cin >> config::InitRelEpsKineticEnergy;
+          break;
+        case 'h': // InitMaxMinStopStep
+          cout << Verbose(0) << "Old: " << config::InitMaxMinStopStep << "\t new: ";
+          cin >> config::InitMaxMinStopStep;
+          break;
+        
+        case 'j': // BoxLength
+          cout << Verbose(0) << "enter lower triadiagonalo form of basis matrix" << endl << endl;
+          for (int i=0;i<6;i++) {
+            cout << Verbose(0) << "Cell size" << i << ": ";
+            cin >> mol->cell_size[i];
+          }
+          break;
+        
+        case 'k': // ECut
+          cout << Verbose(0) << "Old: " << config::ECut << "\t new: ";
+          cin >> config::ECut;
+          break;
+        case 'l': // MaxLevel
+          cout << Verbose(0) << "Old: " << config::MaxLevel << "\t new: ";
+          cin >> config::MaxLevel;
+          break;
+        case 'm': // RiemannTensor
+          cout << Verbose(0) << "Old: " << config::RiemannTensor << "\t new: ";
+          cin >> config::RiemannTensor;
+          break;
+        case 'n': // LevRFactor
+          cout << Verbose(0) << "Old: " << config::LevRFactor << "\t new: ";
+          cin >> config::LevRFactor;
+          break;
+        case 'o': // RiemannLevel
+          cout << Verbose(0) << "Old: " << config::RiemannLevel << "\t new: ";
+          cin >> config::RiemannLevel;
+          break;
+        case 'p': // Lev0Factor
+          cout << Verbose(0) << "Old: " << config::Lev0Factor << "\t new: ";
+          cin >> config::Lev0Factor;
+          break;
+        case 'r': // RTActualUse
+          cout << Verbose(0) << "Old: " << config::RTActualUse << "\t new: ";
+          cin >> config::RTActualUse;
+          break;
+        case 's': // PsiType
+          cout << Verbose(0) << "Old: " << config::PsiType << "\t new: ";
+          cin >> config::PsiType;
+          break;
+        case 't': // MaxPsiDouble
+          cout << Verbose(0) << "Old: " << config::MaxPsiDouble << "\t new: ";
+          cin >> config::MaxPsiDouble;
+          break;
+        case 'u': // PsiMaxNoUp
+          cout << Verbose(0) << "Old: " << config::PsiMaxNoUp << "\t new: ";
+          cin >> config::PsiMaxNoUp;
+          break;
+        case 'v': // PsiMaxNoDown
+          cout << Verbose(0) << "Old: " << config::PsiMaxNoDown << "\t new: ";
+          cin >> config::PsiMaxNoDown;
+          break;
+        case 'w': // AddPsis
+          cout << Verbose(0) << "Old: " << config::AddPsis << "\t new: ";
+          cin >> config::AddPsis;
+          break;
+
+        case 'x': // RCut
+          cout << Verbose(0) << "Old: " << config::RCut << "\t new: ";
+          cin >> config::RCut;
+          break;
+        case 'y': // StructOpt
+          cout << Verbose(0) << "Old: " << config::StructOpt << "\t new: ";
+          cin >> config::StructOpt;
+          break;
+        case 'z': // IsAngstroem
+          cout << Verbose(0) << "Old: " << config::IsAngstroem << "\t new: ";
+          cin >> config::IsAngstroem;
+          break;
+        case 'i': // RelativeCoord
+          cout << Verbose(0) << "Old: " << config::RelativeCoord << "\t new: ";
+          cin >> config::RelativeCoord;
+          break;
+    };
+  } while (choice != 'q');
+};
+
+/** Tests whether a given configuration file adhears to old or new syntax.
+ * \param *file input file stream being the opened config file
+ * \param *periode pointer to a periodentafel class with all elements
+ * \param *mol pointer to molecule containing all atoms of the molecule
+ * \return 0 - old syntax, 1 - new syntax, -1 - unknown syntax 
+ */
+int config::TestSyntax(ifstream *file, periodentafel *periode, molecule *mol)
+{
+  int test;
+  // search file for keyword: ProcPEGamma (new syntax)
+  if (ParseForParameter(1,file,"ProcPEGamma", 0, 1, 1, int_type, &test, 1, optional))
+    return 1;
+  // search file for keyword: ProcsGammaPsi (old syntax)
+  if (ParseForParameter(1,file,"ProcsGammaPsi", 0, 1, 1, int_type, &test, 1, optional))
+    return 0;
+  return -1;
+}
+
+/** Returns private config::IsAngstroem.
+ * \return IsAngstroem
+ */
+bool config::GetIsAngstroem() const
+{
+  return (IsAngstroem == 1);
+};
+
+/** Returns private config::*defaultpath.
+ * \return *defaultpath
+ */
+char * config::GetDefaultPath() const
+{
+  return defaultpath;
+};
+
+
+/** Returns private config::*defaultpath.
+ * \return *defaultpath
+ */
+void config::SetDefaultPath(const char *path)
+{
+  strcpy(defaultpath, path);
+};
+
+/** Initializes config file structure by loading elements from a give file.
+ * \param *file input file stream being the opened config file
+ * \param *periode pointer to a periodentafel class with all elements
+ * \param *mol pointer to molecule containing all atoms of the molecule 
+ */
+void config::Load(ifstream *file, periodentafel *periode, molecule *mol)
+{
+  // ParseParameters
+  
+  /* Oeffne Hauptparameterdatei */
+  int di;
+  double BoxLength[9];
+  string zeile;
+  string dummy;
+  element *elementhash[128];
+  char name[128];
+  char keyword[128];
+  int Z, No;
+  int verbose = 0;
+  
+  /* Namen einlesen */
+
+  ParseForParameter(verbose,file, "mainname", 0, 1, 1, string_type, (config::mainname), 1, critical);
+  ParseForParameter(verbose,file, "defaultpath", 0, 1, 1, string_type, (config::defaultpath), 1, critical);
+  ParseForParameter(verbose,file, "pseudopotpath", 0, 1, 1, string_type, (config::pseudopotpath), 1, critical);
+  ParseForParameter(verbose,file,"ProcPEGamma", 0, 1, 1, int_type, &(config::ProcPEGamma), 1, critical);
+  ParseForParameter(verbose,file,"ProcPEPsi", 0, 1, 1, int_type, &(config::ProcPEPsi), 1, critical);
+
+  if (!ParseForParameter(verbose,file,"Seed", 0, 1, 1, int_type, &(config::Seed), 1, optional))
+    config::Seed = 1;
+
+  if(!ParseForParameter(verbose,file,"DoOutOrbitals", 0, 1, 1, int_type, &(config::DoOutOrbitals), 1, optional)) {
+    config::DoOutOrbitals = 0;
+  } else {
+    if (config::DoOutOrbitals < 0) config::DoOutOrbitals = 0;
+    if (config::DoOutOrbitals > 1) config::DoOutOrbitals = 1;
+  }
+  ParseForParameter(verbose,file,"DoOutVis", 0, 1, 1, int_type, &(config::DoOutVis), 1, critical);
+  if (config::DoOutVis < 0) config::DoOutVis = 0;
+  if (config::DoOutVis > 1) config::DoOutVis = 1;
+  if (!ParseForParameter(verbose,file,"VectorPlane", 0, 1, 1, int_type, &(config::VectorPlane), 1, optional))
+    config::VectorPlane = -1;
+  if (!ParseForParameter(verbose,file,"VectorCut", 0, 1, 1, double_type, &(config::VectorCut), 1, optional))
+    config::VectorCut = 0.;
+  ParseForParameter(verbose,file,"DoOutMes", 0, 1, 1, int_type, &(config::DoOutMes), 1, critical);
+  if (config::DoOutMes < 0) config::DoOutMes = 0;
+  if (config::DoOutMes > 1) config::DoOutMes = 1;
+  if (!ParseForParameter(verbose,file,"DoOutCurr", 0, 1, 1, int_type, &(config::DoOutCurrent), 1, optional))
+    config::DoOutCurrent = 0;
+  if (config::DoOutCurrent < 0) config::DoOutCurrent = 0;
+  if (config::DoOutCurrent > 1) config::DoOutCurrent = 1; 
+  ParseForParameter(verbose,file,"AddGramSch", 0, 1, 1, int_type, &(config::UseAddGramSch), 1, critical);
+  if (config::UseAddGramSch < 0) config::UseAddGramSch = 0;
+  if (config::UseAddGramSch > 2) config::UseAddGramSch = 2;
+  if(!ParseForParameter(verbose,file,"CommonWannier", 0, 1, 1, int_type, &(config::CommonWannier), 1, optional)) {
+    config::CommonWannier = 0;
+  } else {
+    if (config::CommonWannier < 0) config::CommonWannier = 0;
+    if (config::CommonWannier > 4) config::CommonWannier = 4;
+  }
+  if(!ParseForParameter(verbose,file,"SawtoothStart", 0, 1, 1, double_type, &(config::SawtoothStart), 1, optional)) {
+    config::SawtoothStart = 0.01;
+  } else {
+    if (config::SawtoothStart < 0.) config::SawtoothStart = 0.;
+    if (config::SawtoothStart > 1.) config::SawtoothStart = 1.;
+  }
+  
+  ParseForParameter(verbose,file,"MaxOuterStep", 0, 1, 1, int_type, &(config::MaxOuterStep), 1, critical);
+  ParseForParameter(verbose,file,"Deltat", 0, 1, 1, double_type, &(config::Deltat), 1, optional);
+  ParseForParameter(verbose,file,"OutVisStep", 0, 1, 1, int_type, &(config::OutVisStep), 1, optional);
+  ParseForParameter(verbose,file,"OutSrcStep", 0, 1, 1, int_type, &(config::OutSrcStep), 1, optional);
+  ParseForParameter(verbose,file,"TargetTemp", 0, 1, 1, double_type, &(config::TargetTemp), 1, optional);
+  //ParseForParameter(verbose,file,"Thermostat", 0, 1, 1, int_type, &(config::ScaleTempStep), 1, optional);
+  if (!ParseForParameter(verbose,file,"EpsWannier", 0, 1, 1, double_type, &(config::EpsWannier), 1, optional))
+    config::EpsWannier = 1e-8;
+  
+  // stop conditions
+  //if (config::MaxOuterStep <= 0) config::MaxOuterStep = 1;
+  ParseForParameter(verbose,file,"MaxPsiStep", 0, 1, 1, int_type, &(config::MaxPsiStep), 1, critical);
+  if (config::MaxPsiStep <= 0) config::MaxPsiStep = 3;
+  
+  ParseForParameter(verbose,file,"MaxMinStep", 0, 1, 1, int_type, &(config::MaxMinStep), 1, critical);
+  ParseForParameter(verbose,file,"RelEpsTotalE", 0, 1, 1, double_type, &(config::RelEpsTotalEnergy), 1, critical);
+  ParseForParameter(verbose,file,"RelEpsKineticE", 0, 1, 1, double_type, &(config::RelEpsKineticEnergy), 1, critical);
+  ParseForParameter(verbose,file,"MaxMinStopStep", 0, 1, 1, int_type, &(config::MaxMinStopStep), 1, critical);
+  ParseForParameter(verbose,file,"MaxMinGapStopStep", 0, 1, 1, int_type, &(config::MaxMinGapStopStep), 1, critical);
+  if (config::MaxMinStep <= 0) config::MaxMinStep = config::MaxPsiStep;
+  if (config::MaxMinStopStep < 1) config::MaxMinStopStep = 1;
+  if (config::MaxMinGapStopStep < 1) config::MaxMinGapStopStep = 1;
+  
+  ParseForParameter(verbose,file,"MaxInitMinStep", 0, 1, 1, int_type, &(config::MaxInitMinStep), 1, critical);
+  ParseForParameter(verbose,file,"InitRelEpsTotalE", 0, 1, 1, double_type, &(config::InitRelEpsTotalEnergy), 1, critical);
+  ParseForParameter(verbose,file,"InitRelEpsKineticE", 0, 1, 1, double_type, &(config::InitRelEpsKineticEnergy), 1, critical);
+  ParseForParameter(verbose,file,"InitMaxMinStopStep", 0, 1, 1, int_type, &(config::InitMaxMinStopStep), 1, critical);
+  ParseForParameter(verbose,file,"InitMaxMinGapStopStep", 0, 1, 1, int_type, &(config::InitMaxMinGapStopStep), 1, critical);
+  if (config::MaxInitMinStep <= 0) config::MaxInitMinStep = config::MaxPsiStep;
+  if (config::InitMaxMinStopStep < 1) config::InitMaxMinStopStep = 1;
+  if (config::InitMaxMinGapStopStep < 1) config::InitMaxMinGapStopStep = 1;
+  
+  // Unit cell and magnetic field
+  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];
+  if (1) fprintf(stderr,"\n");
+
+  ParseForParameter(verbose,file,"DoPerturbation", 0, 1, 1, int_type, &(config::DoPerturbation), 1, optional);
+  ParseForParameter(verbose,file,"DoOutNICS", 0, 1, 1, int_type, &(config::DoOutNICS), 1, optional);
+  if (!ParseForParameter(verbose,file,"DoFullCurrent", 0, 1, 1, int_type, &(config::DoFullCurrent), 1, optional))
+    config::DoFullCurrent = 0;
+  if (config::DoFullCurrent < 0) config::DoFullCurrent = 0;
+  if (config::DoFullCurrent > 2) config::DoFullCurrent = 2; 
+  if (config::DoOutNICS < 0) config::DoOutNICS = 0;
+  if (config::DoOutNICS > 2) config::DoOutNICS = 2; 
+  if (config::DoPerturbation == 0) {
+    config::DoFullCurrent = 0;
+    config::DoOutNICS = 0;
+  }
+
+  ParseForParameter(verbose,file,"ECut", 0, 1, 1, double_type, &(config::ECut), 1, critical);
+  ParseForParameter(verbose,file,"MaxLevel", 0, 1, 1, int_type, &(config::MaxLevel), 1, critical);
+  ParseForParameter(verbose,file,"Level0Factor", 0, 1, 1, int_type, &(config::Lev0Factor), 1, critical);
+  if (config::Lev0Factor < 2) {
+    config::Lev0Factor = 2;
+  }
+  ParseForParameter(verbose,file,"RiemannTensor", 0, 1, 1, int_type, &di, 1, critical);
+  if (di >= 0 && di < 2) {
+    config::RiemannTensor = di;
+  } else {
+    fprintf(stderr, "0 <= RiemanTensor < 2: 0 UseNotRT, 1 UseRT");
+    exit(1); 
+  }
+  switch (config::RiemannTensor) {
+    case 0: //UseNoRT
+      if (config::MaxLevel < 2) {
+        config::MaxLevel = 2;
+      }
+      config::LevRFactor = 2;
+      config::RTActualUse = 0;
+      break;
+    case 1: // UseRT
+      if (config::MaxLevel < 3) {
+        config::MaxLevel = 3;
+      }
+      ParseForParameter(verbose,file,"RiemannLevel", 0, 1, 1, int_type, &(config::RiemannLevel), 1, critical);
+      if (config::RiemannLevel < 2) {
+        config::RiemannLevel = 2;
+      } 
+      if (config::RiemannLevel > config::MaxLevel-1) {
+        config::RiemannLevel = config::MaxLevel-1;
+      }
+      ParseForParameter(verbose,file,"LevRFactor", 0, 1, 1, int_type, &(config::LevRFactor), 1, critical);
+      if (config::LevRFactor < 2) {
+        config::LevRFactor = 2;
+      } 
+      config::Lev0Factor = 2;
+      config::RTActualUse = 2;
+      break;
+  }
+  ParseForParameter(verbose,file,"PsiType", 0, 1, 1, int_type, &di, 1, critical);
+  if (di >= 0 && di < 2) {
+    config::PsiType = di;
+  } else {
+    fprintf(stderr, "0 <= PsiType < 2: 0 UseSpinDouble, 1 UseSpinUpDown");
+    exit(1); 
+  }
+  switch (config::PsiType) {
+  case 0: // SpinDouble
+    ParseForParameter(verbose,file,"MaxPsiDouble", 0, 1, 1, int_type, &(config::MaxPsiDouble), 1, critical);
+    ParseForParameter(verbose,file,"AddPsis", 0, 1, 1, int_type, &(config::AddPsis), 1, optional);
+    break;
+  case 1: // SpinUpDown
+    if (config::ProcPEGamma % 2) config::ProcPEGamma*=2;
+    ParseForParameter(verbose,file,"PsiMaxNoUp", 0, 1, 1, int_type, &(config::PsiMaxNoUp), 1, critical);
+    ParseForParameter(verbose,file,"PsiMaxNoDown", 0, 1, 1, int_type, &(config::PsiMaxNoDown), 1, critical);
+    ParseForParameter(verbose,file,"AddPsis", 0, 1, 1, int_type, &(config::AddPsis), 1, optional);
+    break;
+  }
+  
+  // IonsInitRead
+  
+  ParseForParameter(verbose,file,"RCut", 0, 1, 1, double_type, &(config::RCut), 1, critical);
+  ParseForParameter(verbose,file,"IsAngstroem", 0, 1, 1, int_type, &(config::IsAngstroem), 1, critical);
+  ParseForParameter(verbose,file,"MaxTypes", 0, 1, 1, int_type, &(config::MaxTypes), 1, critical);
+  if (!ParseForParameter(verbose,file,"RelativeCoord", 0, 1, 1, int_type, &(config::RelativeCoord) , 1, optional))
+    config::RelativeCoord = 0;
+  if (!ParseForParameter(verbose,file,"StructOpt", 0, 1, 1, int_type, &(config::StructOpt), 1, optional))
+    config::StructOpt = 0;
+  for (int i=0; i < config::MaxTypes; i++) {
+    sprintf(name,"Ion_Type%i",i+1);
+    ParseForParameter(verbose,file, (const char*)name, 0, 1, 1, int_type, &No, 1, critical);
+    ParseForParameter(verbose,file, name, 0, 2, 1, int_type, &Z, 1, critical);
+    elementhash[i] = periode->FindElement(Z);
+    for(int j=0;j<No;j++) {
+      int repetition = 1; // which repeated keyword shall be read
+      sprintf(keyword,"%s_%i",name, j+1);
+      atom *neues = new atom();
+      // then parse for each atom the coordinates as often as present
+      while (ParseForParameter(verbose,file, keyword, 0, 1, 1, double_type, &neues->x.x[0], repetition, (repetition == 1) ? critical : optional) &&
+        ParseForParameter(verbose,file, keyword, 0, 2, 1, double_type, &neues->x.x[1], repetition, (repetition == 1) ? critical : optional) &&
+        ParseForParameter(verbose,file, keyword, 0, 3, 1, double_type, &neues->x.x[2], repetition, (repetition == 1) ? critical : optional))
+        repetition++;
+      repetition--;
+      cout << "Found " << repetition << " times of the keyword " << keyword << "." << endl;
+      ParseForParameter(verbose,file, keyword, 0, 1, 1, double_type, &neues->x.x[0], repetition,critical);
+      ParseForParameter(verbose,file, keyword, 0, 2, 1, double_type, &neues->x.x[1], repetition,critical);
+      ParseForParameter(verbose,file, keyword, 0, 3, 1, double_type, &neues->x.x[2], repetition,critical);
+      neues->type = elementhash[i]; // find element type
+      mol->AddAtom(neues);
+    }
+  }
+};
+
+/** Initializes config file structure by loading elements from a give file with old pcp syntax.
+ * \param *file input file stream being the opened config file with old pcp syntax
+ * \param *periode pointer to a periodentafel class with all elements
+ * \param *mol pointer to molecule containing all atoms of the molecule 
+ */
+void config::LoadOld(ifstream *file, periodentafel *periode, molecule *mol)
+{
+  // ParseParameters
+  
+  /* Oeffne Hauptparameterdatei */
+  int l, i, di;
+  double a,b;
+  double BoxLength[9];
+  string zeile;
+  string dummy;
+  element *elementhash[128];
+  int Z, No, AtomNo, found;
+  int verbose = 0;
+  
+  /* Namen einlesen */
+
+  ParseForParameter(verbose,file, "mainname", 0, 1, 1, string_type, (config::mainname), 1, critical);
+  ParseForParameter(verbose,file, "defaultpath", 0, 1, 1, string_type, (config::defaultpath), 1, critical);
+  ParseForParameter(verbose,file, "pseudopotpath", 0, 1, 1, string_type, (config::pseudopotpath), 1, critical);
+  ParseForParameter(verbose,file, "ProcsGammaPsi", 0, 1, 1, int_type, &(config::ProcPEGamma), 1, critical);
+  ParseForParameter(verbose,file, "ProcsGammaPsi", 0, 2, 1, int_type, &(config::ProcPEPsi), 1, critical);
+  config::Seed = 1;
+  config::DoOutOrbitals = 0;
+  ParseForParameter(verbose,file,"DoOutVis", 0, 1, 1, int_type, &(config::DoOutVis), 1, critical);
+  if (config::DoOutVis < 0) config::DoOutVis = 0;
+  if (config::DoOutVis > 1) config::DoOutVis = 1;
+  config::VectorPlane = -1;
+  config::VectorCut = 0.;
+  ParseForParameter(verbose,file,"DoOutMes", 0, 1, 1, int_type, &(config::DoOutMes), 1, critical);
+  if (config::DoOutMes < 0) config::DoOutMes = 0;
+  if (config::DoOutMes > 1) config::DoOutMes = 1;
+  config::DoOutCurrent = 0;
+  ParseForParameter(verbose,file,"AddGramSch", 0, 1, 1, int_type, &(config::UseAddGramSch), 1, critical);
+  if (config::UseAddGramSch < 0) config::UseAddGramSch = 0;
+  if (config::UseAddGramSch > 2) config::UseAddGramSch = 2;
+  config::CommonWannier = 0;
+  config::SawtoothStart = 0.01;
+
+  ParseForParameter(verbose,file,"MaxOuterStep", 0, 1, 1, double_type, &(config::MaxOuterStep), 1, critical);
+  ParseForParameter(verbose,file,"Deltat", 0, 1, 1, double_type, &(config::Deltat), 1, optional);
+  ParseForParameter(verbose,file,"VisOuterStep", 0, 1, 1, int_type, &(config::OutVisStep), 1, optional);
+  ParseForParameter(verbose,file,"VisSrcOuterStep", 0, 1, 1, int_type, &(config::OutSrcStep), 1, optional);
+  ParseForParameter(verbose,file,"TargetTemp", 0, 1, 1, double_type, &(config::TargetTemp), 1, optional);
+  ParseForParameter(verbose,file,"ScaleTempStep", 0, 1, 1, int_type, &(config::ScaleTempStep), 1, optional);
+  config::EpsWannier = 1e-8;
+  
+  // stop conditions
+  //if (config::MaxOuterStep <= 0) config::MaxOuterStep = 1;
+  ParseForParameter(verbose,file,"MaxPsiStep", 0, 1, 1, int_type, &(config::MaxPsiStep), 1, critical);
+  if (config::MaxPsiStep <= 0) config::MaxPsiStep = 3;
+  
+  ParseForParameter(verbose,file,"MaxMinStep", 0, 1, 1, int_type, &(config::MaxMinStep), 1, critical);
+  ParseForParameter(verbose,file,"MaxMinStep", 0, 2, 1, double_type, &(config::RelEpsTotalEnergy), 1, critical);
+  ParseForParameter(verbose,file,"MaxMinStep", 0, 3, 1, double_type, &(config::RelEpsKineticEnergy), 1, critical);
+  ParseForParameter(verbose,file,"MaxMinStep", 0, 4, 1, int_type, &(config::MaxMinStopStep), 1, critical);
+  if (config::MaxMinStep <= 0) config::MaxMinStep = config::MaxPsiStep;
+  if (config::MaxMinStopStep < 1) config::MaxMinStopStep = 1;
+  config::MaxMinGapStopStep = 1;
+  
+  ParseForParameter(verbose,file,"MaxInitMinStep", 0, 1, 1, int_type, &(config::MaxInitMinStep), 1, critical);
+  ParseForParameter(verbose,file,"MaxInitMinStep", 0, 2, 1, double_type, &(config::InitRelEpsTotalEnergy), 1, critical);
+  ParseForParameter(verbose,file,"MaxInitMinStep", 0, 3, 1, double_type, &(config::InitRelEpsKineticEnergy), 1, critical);
+  ParseForParameter(verbose,file,"MaxInitMinStep", 0, 4, 1, int_type, &(config::InitMaxMinStopStep), 1, critical);
+  if (config::MaxInitMinStep <= 0) config::MaxInitMinStep = config::MaxPsiStep;
+  if (config::InitMaxMinStopStep < 1) config::InitMaxMinStopStep = 1;
+  config::InitMaxMinGapStopStep = 1;
+
+  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];
+  if (1) fprintf(stderr,"\n");
+  config::DoPerturbation = 0;
+  config::DoFullCurrent = 0;
+
+  ParseForParameter(verbose,file,"ECut", 0, 1, 1, double_type, &(config::ECut), 1, critical);
+  ParseForParameter(verbose,file,"MaxLevel", 0, 1, 1, int_type, &(config::MaxLevel), 1, critical);
+  ParseForParameter(verbose,file,"Level0Factor", 0, 1, 1, int_type, &(config::Lev0Factor), 1, critical);
+  if (config::Lev0Factor < 2) {
+    config::Lev0Factor = 2;
+  }
+  ParseForParameter(verbose,file,"RiemannTensor", 0, 1, 1, int_type, &di, 1, critical);
+  if (di >= 0 && di < 2) {
+    config::RiemannTensor = di;
+  } else {
+    fprintf(stderr, "0 <= RiemanTensor < 2: 0 UseNotRT, 1 UseRT");
+    exit(1); 
+  }
+  switch (config::RiemannTensor) {
+    case 0: //UseNoRT
+      if (config::MaxLevel < 2) {
+        config::MaxLevel = 2;
+      }
+      config::LevRFactor = 2;
+      config::RTActualUse = 0;
+      break;
+    case 1: // UseRT
+      if (config::MaxLevel < 3) {
+        config::MaxLevel = 3;
+      }
+      ParseForParameter(verbose,file,"RiemannLevel", 0, 1, 1, int_type, &(config::RiemannLevel), 1, critical);
+      if (config::RiemannLevel < 2) {
+        config::RiemannLevel = 2;
+      } 
+      if (config::RiemannLevel > config::MaxLevel-1) {
+        config::RiemannLevel = config::MaxLevel-1;
+      }
+      ParseForParameter(verbose,file,"LevRFactor", 0, 1, 1, int_type, &(config::LevRFactor), 1, critical);
+      if (config::LevRFactor < 2) {
+        config::LevRFactor = 2;
+      } 
+      config::Lev0Factor = 2;
+      config::RTActualUse = 2;
+      break;
+  }
+  ParseForParameter(verbose,file,"PsiType", 0, 1, 1, int_type, &di, 1, critical);
+  if (di >= 0 && di < 2) {
+    config::PsiType = di;
+  } else {
+    fprintf(stderr, "0 <= PsiType < 2: 0 UseSpinDouble, 1 UseSpinUpDown");
+    exit(1); 
+  }
+  switch (config::PsiType) {
+  case 0: // SpinDouble
+    ParseForParameter(verbose,file,"MaxPsiDouble", 0, 1, 1, int_type, &(config::MaxPsiDouble), 1, critical);
+    config::AddPsis = 0;
+    break;
+  case 1: // SpinUpDown
+    if (config::ProcPEGamma % 2) config::ProcPEGamma*=2;
+    ParseForParameter(verbose,file,"MaxPsiUp", 0, 1, 1, int_type, &(config::PsiMaxNoUp), 1, critical);
+    ParseForParameter(verbose,file,"MaxPsiDown", 0, 1, 1, int_type, &(config::PsiMaxNoDown), 1, critical);
+    config::AddPsis = 0;
+    break;
+  }
+  
+  // IonsInitRead
+  
+  ParseForParameter(verbose,file,"RCut", 0, 1, 1, double_type, &(config::RCut), 1, critical);
+  ParseForParameter(verbose,file,"IsAngstroem", 0, 1, 1, int_type, &(config::IsAngstroem), 1, critical);
+  config::RelativeCoord = 0;
+  config::StructOpt = 0;
+
+  // Routine from builder.cpp
+  
+  
+  for (i=0;i<128;i++) elementhash[i] = NULL;
+  cout << Verbose(0) << "Parsing Ions ..." << endl;
+  No=0;
+  found = 0;
+  while (getline(*file,zeile,'\n')) {
+    if (zeile.find("Ions_Data") == 0) {
+      cout << Verbose(1) << "found Ions_Data...begin parsing" << endl;
+      found ++;
+    }
+    if (found > 0) {
+      if (zeile.find("Ions_Data") == 0) 
+        getline(*file,zeile,'\n'); // read next line and parse this one
+      istringstream input(zeile);
+      input >> AtomNo;  // number of atoms
+      input >> Z;       // atomic number
+      input >> a;
+      input >> l;
+      input >> l;
+      input >> b;     // element mass
+      elementhash[No] = periode->FindElement(Z);
+      cout << 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
+          cout << Verbose(2) << "Error: Too few items in ionic list of element" << elementhash[No] << "." << endl << "Exiting." << endl;
+          // return 1;
+        } else {
+          //cout << Verbose(2) << "Reading line: " << zeile << endl;
+        }
+        istringstream input2(zeile);
+        atom *neues = new atom();
+        input2 >> neues->x.x[0]; // x
+        input2 >> neues->x.x[1]; // y
+        input2 >> neues->x.x[2]; // z
+        input2 >> l;
+        neues->type = elementhash[No]; // find element type
+        mol->AddAtom(neues);
+      }
+      No++;
+    }
+  }   
+};
+
+/** Stores all elements of config structure from which they can be re-read.
+ * \param output open output *file stream to write to
+ * \param *periode pointer to a periodentafel class with all elements
+ * \param *mol pointer to molecule containing all atoms of the molecule 
+ */
+bool config::Save(ofstream *output, periodentafel *periode, molecule *mol) const
+{
+  bool result = true;
+	// bring MaxTypes up to date
+	mol->CountElements();
+  if (output != NULL) {
+    *output << "# ParallelCarParinello - main configuration file - created with molecuilder" << endl;
+    *output << endl;
+    *output << "mainname\t" << config::mainname << "\t# programm name (for runtime files)" << endl;
+    *output << "defaultpath\t" << config::defaultpath << "\t# where to put files during runtime" << endl;
+    *output << "pseudopotpath\t" << config::pseudopotpath << "\t# where to find pseudopotentials" << endl;
+    *output << endl;
+    *output << "ProcPEGamma\t" << config::ProcPEGamma << "\t# for parallel computing: share constants" << endl;
+    *output << "ProcPEPsi\t" << config::ProcPEPsi << "\t# for parallel computing: share wave functions" << endl;
+    *output << "DoOutVis\t" << config::DoOutVis << "\t# Output data for OpenDX" << endl;
+    *output << "DoOutMes\t" << config::DoOutMes << "\t# Output data for measurements" << endl;
+    *output << "DoOutOrbitals\t" << config::DoOutOrbitals << "\t# Output all Orbitals" << endl;
+    *output << "DoOutCurr\t" << config::DoOutCurrent << "\t# Ouput current density for OpenDx" << endl;
+    *output << "DoOutNICS\t" << config::DoOutNICS << "\t# Output Nucleus independent current shieldings" << endl;
+    *output << "DoPerturbation\t" << config::DoPerturbation << "\t# Do perturbation calculate and determine susceptibility and shielding" << endl;
+    *output << "DoFullCurrent\t" << config::DoFullCurrent << "\t# Do full perturbation" << endl;
+    *output << "CommonWannier\t" << config::CommonWannier << "\t# Put virtual centers at indivual orbits, all common, merged by variance, to grid point, to cell center" << endl;
+    *output << "SawtoothStart\t" << config::SawtoothStart << "\t# Absolute value for smooth transition at cell border " << endl;
+    *output << "VectorPlane\t" << config::VectorPlane << "\t# Cut plane axis (x, y or z: 0,1,2) for two-dim current vector plot" << endl;
+    *output << "VectorCut\t" << config::VectorCut << "\t# Cut plane axis value" << endl;
+    *output << "AddGramSch\t" << config::UseAddGramSch << "\t# Additional GramSchmidtOrtogonalization to be safe" << endl;
+    *output << "Seed\t\t" << config::Seed << "\t# initial value for random seed for Psi coefficients" << endl;
+    *output << endl;
+    *output << "MaxOuterStep\t" << config::MaxOuterStep << "\t# number of MolecularDynamics/Structure optimization steps" << endl;
+    *output << "Deltat\t" << config::Deltat << "\t# time per MD step" << endl;
+    *output << "OutVisStep\t" << config::OutVisStep << "\t# Output visual data every ...th step" << endl;
+    *output << "OutSrcStep\t" << config::OutSrcStep << "\t# Output \"restart\" data every ..th step" << endl;
+    *output << "TargetTemp\t" << config::TargetTemp << "\t# Target temperature" << endl;
+    *output << "MaxPsiStep\t" << config::MaxPsiStep << "\t# number of Minimisation steps per state (0 - default)" << endl;
+    *output << "EpsWannier\t" << config::EpsWannier << "\t# tolerance value for spread minimisation of orbitals" << endl;
+    *output << endl;
+    *output << "# Values specifying when to stop" << endl;
+    *output << "MaxMinStep\t" << config::MaxMinStep << "\t# Maximum number of steps" << endl;
+    *output << "RelEpsTotalE\t" << config::RelEpsTotalEnergy << "\t# relative change in total energy" << endl;
+    *output << "RelEpsKineticE\t" << config::RelEpsKineticEnergy << "\t# relative change in kinetic energy" << endl;
+    *output << "MaxMinStopStep\t" << config::MaxMinStopStep << "\t# check every ..th steps" << endl;
+    *output << "MaxMinGapStopStep\t" << config::MaxMinGapStopStep << "\t# check every ..th steps" << endl;
+    *output << endl;
+    *output << "# Values specifying when to stop for INIT, otherwise same as above" << endl;
+    *output << "MaxInitMinStep\t" << config::MaxInitMinStep << "\t# Maximum number of steps" << endl;
+    *output << "InitRelEpsTotalE\t" << config::InitRelEpsTotalEnergy << "\t# relative change in total energy" << endl;
+    *output << "InitRelEpsKineticE\t" << config::InitRelEpsKineticEnergy << "\t# relative change in kinetic energy" << endl;
+    *output << "InitMaxMinStopStep\t" << config::InitMaxMinStopStep << "\t# check every ..th steps" << endl;
+    *output << "InitMaxMinGapStopStep\t" << config::InitMaxMinGapStopStep << "\t# check every ..th steps" << endl;
+    *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;
+    // FIXME
+    *output << endl;
+    *output << "ECut\t\t" << config::ECut << "\t# energy cutoff for discretization in Hartrees" << endl;
+    *output << "MaxLevel\t" << config::MaxLevel << "\t# number of different levels in the code, >=2" << endl;
+    *output << "Level0Factor\t" << config::Lev0Factor << "\t# factor by which node number increases from S to 0 level" << endl;
+    *output << "RiemannTensor\t" << config::RiemannTensor << "\t# (Use metric)" << endl;
+    switch (config::RiemannTensor) {
+      case 0: //UseNoRT
+        break;
+      case 1: // UseRT
+        *output << "RiemannLevel\t" << config::RiemannLevel << "\t# Number of Riemann Levels" << endl;
+        *output << "LevRFactor\t" << config::LevRFactor << "\t# factor by which node number increases from 0 to R level from" << endl;
+        break;
+    }
+    *output << "PsiType\t\t" << config::PsiType << "\t# 0 - doubly occupied, 1 - SpinUp,SpinDown" << endl;
+    // write out both types for easier changing afterwards
+  //  switch (PsiType) {
+  //    case 0:
+        *output << "MaxPsiDouble\t" << config::MaxPsiDouble << "\t# here: specifying both maximum number of SpinUp- and -Down-states" << endl;
+  //      break;
+  //    case 1:
+        *output << "PsiMaxNoUp\t" << config::PsiMaxNoUp << "\t# here: specifying maximum number of SpinUp-states" << endl;
+        *output << "PsiMaxNoDown\t" << config::PsiMaxNoDown << "\t# here: specifying maximum number of SpinDown-states" << endl;
+  //      break;
+  //  }
+    *output << "AddPsis\t\t" << config::AddPsis << "\t# Additional unoccupied Psis for bandgap determination" << endl;
+    *output << endl;
+    *output << "RCut\t\t" << config::RCut << "\t# R-cut for the ewald summation" << endl;
+    *output << "StructOpt\t" << config::StructOpt << "\t# Do structure optimization beforehand" << endl;
+    *output << "IsAngstroem\t" << config::IsAngstroem << "\t# 0 - Bohr, 1 - Angstroem" << endl;
+    *output << "RelativeCoord\t" << config::RelativeCoord << "\t# whether ion coordinates are relative (1) or absolute (0)" << endl;
+    *output << "MaxTypes\t" << mol->ElementCount <<  "\t# maximum number of different ion types" << endl;
+    *output << endl;
+    result = result && mol->Checkout(output);
+    result = result && mol->Output(output);
+    return result;
+  } else
+    return false;
+};
+
+/** Reads parameter from a parsed file.
+ * The file is either parsed for a certain keyword or if null is given for
+ * the value in row yth and column xth. If the keyword was necessity#critical,
+ * then an error is thrown and the programme aborted.
+ * \warning value is modified (both in contents and position)!
+ * \param verbose 1 - print found value to stderr, 0 - don't
+ * \param file file to be parsed
+ * \param name Name of value in file (at least 3 chars!)
+ * \param sequential 1 - do not reset file pointer to begin of file, 0 - set to beginning 
+ *        (if file is sequentially parsed this can be way faster! However, beware of multiple values per line, as whole line is read -
+ *         best approach: 0 0 0 1 (not resetted only on last value of line) - and of yth, which is now
+ *         counted from this unresetted position!)
+ * \param xth Which among a number of parameters it is (in grid case it's row number as grid is read as a whole!)
+ * \param yth In grid case specifying column number, otherwise the yth \a name matching line
+ * \param type Type of the Parameter to be read
+ * \param value address of the value to be read (must have been allocated)
+ * \param repetition determines, if the keyword appears multiply in the config file, which repetition shall be parsed, i.e. 1 if not multiply
+ * \param critical necessity of this keyword being specified (optional, critical)
+ * \return 1 - found, 0 - not found
+ * \note Routine is taken from the pcp project and hack-a-slack adapted to C++
+ */
+int config::ParseForParameter(int verbose, ifstream *file, const char *name, int sequential, int const xth, int const yth, int type, void *value, int repetition, int critical) {
+  int i,j;  // loop variables
+  int length = 0, maxlength = -1;
+  long file_position = file->tellg(); // mark current position
+  char *dummy1, *dummy, *free_dummy;    // pointers in the line that is read in per step
+  dummy1 = free_dummy = (char *) Malloc(256 * sizeof(char), "config::ParseForParameter: *free_dummy");
+
+  //fprintf(stderr,"Parsing for %s\n",name);  
+  if (repetition == 0)
+    //Error(SomeError, "ParseForParameter(): argument repetition must not be 0!");
+    return 0;
+
+  int line = 0; // marks line where parameter was found
+  int found = (type >= grid) ? 0 : (-yth + 1);  // marks if yth parameter name was found
+  while((found != repetition)) {
+    dummy1 = dummy = free_dummy;
+    do {
+      file->getline(dummy1, 256); // Read the whole line
+      if (file->eof()) {
+        if ((critical) && (found == 0)) {
+          Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");
+          //Error(InitReading, name);
+          fprintf(stderr,"Error:InitReading, critical %s not found\n", name);
+          exit(255);
+        } else {
+          //if (!sequential)
+          file->clear();
+          file->seekg(file_position, ios::beg);  // rewind to start position
+          Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");          
+          return 0;
+        }
+      }
+      line++;
+    } while (((dummy1[0] == '#') || (dummy1[0] == '\n')) && dummy != NULL); // skip commentary and empty lines
+    
+    // C++ getline removes newline at end, thus re-add
+    if ((dummy1 != NULL) && (strchr(dummy1,'\n') == NULL)) {
+      i = strlen(dummy1);
+      dummy1[i] = '\n';
+      dummy1[i+1] = '\0';
+    }
+    //fprintf(stderr,"line ends at %i, newline at %i\n", strlen(dummy1), strchr(dummy1,'\n')-free_dummy);
+    if (dummy1 == NULL) {
+      if (verbose) fprintf(stderr,"Error reading line %i\n",line);
+    } else {
+      //fprintf(stderr,"Reading next line %i: %s\n", line, dummy1);
+    }
+    // Seek for possible end of keyword on line if given ...
+    if (name != NULL) {
+      dummy = strchr(dummy1,'\t');  // set dummy on first tab or space which ever's nearer
+      if (dummy == NULL) {
+        dummy = strchr(dummy1, ' ');  // if not found seek for space
+        while ((dummy != NULL) && ((*dummy == '\t') || (*dummy == ' ')))    // skip some more tabs and spaces if necessary
+          dummy++;
+      }
+      if (dummy == NULL) {
+        dummy = strchr(dummy1, '\n'); // set on line end then (whole line = keyword)
+        //fprintf(stderr,"Error: Cannot find tabs or spaces on line %i in search for %s\n", line, name);
+        //Free((void **)&free_dummy);
+        //Error(FileOpenParams, NULL);      
+      } else {
+        //fprintf(stderr,"found tab at %i\n",(char *)dummy-(char *)dummy1);
+      }
+    } else dummy = dummy1;
+    // ... and check if it is the keyword!
+    //fprintf(stderr,"name %p, dummy %i/%c, dummy1 %i/%c, strlen(name) %i\n", &name, dummy, *dummy, dummy1, *dummy1, strlen(name));
+    if ((name == NULL) || ((dummy-dummy1 >= 3) && (strncmp(dummy1, name, strlen(name)) == 0)) && ((unsigned int)(dummy-dummy1) == strlen(name))) {
+      found++; // found the parameter!
+      //fprintf(stderr,"found %s at line %i between %i and %i\n", name, line, dummy1, dummy);    
+      
+      if (found == repetition) {
+        for (i=0;i<xth;i++) { // i = rows
+          if (type >= grid) {
+            // grid structure means that grid starts on the next line, not right after keyword
+            dummy1 = dummy = free_dummy;
+            do {
+              file->getline(dummy1, 256); // Read the whole line, skip commentary and empty ones
+              if (file->eof()) {
+                if ((critical) && (found == 0)) {
+                  Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");
+                  //Error(InitReading, name);
+                  fprintf(stderr,"Error:InitReading, critical %s not found\n", name);
+                  exit(255);
+                } else {
+                  //if (!sequential)
+                  file->clear();
+                  file->seekg(file_position, ios::beg);  // rewind to start position
+                  Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");
+                  return 0;
+                }
+              }
+              line++;
+            } while ((dummy1[0] == '#') || (dummy1[0] == '\n'));
+            if (dummy1 == NULL){
+              if (verbose) fprintf(stderr,"Error reading line %i\n", line);
+            } else {
+              //fprintf(stderr,"Reading next line %i: %s\n", line, dummy1);
+            }
+          } else { // simple int, strings or doubles start in the same line
+            while ((*dummy == '\t') || (*dummy == ' '))   // skip interjacent tabs and spaces
+              dummy++;
+          }
+          // C++ getline removes newline at end, thus re-add
+          if ((dummy1 != NULL) && (strchr(dummy1,'\n') == NULL)) {
+            j = strlen(dummy1);
+            dummy1[j] = '\n';
+            dummy1[j+1] = '\0';
+          }
+  
+          int start = (type >= grid) ? 0 : yth-1 ;
+          for (j=start;j<yth;j++) { // j = columns
+            // check for lower triangular area and upper triangular area
+            if ( ((i > j) && (type == upper_trigrid)) || ((j > i) && (type == lower_trigrid))) {
+              *((double *)value) = 0.0;
+              fprintf(stderr,"%f\t",*((double *)value));
+              value = (void *)((long)value + sizeof(double));
+              //value += sizeof(double);
+            } else {
+              // otherwise we must skip all interjacent tabs and spaces and find next value
+              dummy1 = dummy;
+              dummy = strchr(dummy1, '\t'); // seek for tab or space
+              if (dummy == NULL) {
+                dummy = strchr(dummy1, ' ');  // if not found seek for space
+                while ((dummy != NULL) && ((*dummy == '\t') || (*dummy == ' ')))    // skip some more tabs and spaces if necessary
+                  dummy++;
+              }
+/*              while ((dummy != NULL) && ((*dummy == '\t') || (*dummy == ' ')))    // skip some more tabs and spaces if necessary
+                dummy++;*/
+              if (dummy == NULL) { // if still zero returned ...
+                dummy = strchr(dummy1, '\n');  // ... at line end then
+                if ((j < yth-1) && (type < 4)) {  // check if xth value or not yet
+                  if (critical) {
+                    if (verbose) fprintf(stderr,"Error: EoL at %i and still missing %i value(s) for parameter %s\n", line, yth-j, name);
+                    Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");
+                    //return 0;
+                    exit(255);
+                    //Error(FileOpenParams, NULL);      
+                  } else {
+                    //if (!sequential)
+                    file->clear();
+                    file->seekg(file_position, ios::beg);  // rewind to start position
+                    Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");
+                    return 0;
+                  }
+                }
+              } else {
+                //fprintf(stderr,"found tab at %i\n",(char *)dummy-(char *)free_dummy);
+              }
+              //fprintf(stderr,"value from %i to %i\n",(char *)dummy1-(char *)free_dummy,(char *)dummy-(char *)free_dummy);
+              switch(type) {
+                case (row_int):
+                  *((int *)value) = atoi(dummy1);
+                  if ((verbose) && (i==0) && (j==0)) fprintf(stderr,"%s = ", name);
+                  if (verbose) fprintf(stderr,"%i\t",*((int *)value));
+                    value = (void *)((long)value + sizeof(int));
+                    //value += sizeof(int);
+                  break;
+                case(row_double): 
+                case(grid):
+                case(lower_trigrid):
+                case(upper_trigrid):
+                  *((double *)value) = atof(dummy1);
+                  if ((verbose) && (i==0) && (j==0)) fprintf(stderr,"%s = ", name);
+                  if (verbose) fprintf(stderr,"%lg\t",*((double *)value));
+                  value = (void *)((long)value + sizeof(double));
+                  //value += sizeof(double);
+                  break;
+                case(double_type):
+                  *((double *)value) = atof(dummy1);
+                  if ((verbose) && (i == xth-1)) fprintf(stderr,"%s = %lg\n", name, *((double *) value));
+                  //value += sizeof(double);
+                  break;
+                case(int_type):
+                  *((int *)value) = atoi(dummy1);
+                  if ((verbose) && (i == xth-1)) fprintf(stderr,"%s = %i\n", name, *((int *) value));
+                  //value += sizeof(int);
+                  break;
+                default:
+                case(string_type):
+                  if (value != NULL) {
+                    if (maxlength == -1) maxlength = strlen((char *)value); // get maximum size of string array
+                    length = maxlength > (dummy-dummy1) ? (dummy-dummy1) : maxlength; // cap at maximum
+                    strncpy((char *)value, dummy1, length);  // copy as much
+                    ((char *)value)[length] = '\0';  // and set end marker
+                    if ((verbose) && (i == xth-1)) fprintf(stderr,"%s is '%s' (%i chars)\n",name,((char *) value), length);
+                    //value += sizeof(char);
+                  } else {
+                  }
+                break;
+              }
+            }
+            while (*dummy == '\t')
+              dummy++;
+          }
+        }
+      }
+    }
+  } 
+  if ((type >= row_int) && (verbose)) fprintf(stderr,"\n");
+  Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");
+  if (!sequential) {
+    file->clear();
+    file->seekg(file_position, ios::beg);  // rewind to start position
+  }
+  //fprintf(stderr, "End of Parsing\n\n");
+  
+  return (found); // true if found, false if not
+}
Index: molecuilder/src/datacreator.cpp
===================================================================
--- molecuilder/src/datacreator.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/datacreator.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,524 @@
+/** \file datacreator.cpp
+ *
+ * Declarations of assisting functions in creating data and plot files. 
+ *    
+ */
+
+//============================ INCLUDES ===========================
+
+#include "datacreator.hpp"
+
+//=========================== FUNCTIONS============================
+
+/** Opens a file with \a *filename in \a *dir.
+ * \param output file handle on return
+ * \param *dir directory
+ * \param *filename name of file
+ * \return true if file has been opened
+ */
+bool OpenOutputFile(ofstream &output, const char *dir, const char *filename)
+{
+  stringstream name;
+  name << dir << "/" << filename;
+  output.open(name.str().c_str(), ios::out);
+  if (output == NULL) {
+    cout << "Unable to open " << name.str() << " for writing, is directory correct?" << endl;
+    return false;
+  }
+  return true;
+}; 
+
+/** Plots an energy vs. order.
+ * \param Energy EnergyMatrix class containing matrix values (last matrix is created by summing over Fragments)
+ * \param EnergyFragments EnergyMatrix class containing matrix values
+ * \param KeySet KeySetContainer class holding bond KeySetContainer::Order
+ * \param *prefix prefix in filename (without ending)
+ * \param *msg message to be place in first line as a comment
+ * \return true if file was written successfully
+ */
+bool CreateDataEnergyOrder(class MatrixContainer &Energy, class MatrixContainer &EnergyFragments, class KeySetsContainer &KeySet, char *dir, char *prefix, char *msg, char *datum) 
+{
+  stringstream filename;
+  ofstream output;
+
+  filename << prefix << ".dat";
+  if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
+  cout << msg << endl;
+  output << "# " << msg << ", created on " << datum;
+  output << "#Order\tFrag.No.\t" << Energy.Header << endl;
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    for(int i=0;i<KeySet.FragmentsPerOrder[BondOrder];i++) {
+      for(int j=0;j<Energy.RowCounter[ KeySet.OrderSet[BondOrder][i] ];j++)
+        for(int k=0;k<Energy.ColumnCounter;k++)
+          Energy.Matrix[Energy.MatrixCounter][j][k] -= EnergyFragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+    }
+    output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
+    for (int l=0;l<Energy.ColumnCounter;l++)
+      if (fabs(EnergyFragments.Matrix[EnergyFragments.MatrixCounter][ EnergyFragments.RowCounter[EnergyFragments.MatrixCounter]-1 ][l]) < MYEPSILON)
+        output << scientific << "\t" << Energy.Matrix[Energy.MatrixCounter][ Energy.RowCounter[Energy.MatrixCounter]-1 ][l];
+      else
+        output << scientific << "\t" << (Energy.Matrix[Energy.MatrixCounter][ Energy.RowCounter[Energy.MatrixCounter]-1 ][l] / EnergyFragments.Matrix[EnergyFragments.MatrixCounter][ EnergyFragments.RowCounter[EnergyFragments.MatrixCounter]-1 ][l]);
+    output << endl;
+  }
+  output.close();
+  return true;
+};
+
+/** Plot forces vs. order.
+ */
+bool CreateDataForcesOrder(class MatrixContainer &Force, class MatrixContainer &ForceFragments, class KeySetsContainer &KeySet, char *dir, char *prefix, char *msg, char *datum, void (*CreateForce)(class MatrixContainer &, int))
+{
+  stringstream filename;
+  ofstream output;
+
+  filename << prefix << ".dat";
+  if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
+  cout << msg << endl;
+  output << "# " << msg << ", created on " << datum;
+  output << "# Order\tFrag.No.\t" << Force.Header << endl;
+  for(int j=0;j<=Force.RowCounter[ Force.MatrixCounter ];j++)
+    for(int k=0;k<Force.ColumnCounter;k++)
+       Force.Matrix[Force.MatrixCounter][j][k] = 0.;
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    for(int i=0;i<KeySet.FragmentsPerOrder[BondOrder];i++) {
+      for(int l=0;l<Force.RowCounter[ KeySet.OrderSet[BondOrder][i] ];l++) {
+        int j = Force.Indices[ KeySet.OrderSet[BondOrder][i] ][l];
+        if (j > Force.RowCounter[Force.MatrixCounter]) {
+          cerr << "Current force index " << j << " is greater than " << Force.RowCounter[Force.MatrixCounter] << "!" << endl;
+          return 1;
+        }
+        if (j != -1)
+          for(int k=0;k<Force.ColumnCounter;k++) {
+            Force.Matrix[Force.MatrixCounter][j][k] += ForceFragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][l][k];
+          }
+      }
+    }
+    output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
+    CreateForce(Force, Force.MatrixCounter);
+    for (int l=0;l<Force.ColumnCounter;l++)
+       output << scientific << "\t" << Force.Matrix[Force.MatrixCounter][ Force.RowCounter[Force.MatrixCounter] ][l];
+    output << endl;
+  }
+  output.close();
+  return true;
+};
+
+/** Plot matrix vs. fragment.
+ */
+bool CreateDataFragment(class MatrixContainer &Fragment, class KeySetsContainer &KeySet, char *dir, char *prefix, char *msg, char *datum, void (*CreateFragment)(class MatrixContainer &, int))
+{
+  stringstream filename;
+  ofstream output;
+
+  filename << prefix << ".dat";
+  if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
+  cout << msg << endl;
+  output << "# " << msg << ", created on " << datum;
+  output << "#Order\tFrag.No.\t" << Fragment.Header << endl;
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    for(int i=0;i<KeySet.FragmentsPerOrder[BondOrder];i++) {
+      output << BondOrder+1 << "\t" << KeySet.OrderSet[BondOrder][i]+1;
+      CreateFragment(Fragment, KeySet.OrderSet[BondOrder][i]);
+      for (int l=0;l<Fragment.ColumnCounter;l++)
+        output << scientific << "\t" << Fragment.Matrix[ KeySet.OrderSet[BondOrder][i] ][ Fragment.RowCounter[ KeySet.OrderSet[BondOrder][i] ] ][l];
+      output << endl;
+    }
+  }
+  output.close();
+  return true;
+};
+
+/** Copies fragment energy values into last matrix of \a Matrix with greatest total energy.
+ * \param &Matrix MatrixContainer with all fragment energy values
+ * \param &KeySet KeySetsContainer with associations of each fragment to a bond order
+ * \param BondOrder current bond order
+ */ 
+void CreateMaxFragmentOrder(class MatrixContainer &Fragments, class KeySetsContainer &KeySet, int BondOrder)
+{
+  for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) {
+    for(int i=0;i<KeySet.FragmentsPerOrder[BondOrder];i++) {
+      if (fabs(Fragments.Matrix[ Fragments.MatrixCounter ][j][1]) < fabs(Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][1])) {
+        for (int k=0;k<Fragments.ColumnCounter;k++)
+          Fragments.Matrix[ Fragments.MatrixCounter ][j][k] = Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+      }
+    }      
+  }
+};
+
+/** Copies fragment energy values into last matrix of \a Matrix with smallest total energy.
+ * \param &Matrix MatrixContainer with all fragment energy values
+ * \param &KeySet KeySetsContainer with associations of each fragment to a bond order
+ * \param BondOrder current bond order
+ */ 
+void CreateMinFragmentOrder(class MatrixContainer &Fragments, class KeySetsContainer &KeySet, int BondOrder)
+{
+  for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) {
+    int i=0;
+    do {  // first get a minimum value unequal to 0
+      for (int k=0;k<Fragments.ColumnCounter;k++)
+        Fragments.Matrix[ Fragments.MatrixCounter ][j][k] = Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+      i++;
+    } while ((fabs(Fragments.Matrix[ Fragments.MatrixCounter ][j][1]) < MYEPSILON) && (i<KeySet.FragmentsPerOrder[BondOrder]));
+    for(;i<KeySet.FragmentsPerOrder[BondOrder];i++) { // then find lowest
+      if (fabs(Fragments.Matrix[ Fragments.MatrixCounter ][j][1]) > fabs(Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][1])) {
+        for (int k=0;k<Fragments.ColumnCounter;k++)
+          Fragments.Matrix[ Fragments.MatrixCounter ][j][k] = Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+      }
+    }      
+  }
+};
+
+/** Plot matrix vs. fragment.
+ */
+bool CreateDataFragmentOrder(class MatrixContainer &Fragment, class KeySetsContainer &KeySet, char *dir, char *prefix, char *msg, char *datum, void (*CreateFragmentOrder)(class MatrixContainer &, class KeySetsContainer &, int))
+{
+  stringstream filename;
+  ofstream output;
+
+  filename << prefix << ".dat";
+  if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
+  cout << msg << endl;
+  output << "# " << msg << ", created on " << datum;
+  output << "#Order\tFrag.No.\t" << Fragment.Header << endl;
+  // max
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    Fragment.SetLastMatrix(0.,0);
+    CreateFragmentOrder(Fragment, KeySet, BondOrder);
+    output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
+    for (int l=0;l<Fragment.ColumnCounter;l++)
+      output << scientific << "\t" << Fragment.Matrix[ Fragment.MatrixCounter ][ Fragment.RowCounter[ Fragment.MatrixCounter ]-1 ][l];
+    output << endl;
+  }
+  output.close();
+  return true;
+};
+
+/** Takes last but one row and copies into final row.
+ * \param Energy MatrixContainer with matrix values
+ * \param MatrixNumber the index for the ForceMatrix::matrix array
+ */
+void CreateEnergy(class MatrixContainer &Energy, int MatrixNumber)
+{
+  for(int k=0;k<Energy.ColumnCounter;k++)
+    Energy.Matrix[MatrixNumber][ Energy.RowCounter[MatrixNumber] ] [k] =  Energy.Matrix[MatrixNumber][ Energy.RowCounter[MatrixNumber]-1 ] [k];
+};
+
+/** Scans forces for the minimum in magnitude.
+ * Results are stored in the matrix ForceMatrix::MatrixCounter of \a Force.
+ * \param Force ForceMatrix class containing matrix values
+ * \param MatrixNumber the index for the ForceMatrix::matrix array
+ */
+void CreateMinimumForce(class MatrixContainer &Force, int MatrixNumber)
+{
+  for (int l=0;l<Force.ColumnCounter;l++)
+    Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] = 0.;
+  for (int l=5;l<Force.ColumnCounter;l+=3) {
+    double stored = 0;
+    int k=0;
+    do {
+      for (int m=0;m<3;m++) {
+        stored += Force.Matrix[MatrixNumber][ k ][l+m] 
+              * Force.Matrix[MatrixNumber][ k ][l+m];
+        Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l+m]  = Force.Matrix[MatrixNumber][ k ][l+m]; 
+      }
+      k++;
+    } while ((fabs(stored) < MYEPSILON) && (k<Force.RowCounter[MatrixNumber]));
+    for (;k<Force.RowCounter[MatrixNumber];k++) {
+      double tmp = 0;
+      for (int m=0;m<3;m++)
+        tmp += Force.Matrix[MatrixNumber][ k ][l+m] 
+              * Force.Matrix[MatrixNumber][ k ][l+m];
+      if ((fabs(tmp) > MYEPSILON) && (tmp < stored)) {  // current force is greater than stored
+        for (int m=0;m<3;m++)
+          Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l+m]  = Force.Matrix[MatrixNumber][ k ][l+m]; 
+        stored = tmp;
+      }
+    }
+  }
+};
+
+/** Scans forces for the mean in magnitude.
+ * Results are stored in the matrix ForceMatrix::MatrixCounter of \a Force.
+ * \param Force ForceMatrix class containing matrix values
+  * \param MatrixNumber the index for the ForceMatrix::matrix array
+ */
+void CreateMeanForce(class MatrixContainer &Force, int MatrixNumber)
+{
+  int divisor = 0;
+  for (int l=0;l<Force.ColumnCounter;l++)
+    Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] = 0.;
+  for (int l=5;l<Force.ColumnCounter;l+=3) {
+    double tmp = 0;
+    for (int k=0;k<Force.RowCounter[MatrixNumber];k++) {
+      double norm = 0.;
+      for (int m=0;m<3;m++)
+        norm += Force.Matrix[MatrixNumber][ k ][l+m] 
+              * Force.Matrix[MatrixNumber][ k ][l+m];
+      tmp += sqrt(norm);
+      if (fabs(norm) > MYEPSILON) divisor++;
+    }
+    tmp /= (double)divisor;
+    Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] = tmp;
+  }
+};
+
+/** Scans forces for the maximum in magnitude.
+ * Results are stored in the matrix ForceMatrix::MatrixCounter of \a Force.
+ * \param Force ForceMatrix class containing matrix values
+ * \param MatrixNumber the index for the ForceMatrix::matrix array
+ */
+void CreateMaximumForce(class MatrixContainer &Force, int MatrixNumber)
+{
+  for (int l=5;l<Force.ColumnCounter;l+=3) {
+    double stored = 0;
+    for (int k=0;k<Force.RowCounter[MatrixNumber];k++) {
+      double tmp = 0;
+      for (int m=0;m<3;m++)
+        tmp += Force.Matrix[MatrixNumber][ k ][l+m] 
+              * Force.Matrix[MatrixNumber][ k ][l+m];
+      if (tmp > stored) {  // current force is greater than stored
+        for (int m=0;m<3;m++)
+          Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l+m]  = Force.Matrix[MatrixNumber][ k ][l+m]; 
+        stored = tmp;
+      }
+    }
+  }
+};
+
+/** Adds vectorwise all forces.
+ * Results are stored in the matrix ForceMatrix::MatrixCounter of \a Force.
+ * \param Force ForceMatrix class containing matrix values
+ * \param MatrixNumber the index for the ForceMatrix::matrix array
+ */
+void CreateVectorSumForce(class MatrixContainer &Force, int MatrixNumber)
+{
+  for (int l=0;l<Force.ColumnCounter;l++)
+    Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] = 0.;
+  for (int l=5;l<Force.ColumnCounter;l++) {
+    for (int k=0;k<Force.RowCounter[MatrixNumber];k++)
+      Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] += Force.Matrix[MatrixNumber][k][l];
+  }
+};
+
+/** Writes the standard pyxplot header info.
+ * \param keycolumns number of columns of the key
+ * \param *key position of key
+ * \param *logscale axis for logscale
+ * \param *extraline extra set lines if desired 
+ * \param mxtics small tics at ...
+ * \param xtics large tics at ...
+ * \param *xlabel label for x axis  
+ * \param *ylabel label for y axis
+ */ 
+void CreatePlotHeader(ofstream &output, const char *prefix, const int keycolumns, const char *key, const char *logscale, const char *extraline, const int mxtics, const int xtics, const char *xlabel, const char *ylabel)
+{
+  //output << "#!/home/heber/build/pyxplot/pyxplot" << endl << endl;
+  output << "reset" << endl;
+  output << "set keycolumns "<< keycolumns << endl;
+  output << "set key " << key << endl;
+  output << "set mxtics "<< mxtics << endl;
+  output << "set xtics "<< xtics << endl;
+  if (logscale != "")
+    output << "set logscale " << logscale << endl;
+  if (extraline != "")
+    output << extraline << endl;
+  output << "set xlabel '" << xlabel << "'" << endl;
+  output << "set ylabel '" << ylabel << "'" << endl;
+  output << "set terminal eps color" << endl;
+  output << "set output '"<< prefix << ".eps'" << endl;
+};
+
+/** Creates the pyxplotfile for energy data.
+ * \param Matrix MatrixContainer with matrix values
+ * \param KeySet contains bond order
+ * \param *dir directory
+ * \param *prefix prefix for all filenames (without ending)
+ * \param keycolumns number of columns of the key
+ * \param *key position of key
+ * \param logscale axis for logscale
+ * \param mxtics small tics at ...
+ * \param xtics large tics at ...
+ * \param xlabel label for x axis  
+ * \param xlabel label for x axis
+ * \param *xrange xrange
+ * \param *yrange yrange
+ * \param *xargument number of column to plot against (x axis)
+ * \param uses using string for plot command
+ * \param (*CreatePlotLines) function reference that writes a single plot line
+ * \return true if file was written successfully
+ */   
+bool CreatePlotOrder(class MatrixContainer &Matrix, const class KeySetsContainer &KeySet, const char *dir, const char *prefix, const int keycolumns, const char *key, const char *logscale, const char *extraline, const int mxtics, const int xtics, const char *xlabel, const char *ylabel, const char *xrange, const char *yrange, const char *xargument, const char *uses, void (*CreatePlotLines)(ofstream &, class MatrixContainer &, const char *, const char *, const char *))
+{
+  stringstream filename;
+  ofstream output;
+
+  filename << prefix << ".pyx";
+  if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
+  CreatePlotHeader(output, prefix, keycolumns, key, logscale, extraline, mxtics, xtics, xlabel, ylabel);
+  output << "plot " << xrange << " " << yrange << " \\" << endl;
+  CreatePlotLines(output, Matrix, prefix, xargument, uses);
+  output.close();  
+  return true;
+};
+
+/** Writes plot lines for absolute energies.
+ * \param output file handler
+ * \param Energy MatrixContainer with matrix values
+ * \param *prefix prefix of data file
+ * \param *xargument number of column to plot against (x axis)
+ * \param *uses uses command
+ */
+void AbsEnergyPlotLine(ofstream &output, class MatrixContainer &Energy, const char *prefix, const char *xargument, const char *uses)
+{
+  char item[1024];
+  stringstream line(Energy.Header);
+
+  line >> item;
+  for (int i=3; i< Energy.ColumnCounter;i++) {
+    line >> item;
+    output << "'" << prefix << ".dat' title '" << item << "' using " << xargument << ":(abs($" << i+1 << ")) " << uses;
+    if (i != (Energy.ColumnCounter-1))
+      output << ", \\";
+    output << endl;
+  }
+};
+
+/** Writes plot lines for energies.
+ * \param output file handler
+ * \param Energy MatrixContainer with matrix values
+ * \param *prefix prefix of data file
+ * \param *xargument number of column to plot against (x axis)
+ * \param *uses uses command
+ */
+void EnergyPlotLine(ofstream &output, class MatrixContainer &Energy, const char *prefix, const char *xargument, const char *uses)
+{
+  char item[1024];
+  stringstream line(Energy.Header);
+
+  line >> item;
+  for (int i=3; i< Energy.ColumnCounter;i++) {
+    line >> item;
+    output << "'" << prefix << ".dat' title '" << item << "' using " << xargument << ":" << i+1 << " " << uses;
+    if (i != (Energy.ColumnCounter-1))
+      output << ", \\";
+    output << endl;
+  }
+};
+
+/** Writes plot lines for absolute force magnitudes.
+ * \param output file handler
+ * \param Force MatrixContainer with matrix values
+ * \param *prefix prefix of data file
+ * \param *xargument number of column to plot against (x axis)
+ * \param *uses uses command
+ */
+void ForceMagnitudePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses)
+{
+  char item[1024];
+  stringstream line(Force.Header);
+
+  line >> item;
+  line >> item;
+  line >> item;
+  line >> item;
+  line >> item;
+  for (int i=7; i< Force.ColumnCounter;i+=3) {
+    line >> item;
+    item[strlen(item)-1] = '\0';  // kill residual index char (the '0')
+    output << "'" << prefix << ".dat' title '" << item << "' using " << xargument << ":(sqrt($" << i+1 << "*$" << i+1 << "+$" << i+2 << "*$" << i+2 << "+$" << i+3 << "*$" << i+3 << ")) " << uses;
+    if (i != (Force.ColumnCounter-1))
+      output << ", \\";
+    output << endl;
+    line >> item;
+    line >> item;
+  }
+};
+
+/** Writes plot lines for first component of force vector.
+ * \param output file handler
+ * \param Force MatrixContainer with matrix values
+ * \param *prefix prefix of data file
+ * \param *xargument number of column to plot against (x axis)
+ * \param *uses uses command
+ */
+void AbsFirstForceValuePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses)
+{
+  char item[1024];
+  stringstream line(Force.Header);
+
+  line >> item;
+  line >> item;
+  line >> item;
+  line >> item;
+  line >> item;
+  for (int i=7; i< Force.ColumnCounter;i+=3) {
+    line >> item;
+    item[strlen(item)-1] = '\0';  // kill residual index char (the '0')
+    output << "'" << prefix << ".dat' title '" << item << "' using " << xargument << ":(abs($" << i+1 << ")) " << uses;
+    if (i != (Force.ColumnCounter-1))
+      output << ", \\";
+    output << endl;
+    line >> item;
+    line >> item;
+  }
+};
+
+/** Writes plot lines for force vector as boxes with a fillcolor.
+ * \param output file handler
+ * \param Force MatrixContainer with matrix values
+ * \param *prefix prefix of data file
+ * \param *xargument number of column to plot against (x axis)
+ * \param *uses uses command
+ */
+void BoxesForcePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses)
+{
+  char item[1024];
+  stringstream line(Force.Header);
+  char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
+
+  line >> item;
+  line >> item;
+  line >> item;
+  line >> item;
+  line >> item;
+  for (int i=7; i< Force.ColumnCounter;i+=3) {
+    line >> item;
+    item[strlen(item)-1] = '\0';  // kill residual index char (the '0')
+    output << "'" << prefix << ".dat' title '" << item << "' using ($" << xargument << "+" << fixed << setprecision(1) << (double)((i-7)/3)*0.2 << "):(sqrt($" << i+1 << "*$" << i+1 << "+$" << i+2 << "*$" << i+2 << "+$" << i+3 << "*$" << i+3 << ")) " << uses << " " << fillcolor[(i-7)/3];
+    if (i != (Force.ColumnCounter-1))
+      output << ", \\";
+    output << endl;
+    line >> item;
+    line >> item;
+  }
+};
+
+/** Writes plot lines for first force vector component as boxes with a fillcolor.
+ * \param output file handler
+ * \param Force MatrixContainer with matrix values
+ * \param *prefix prefix of data file
+ * \param *xargument number of column to plot against (x axis)
+ * \param *uses uses command
+ */
+void BoxesFirstForceValuePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses)
+{
+  char item[1024];
+  stringstream line(Force.Header);
+  char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
+
+  line >> item;
+  line >> item;
+  line >> item;
+  line >> item;
+  line >> item;
+  for (int i=7; i< Force.ColumnCounter;i+=3) {
+    line >> item;
+    item[strlen(item)-1] = '\0';  // kill residual index char (the '0')
+    output << "'" << prefix << ".dat' title '" << item << "' using ($" << xargument << "+" << fixed << setprecision(1) << (double)((i-7)/3)*0.2 << "):" << i+1 << " " << uses << " " << fillcolor[(i-7)/3];
+    if (i != (Force.ColumnCounter-1))
+      output << ", \\";
+    output << endl;
+    line >> item;
+    line >> item;
+  }
+};
Index: molecuilder/src/datacreator.hpp
===================================================================
--- molecuilder/src/datacreator.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/datacreator.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,44 @@
+/** \file datacreator.cpp
+ *
+ * Definitions of assisting functions in creating data and plot files. 
+ *    
+ */
+
+#ifndef DATACREATOR_HPP_
+#define DATACREATOR_HPP_
+
+using namespace std;
+
+//============================ INCLUDES ===========================
+
+#include "helpers.hpp" 
+#include "parser.hpp"
+
+//=========================== FUNCTIONS============================
+
+bool OpenOutputFile(ofstream &output, const char *dir, const char *filename);
+
+bool CreateDataEnergyOrder(class MatrixContainer &Energy, class MatrixContainer &EnergyFragments, class KeySetsContainer &KeySet, char *dir, char *prefix, char *msg, char *datum); 
+bool CreateDataForcesOrder(class MatrixContainer &Force, class MatrixContainer &ForceFragments, class KeySetsContainer &KeySet, char *dir, char *prefix, char *msg, char *datum, void (*CreateForce)(class MatrixContainer &, int));
+bool CreateDataFragment(class MatrixContainer &ForceFragments, class KeySetsContainer &KeySet, char *dir, char *prefix, char *msg, char *datum, void (*CreateForce)(class MatrixContainer &, int));
+bool CreateDataFragmentOrder(class MatrixContainer &Fragment, class KeySetsContainer &KeySet, char *dir, char *prefix, char *msg, char *datum, void (*CreateFragmentOrder)(class MatrixContainer &, class KeySetsContainer &, int));
+
+void CreateEnergy(class MatrixContainer &Energy, int MatrixNumber);
+void CreateMaxFragmentOrder(class MatrixContainer &Matrix, class KeySetsContainer &KeySet, int BondOrder);
+void CreateMinFragmentOrder(class MatrixContainer &Matrix, class KeySetsContainer &KeySet, int BondOrder);
+void CreateMinimumForce(class MatrixContainer &Force, int MatrixNumber);
+void CreateMeanForce(class MatrixContainer &Force, int MatrixNumber);
+void CreateMaximumForce(class MatrixContainer &Force, int MatrixNumber);
+void CreateVectorSumForce(class MatrixContainer &Force, int MatrixNumber);
+
+void CreatePlotHeader(ofstream &output, const char *prefix, const int keycolumns, const char *key, const char *logscale, const char *extraline, const int mxtics, const int xtics, const char *xlabel, const char *ylabel);
+bool CreatePlotOrder(class MatrixContainer &Matrix, const class KeySetsContainer &KeySet, const char *dir, const char *prefix, const int keycolumns, const char *key, const char *logscale, const char *extraline, const int mxtics, const int xtics, const char *xlabel, const char *ylabel, const char *xrange, const char *yrange, const char *xargument, const char *uses, void (*CreatePlotLines)(ofstream &, class MatrixContainer &, const char *, const char *, const char *));
+
+void AbsEnergyPlotLine(ofstream &output, class MatrixContainer &Energy, const char *prefix, const char *xargument, const char *uses);
+void EnergyPlotLine(ofstream &output, class MatrixContainer &Energy, const char *prefix, const char *xargument, const char *uses);
+void ForceMagnitudePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses);
+void AbsFirstForceValuePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses);
+void BoxesForcePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses);
+void BoxesFirstForceValuePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses);
+
+#endif /*DATACREATOR_HPP_*/
Index: molecuilder/src/defs.hpp
===================================================================
--- molecuilder/src/defs.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/defs.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,35 @@
+/** \file defs.hpp
+ * 
+ * Constant definitons and enumerations.
+ * 
+ */
+
+#ifndef DEFS_HPP_
+#define DEFS_HPP_
+
+using namespace std;
+
+#define MYEPSILON 1e-13   //!< machine epsilon precision
+#define NDIM  3   //!< number of spatial dimensions
+#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 
+
+enum BondOrderScheme { NoScheme, BottomUp, TopDown, ANOVA, Combined }; //!< Fragmentation scheme used in BOSS
+
+enum EdgeType { Undetermined, TreeEdge, BackEdge }; //!< edge type in a graph after Depth-First-Search analysis.
+
+enum Shading { white, lightgray, darkgray, black };  //!< color in Breadth-First-Search analysis
+
+enum CutCyclicBond { KeepBond,  SaturateBond }; //!< Saturation scheme either atom- or bondwise 
+
+// Specifting whether a value in the parameter file must be specified or is optional
+enum necessity { optional,    //!< parameter is optional, if not given sensible value is chosen
+                 critical     //!< parameter must be given or programme won't initiate
+               };
+
+// Specifying the cast type to be read of a parameter, see ParseForParameter()
+enum value_type { string_type, double_type, int_type, row_int, row_double, grid, lower_trigrid, upper_trigrid}; 
+
+
+#endif /*DEFS_HPP_*/
Index: molecuilder/src/element.cpp
===================================================================
--- molecuilder/src/element.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/element.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,44 @@
+/** \file element.cpp
+ * 
+ * Function implementations for the class element.
+ * 
+ */
+
+#include "molecules.hpp"
+
+/************************************* Functions for class element **********************************/
+
+/** Constructor of class element.
+ */
+element::element() {};
+
+/** Destructor of class element.
+ */
+element::~element() {};
+
+/** Prints element data to \a *out.
+ * \param *out outstream
+ */
+bool element::Output(ofstream *out) const
+{ 
+  if (out != NULL) {
+    *out << name << "\t" << symbol << "\t" << period << "\t" << group << "\t" << block << "\t" << Z << "\t" << mass << "\t" << CovalentRadius << "\t" << VanDerWaalsRadius << endl;
+    //*out << Z << "\t"  << fixed << setprecision(11) << showpoint << mass << "g/mol\t" << name << "\t" << symbol << "\t" << endl;
+    return true;
+  } else
+    return false;
+};
+
+/** Prints element data to \a *out.
+ * \param *out outstream
+ * \param No  cardinal number of element
+ * \param NoOfAtoms total number of atom of this element type
+ */
+bool element::Checkout(ofstream *out, const int No, const int NoOfAtoms) const
+{ 
+  if (out != NULL) {
+    *out << "Ion_Type" << No << "\t" << NoOfAtoms << "\t" << Z << "\t1.0\t3\t3\t" << fixed << setprecision(11) << showpoint << mass << "\t" << name << "\t" << symbol <<endl;
+    return true;
+  } else
+    return false;
+};
Index: molecuilder/src/elements.db
===================================================================
--- molecuilder/src/elements.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/elements.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,112 @@
+#	Covalent	radius	of	each	element	in	Angstroem	from	CSD	(binding	is:	[Rcov(A)+Rcov(B)-t,Rcov(A)+Rcov(B)+t]	with	t	=	0.4A
+#Element	Name	Symbol	Period	Group	Block	Atomic	Number	AtomicWeight	Covalent	Radius	vdW	Radius
+Hydrogen	H	1	1	s	1	1.008	0.23	1.09
+Helium	He	1	18	p	2	4.003	1.50	1.40
+Lithium	Li	2	1	s	3	6.941	0.68	1.82
+Beryllium	Be	2	2	s	4	9.012	0.35	2.00
+Boron	B	2	13	p	5	10.811	0.83	2.00
+Carbon	C	2	14	p	6	12.011	0.68	1.70
+Nitrogen	N	2	15	p	7	14.007	0.68	1.55
+Oxygen	O	2	16	p	8	15.999	0.68	1.52
+Fluorine	F	2	17	p	9	18.998	0.64	1.47
+Neon	Ne	2	18	p	10	20.180	1.50	1.54
+Sodium	Na	3	1	s	11	22.991	0.97	2.27
+Magnesium	Mg	3	2	s	12	24.305	1.10	1.73
+Aluminium	Al	3	13	p	13	26.982	1.35	2.00
+Silicon	Si	3	14	p	14	28.086	1.20	2.10
+Phosphorus	P	3	15	p	15	30.974	1.05	1.80
+Sulphur	S	3	16	p	16	32.066	1.02	1.80
+Chlorine	Cl	3	17	p	17	35.453	0.99	1.75
+Argon	Ar	3	18	p	18	39.948	1.51	1.88
+Potassium	K	4	1	s	19	39.098	1.33	2.75
+Calcium	Ca	4	2	s	20	40.078	0.99	2.00
+Scandium	Sc	4	3	d	21	44.956	1.44	2.00
+Titanium	Ti	4	4	d	22	47.867	1.47	2.00
+Vanadium	V	4	5	d	23	50.942	1.33	2.00
+Chromium	Cr	4	6	d	24	51.996	1.35	2.00
+Manganese	Mn	4	7	d	25	54.938	1.35	2.00
+Iron	Fe	4	8	d	26	55.845	1.34	2.00
+Cobalt	Co	4	9	d	27	58.933	1.33	2.00
+Nickel	Ni	4	10	d	28	58.693	1.50	1.63
+Copper	Cu	4	11	d	29	63.546	1.52	1.40
+Zinc	Zn	4	12	d	30	65.390	1.45	1.39
+Gallium	Ga	4	13	p	31	69.723	1.22	1.87
+Germanium	Ge	4	14	p	32	72.610	1.17	2.00
+Arsenic	As	4	15	p	33	74.922	1.21	1.85
+Selenium	Se	4	16	p	34	78.960	1.22	1.90
+Bromine	Br	4	17	p	35	79.904	1.21	1.85
+Krypton	Kr	4	18	p	36	83.800	1.50	2.02
+Rubidium	Rb	5	1	s	37	85.468	1.47	2.00
+Strontium	Sr	5	2	s	38	87.620	1.12	2.00
+Yttrium	Y	5	3	d	39	88.906	1.78	2.00
+Zirconium	Zr	5	4	d	40	91.224	1.56	2.00
+Niobium	Nb	5	5	d	41	92.906	1.48	2.00
+Molybdenum	Mo	5	6	d	42	95.940	1.47	2.00
+Technetium	Tc	5	7	d	43	98	1.35	2.00
+Ruthenium	Ru	5	8	d	44	101.070	1.40	2.00
+Rhodium	Rh	5	9	d	45	102.906	1.45	2.00
+Palladium	Pd	5	10	d	46	106.420	1.50	1.63
+Silver	Ag	5	11	d	47	107.868	1.59	1.72
+Cadmium	Cd	5	12	d	48	112.411	1.69	1.58
+Indium	In	5	13	p	49	114.818	1.63	1.93
+Tin	Sn	5	14	p	50	118.71	1.46	2.17
+Antimony	Sb	5	15	p	51	121.760	1.46	2.00
+Tellurium	Te	5	16	p	52	127.600	1.47	2.06
+Iodine	I	5	17	p	53	126.904	1.40	1.98
+Xenon	Xe	5	18	p	54	131.290	1.50	2.16
+Caesium	Cs	6	1	s	55	132.905	1.67	2.00
+Barium	Ba	6	2	s	56	137.327	1.34	2.00
+Lutetium	Lu	6	3	d	71	174.967	1.72	2.00
+Hafnium	Hf	6	4	d	72	178.490	1.57	2.00
+Tantalum	Ta	6	5	d	73	180.948	1.43	2.00
+Tungsten	W	6	6	d	74	183.840	1.37	2.00
+Rhenium	Re	6	7	d	75	186.207	1.35	2.00
+Osmium	Os	6	8	d	76	190.230	1.37	2.00
+Iridium	Ir	6	9	d	77	192.217	1.32	2.00
+Platinum	Pt	6	10	d	78	195.078	1.50	1.72
+Gold	Au	6	11	d	79	196.967	1.50	1.66
+Mercury	Hg	6	12	d	80	200.590	1.70	1.55
+Thallium	Tl	6	13	p	81	204.383	1.55	1.96
+Lead	Pb	6	14	p	82	207.200	1.54	2.02
+Bismuth	Bi	6	15	p	83	208.980	1.54	2.00
+Polonium	Po	6	16	p	84	210	1.68	2.00
+Astatine	At	6	17	p	85	210	1.21	2.00
+Radon	Rn	6	18	p	86	222	1.50	2.00
+Cerium	Ce	6Lan	19	f	58	140.116	1.83	2.00
+Dysprosium	Dy	6Lan	19	f	66	162.500	1.75	2.00
+Erbium	Er	6Lan	19	f	68	167.260	1.73	2.00
+Europium	Eu	6Lan	19	f	63	151.964	1.99	2.00
+Gadolinium	Gd	6Lan	19	f	64	157.250	1.79	2.00
+Holmium	Ho	6Lan	19	f	67	164.930	1.74	2.00
+Lanthanum	La	6Lan	19	f	57	138.906	1.87	2.00
+Neodymium	Nd	6Lan	19	f	60	144.240	1.81	2.00
+Promethium	Pm	6Lan	19	f	61	145	1.80	2.00
+Praseodymium	Pr	6Lan	19	f	59	140.908	1.82	2.00
+Samarium	Sm	6Lan	19	f	62	150.360	1.80	2.00
+Terbium	Tb	6Lan	19	f	65	158.925	1.76	2.00
+Thulium	Tm	6Lan	19	f	69	168.934	1.72	2.00
+Ytterbium	Yb	6Lan	19	f	70	173.040	1.94	2.00
+Francium	Fr	7	1	s	87	223	1.50	2.00
+Radium	Ra	7	2	s	88	226	1.90	2.00
+Lawrencium	Lr	7	3	d	103	262	1.50	2.00
+Rutherfordium	Rf	7	4	d	104	261	1.50	2.00
+Dubnium	Db	7	5	d	105	262	1.50	2.00
+Seaborgium	Sg	7	6	d	106	266	1.50	2.00
+Bohrium	Bh	7	7	d	107	264	1.50	2.00
+Hassium	Hs	7	8	d	108	269	1.50	2.00
+Meitnerium	Mt	7	9	d	109	268	1.50	2.00
+Darmstadtium	Ds	7	10	d	110	271	1.50	2.00
+Actinium	Ac	7Act	20	f	89	227	1.88	2.00
+Americium	Am	7Act	20	f	95	243	1.51	2.00
+Berkelium	Bk	7Act	20	f	97	247	1.54	2.00
+Californium	Cf	7Act	20	f	98	251	1.83	2.00
+Curium	Cm	7Act	20	f	96	247	0.99	2.00
+Einsteinium	Es	7Act	20	f	99	252	1.50	2.00
+Fermium	Fm	7Act	20	f	100	257	1.50	2.00
+Mendelevium	Md	7Act	20	f	101	258	1.50	2.00
+Nobelium	No	7Act	20	f	102	259	1.50	2.00
+Neptunium	Np	7Act	20	f	93	237	1.55	2.00
+Protactinium	Pa	7Act	20	f	91	231.036	1.61	2.00
+Plutonium	Pu	7Act	20	f	94	244	1.53	2.00
+Thorium	Th	7Act	20	f	90	232.038	1.79	2.00
+Uranium	U	7Act	20	f	92	238.029	1.58	1.86
Index: molecuilder/src/graph.cpp
===================================================================
--- molecuilder/src/graph.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/graph.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,17 @@
+/** \file graph.cpp
+ * 
+ * Function implementations for the class graph.
+ * 
+ */
+
+using namespace std;
+
+
+#include <iostream>
+#include <list>
+#include <vector>
+
+/***************************************** Functions for class graph ********************************/
+
+
+ 
Index: molecuilder/src/helpers.cpp
===================================================================
--- molecuilder/src/helpers.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/helpers.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,169 @@
+/** \file helpers.cpp
+ *
+ * Implementation of some auxiliary functions for memory dis-/allocation and so on 
+ */
+
+
+#include "helpers.hpp"
+
+/********************************************** helpful functions *********************************/
+
+
+/** Asks for a double value and checks input
+ * \param *text question
+ */
+double ask_value(const char *text)
+{
+  double test = 0.1439851348959832147598734598273456723948652983045928346598365;
+  do {
+    cout << Verbose(0) << text;
+    cin >> test;
+  } while (test == 0.1439851348959832147598734598273456723948652983045928346598365);
+  return test;   
+};
+
+
+/** Wrapper for allocating'ing a memory range with *output if it fails.
+ * \param size number of chars to alloc for \a *buffer
+ * \param *output message if malloc fails
+ * \return pointer to memory range
+ */
+void * Malloc(size_t size, const char* output) 
+{
+  void *buffer = NULL;
+  buffer = (void *)malloc(size); // alloc
+  if (buffer == NULL)
+    cout << Verbose(0) << "Malloc failed - pointer is NULL: " << output << endl;
+  return(buffer);
+};
+
+/** Wrapper for allocating'ing a memory range with *output if it fails.
+ * \param size number of chars to alloc for \a *buffer
+ * \param *output message if malloc fails
+ * \return pointer to memory range
+ */
+void * Calloc(size_t size, const char* output) 
+{
+  void *buffer = NULL;
+  buffer = (void *)calloc(size, (size_t)0); // alloc
+  if (buffer == NULL)
+    cout << Verbose(0) << "Calloc failed - pointer is NULL: " << output << endl;
+  return(buffer);
+};
+
+/** Wrapper for reallocating'ing a memory range with *output if it fails.
+ * \param *OldPointer pointer to old memory range
+ * \param size number of chars to alloc for \a *buffer
+ * \param *output message if malloc fails
+ * \return pointer to memory range
+ */
+void * ReAlloc(void * OldPointer, size_t size, const char* output) 
+{
+  void *buffer = NULL;
+  if (OldPointer == NULL)
+  	cout << Verbose(0) << "ReAlloc impossible - old is NULL: " << output << endl;
+  buffer = (void *)realloc(OldPointer, size); // alloc
+  if (buffer == NULL)
+    cout << Verbose(0) << "ReAlloc failed - new is NULL: " << output << endl;
+  return(buffer);
+};
+
+/** Wrapper for free'ing an allocated memory range with *output if it fails.
+ * \param *buffer pointer to buffer to be free'd
+ * \param *output message if free fails
+ */
+void Free(void ** buffer, const char* output) 
+{
+  if (*buffer == NULL) {
+    //cout << Verbose(5) << "Free not necesary: " << output << endl;
+  } else {
+    free(*buffer);
+  }
+  *buffer = NULL;
+};
+
+/** Malloc string array and set its length to the allocated length.
+ * \param *output message if malloc fails
+ * \param size number of chars to alloc for \a *buffer
+ * \return pointer to string array
+ */
+char* MallocString(size_t size, const char* output) 
+{
+  size_t i;
+  char *buffer;
+  buffer = (char *)malloc(sizeof(char) * (size+1)); // alloc
+  if (buffer == NULL)
+    cout << Verbose(0) << output << endl;
+  for (i=0;i<size;i++)  // reset
+    buffer[i] = i % 2 == 0 ? 'p': 'c';
+  buffer[size] = '\0'; // and set length marker on its end
+  return(buffer);
+}
+
+/** modulo operator for doubles.
+ * \param *b pointer to double
+ * \param lower_bound lower bound
+ * \param upper_bound upper bound
+ */
+void bound(double *b, double lower_bound, double upper_bound)
+{
+  double step = (upper_bound - lower_bound);
+  while (*b >= upper_bound)
+    *b -= step;    
+  while (*b < lower_bound)
+    *b += step;    
+}; 
+
+/** Flips two doubles.
+ * \param *x pointer to first double
+ * \param *y pointer to second double
+ */
+void flip(double *x, double *y)
+{
+  double tmp;
+  tmp = *x;
+  *x = *y;
+  *y = tmp;
+};
+
+/** Returns the power of \a n with respect to \a base.
+ * \param base basis
+ * \param n power
+ * \return \f$base^n\f$
+ */
+int pot(int base, int n)
+{
+  int res = 1;
+  int j;
+  for (j=0;j<n;j++)
+    res *= base;
+  return res;
+};
+
+/** Returns a string with \a i prefixed with 0s to match order of total number of molecules in digits.
+ * \param FragmentNumber total number of fragments to determine necessary number of digits
+ * \param digits number to create with 0 prefixed
+ * \return allocated(!) char array with number in digits, ten base.
+ */
+char *FixedDigitNumber(const int FragmentNumber, const int digits)
+{
+  char *returnstring;
+  int number = FragmentNumber;
+  int order = 0;
+  while (number != 0) { // determine number of digits needed
+    number = (int)floor(((double)number / 10.));
+    order++;
+    //cout << "Number is " << number << ", order is " << order << "." << endl;
+  }
+  // allocate string
+  returnstring = (char *) Malloc(sizeof(char)*(order+2), "MoleculeListClass::CreateFragmentNumberForOutput: *returnstring");
+  // terminate  and fill string array from end backward
+  returnstring[order] = '\0';
+  number = digits;
+  for (int i=order-1;i>=0;i--){
+    returnstring[i] = '0' + (char)(number % 10);
+    number = (int)floor(((double)number / 10.));
+  }
+  return returnstring;
+};
+
Index: molecuilder/src/helpers.hpp
===================================================================
--- molecuilder/src/helpers.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/helpers.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,71 @@
+/** \file helpers.hpp
+ *
+ * Declaration of some auxiliary functions for memory dis-/allocation and so on 
+ */
+
+#ifndef HELPERS_HPP_
+#define HELPERS_HPP_
+
+using namespace std;
+
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+#include <sstream>
+#include <math.h>
+#include <string>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+#include "defs.hpp"
+
+/********************************************** helpful functions *********************************/
+
+double ask_value(const char *text);
+bool check_bounds(double *x, double *cell_size);
+void bound(double *b, double lower_bound, double upper_bound);
+void flip(double *x, double *y);
+int pot(int base, int n);
+void * Malloc(size_t size, const char* output);
+void * Calloc(size_t size, const char* output);
+void * ReAlloc(void * OldPointer, size_t size, const char* output);
+char* MallocString(size_t size, const char* output);
+void Free(void ** buffer, const char* output);
+char *FixedDigitNumber(const int FragmentNumber, const int digits);
+
+/********************************************** helpful structures *********************************/
+
+/************************************* Class Verbose & Binary *******************************/
+
+/** Verbose is an IO manipulator, that writes tabs according to \a Verbosity level.
+ */
+class Verbose
+{
+  public:
+    Verbose(int value) : Verbosity(value) { }
+
+    ostream& print (ostream &ost) const;
+  private:
+    int Verbosity;
+};
+
+ostream& operator<<(ostream& ost,const Verbose& m);
+
+/** Binary is an IO manipulator, that writes 0 and 1 according to number \a Binary.
+ */
+class Binary
+{
+  public:
+    Binary(int value) : BinaryNumber(value) { }
+
+    ostream& print (ostream &ost) const;
+  private:
+    int BinaryNumber;
+};
+
+ostream& operator<<(ostream& ost,const Binary& m);
+
+
+
+#endif /*HELPERS_HPP_*/
Index: molecuilder/src/joiner.cpp
===================================================================
--- molecuilder/src/joiner.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/joiner.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,108 @@
+/** \file joiner.cpp
+ *
+ * Takes evaluated fragments (energy and forces) and by reading the factors files determines total energy
+ * and each force for the whole molecule. 
+ *    
+ */
+
+//============================ INCLUDES ===========================
+
+#include "helpers.hpp" 
+#include "parser.hpp" 
+
+//============================== MAIN =============================
+
+int main(int argc, char **argv)
+{
+  EnergyMatrix Energy;
+  ForceMatrix Force;
+  EnergyMatrix EnergyFragments;
+  ForceMatrix ForceFragments;
+  KeySetsContainer KeySet;  
+  stringstream prefix;
+
+  cout << "Joiner" << endl;
+  cout << "======" << endl;
+  
+  // Get the command line options
+  if (argc < 3) {
+    cout << "Usage: " << argv[0] << " <inputdir> <prefix>" << endl;
+    cout << "<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;
+    cout << "<prefix>\tprefix of energy and forces file." << endl;
+    return 1;
+  }
+  
+  // Test the given directory
+  if (!TestParams(argc, argv))
+    return 1;
+  
+  // +++++++++++++++++ PARSING +++++++++++++++++++++++++++++++
+  
+  // ------------- Parse through all Fragment subdirs --------
+  if (!Energy.ParseMatrix(argv[1], argv[2], EnergySuffix,0,0)) return 1;
+  //if (!ParseSubEnergies(argv[1], argv[2], EnergySuffix, data.EnergyHeader, data.Energies, data.EnergyIndices, data.LevelCounter, data.ColumnCounter, data.FragmentCounter)) return 1;
+  if (!Force.ParseMatrix(argv[1], argv[2], ForcesSuffix, 0,0)) return 1;
+  //if (!ParseSubForces(argv[1], argv[2], ForcesSuffix, data.ForcesHeader, data.Forces, data.AtomCounter, data.Column2Counter, data.FragmentCounter)) return 1;
+
+  // ---------- Parse the TE Factors into an array -----------------
+  if (!Energy.ParseIndices()) return 1;
+  
+  // ---------- Parse the Force indices into an array ---------------
+  if (!Force.ParseIndices(argv[1])) return 1;
+  //if (!ParseForceIndices(argv[1], data.ForcesIndices, data.AtomCounter, data.FragmentCounter)) return 1;
+
+  // ---------- Parse the KeySets into an array ---------------
+  if (!KeySet.ParseKeySets(argv[1], Force.RowCounter, Force.MatrixCounter)) return 1;
+  //if (!ParseKeySets(argv[1], data.KeySets, data.AtomCounter, data.FragmentCounter)) return 1;
+
+  if (!KeySet.ParseManyBodyTerms()) return 1;
+  //if (!ParseManyBodyTerms(data.Order, data.OrderSet, data.FragmentsPerOrder, data.KeySets, data.AtomCounter, data.FragmentCounter)) return 1;
+  if (!EnergyFragments.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return 1;
+  //if (!ParseSubEnergies(argv[1], argv[2], EnergyFragmentSuffix, data.EnergyHeader, data.EnergyFragments, data.EnergyFragmentIndices, data.LevelFragmentCounter, data.ColumnFragmentCounter, data.FragmentCounter)) return 1;
+  if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return 1;
+  //if (!ParseSubForces(argv[1], argv[2], ForceFragmentSuffix, data.ForcesHeader, data.ForceFragments, data.AtomCounter, data.Column2Counter, data.FragmentCounter)) return 1;
+  
+  // ----------- Resetting last matrices (where full QM values are stored right now)
+  if(!Energy.SetLastMatrix(0., 0)) return 1;
+  if(!Force.SetLastMatrix(0., 2)) return 1;
+  
+  // +++++++++++++++++ SUMMING +++++++++++++++++++++++++++++++
+
+  // --------- sum up and write for each order----------------
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    // --------- sum up energy --------------------
+    cout << "Summing energy of order " << BondOrder+1 << " ..." << endl;
+    if (!EnergyFragments.SumSubManyBodyTerms(Energy, KeySet, BondOrder)) return 1;
+    if (!Energy.SumSubEnergy(EnergyFragments, KeySet, BondOrder)) return 1;
+    // --------- sum up Forces --------------------
+    cout << "Summing forces of order " << BondOrder+1 << " ..." << endl;
+    if (!ForceFragments.SumSubManyBodyTerms(Force, KeySet, BondOrder)) return 1;
+    if (!Force.SumSubForces(ForceFragments, KeySet, BondOrder)) return 1;
+
+    // --------- write the energy and forces file --------------------
+    prefix.str(" ");
+    prefix << argv[2] << OrderSuffix << (BondOrder+1);
+    cout << "Writing files " << argv[1] << prefix.str() << ". ..." << endl;
+    // energy
+    if (!Energy.WriteLastMatrix(argv[1], (prefix.str()).c_str(), EnergySuffix)) return 1;
+    // forces
+    if (!Force.WriteLastMatrix(argv[1], (prefix.str()).c_str(), ForcesSuffix)) return 1;
+  }
+  // fragments
+  prefix.str(" ");
+  prefix << argv[2] << EnergyFragmentSuffix;
+  if (!EnergyFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+  prefix.str(" ");
+  prefix << argv[2] << ForceFragmentSuffix;
+  if (!ForceFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+
+  // write last matrices as fragments into central dir (not subdir as above), for analyzer to know index bounds
+  if (!Energy.WriteLastMatrix(argv[1], argv[2], EnergyFragmentSuffix)) return 1;
+  if (!Force.WriteLastMatrix(argv[1], argv[2], ForceFragmentSuffix)) return 1;
+
+  // exit  
+  cout << "done." << endl;
+  return 0;
+};
+
+//============================ END ===========================
Index: molecuilder/src/moleculelist.cpp
===================================================================
--- molecuilder/src/moleculelist.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/moleculelist.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,731 @@
+/** \file MoleculeListClass.cpp
+ * 
+ * Function implementations for the class MoleculeListClass.
+ * 
+ */
+
+#include "molecules.hpp"
+
+/*********************************** Functions for class MoleculeListClass *************************/
+
+/** Constructor for MoleculeListClass.
+ */
+MoleculeListClass::MoleculeListClass()
+{
+};
+
+/** constructor for MoleculeListClass.
+ * \param NumMolecules number of molecules to allocate for
+ * \param NumAtoms number of atoms to allocate for
+ */
+MoleculeListClass::MoleculeListClass(int NumMolecules, int NumAtoms)
+{
+  TEList = (double*) Malloc(sizeof(double)*NumMolecules, "MoleculeListClass:MoleculeListClass: *TEList");
+  ListOfMolecules = (molecule **) Malloc(sizeof(molecule *)*NumMolecules, "MoleculeListClass:MoleculeListClass: **ListOfMolecules");
+  for (int i=0;i<NumMolecules;i++) {
+    TEList[i] = 0.;
+    ListOfMolecules[i] = NULL;
+  }
+  NumberOfMolecules = NumMolecules;
+  NumberOfTopAtoms = NumAtoms;
+};
+
+
+/** Destructor for MoleculeListClass.
+ */
+MoleculeListClass::~MoleculeListClass()
+{
+  cout << Verbose(3) << this << ": Freeing ListOfMolcules and TEList." << endl;
+  for (int i=0;i<NumberOfMolecules;i++) {
+    if (ListOfMolecules[i] != NULL) { // if NULL don't free
+      cout << Verbose(4) << "ListOfMolecules: Freeing " << ListOfMolecules[i] << "." << endl;
+      delete(ListOfMolecules[i]);
+      ListOfMolecules[i] = NULL;
+    }
+  }
+  cout << Verbose(4) << "Freeing ListOfMolecules." << endl;
+  Free((void **)&ListOfMolecules, "MoleculeListClass:MoleculeListClass: **ListOfMolecules");
+  cout << Verbose(4) << "Freeing TEList." << endl;
+  Free((void **)&TEList, "MoleculeListClass:MoleculeListClass: *TEList");
+};
+
+int MolCompare(const void *a, const void *b)
+{
+  int *aList = NULL, *bList = NULL;
+  int Count, Counter, aCounter, bCounter;
+  int flag;
+  atom *aWalker = NULL;
+  atom *bWalker = NULL;
+  
+  // sort each atom list and put the numbers into a list, then go through
+  //cout << "Comparing fragment no. " << *(molecule **)a << " to " << *(molecule **)b << "." << endl;
+  if ( (**(molecule **)a).AtomCount < (**(molecule **)b).AtomCount ) {
+    return -1;
+  } else { if ((**(molecule **)a).AtomCount > (**(molecule **)b).AtomCount)
+    return +1;
+    else {
+      Count = (**(molecule **)a).AtomCount;
+      aList = (int *) Malloc(sizeof(int)*Count, "MolCompare: *aList");
+      bList = (int *) Malloc(sizeof(int)*Count, "MolCompare: *bList");
+  
+      // fill the lists
+      aWalker = (**(molecule **)a).start;
+      bWalker = (**(molecule **)b).start;
+      Counter = 0;
+      aCounter = 0;
+      bCounter = 0;
+      while ((aWalker->next != (**(molecule **)a).end) && (bWalker->next != (**(molecule **)b).end)) {
+        aWalker = aWalker->next;
+        bWalker = bWalker->next;
+        if (aWalker->GetTrueFather() == NULL)
+          aList[Counter] = Count + (aCounter++);
+        else
+          aList[Counter] = aWalker->GetTrueFather()->nr;
+        if (bWalker->GetTrueFather() == NULL)
+          bList[Counter] = Count + (bCounter++);
+        else
+          bList[Counter] = bWalker->GetTrueFather()->nr;
+        Counter++;
+      }
+      // check if AtomCount was for real
+      flag = 0;
+      if ((aWalker->next == (**(molecule **)a).end) && (bWalker->next != (**(molecule **)b).end)) {
+        flag = -1;
+      } else {
+        if ((aWalker->next != (**(molecule **)a).end) && (bWalker->next == (**(molecule **)b).end))
+          flag = 1;
+      }
+      if (flag == 0) {
+        // sort the lists
+        gsl_heapsort(aList,Count, sizeof(int), CompareDoubles); 
+        gsl_heapsort(bList,Count, sizeof(int), CompareDoubles);
+        // compare the lists 
+        
+        flag = 0;
+        for(int i=0;i<Count;i++) {
+          if (aList[i] < bList[i]) {
+            flag = -1;
+          } else {
+            if (aList[i] > bList[i])
+              flag = 1;
+          }
+          if (flag != 0)
+            break;
+        }
+      }
+      Free((void **)&aList, "MolCompare: *aList");
+      Free((void **)&bList, "MolCompare: *bList");
+      return flag;
+    }
+  }
+  return  -1;
+};
+
+/** Returns an allocated index list which fragment should remain and which are doubly appearing.
+ * Again, we use linked cell however not with \a threshold which in most cases is too small and would
+ * generate too many cells, but a too be specified \a celldistance which should e.g. be chosen in
+ * the magnitude of the typical bond distance. In order to avoid so far the need of a vector list,
+ * we simply use the molecule structure and the vector sitting in the atom structure.
+ * \param *out output stream for debugging
+ * \param **MapList empty but allocated(MoleculeListClass::NumberOfMolecules), containing on return mapping of for which equal molecule which atoms corresponds to which one (needed for ForceFactors)
+ * \param threshold threshold value for molecule::IsEqualToWithinThreshold()
+ * \param cell_size 6 entries specifying the unit cell vectors (matrix is symmetric)
+ * \param celldistance needed for linked-cell technique to find possible equals
+ * \return allocated index list with \a Num entries.
+ */
+int * MoleculeListClass::GetMappingToUniqueFragments(ofstream *out, double threshold, double *cell_size, double celldistance)
+{
+  int j, UniqueIndex, HighestNumber;
+  //int NumberCells, divisor[NDIM], n[NDIM], N[NDIM], index, Index;
+  int Counter;
+  //molecule **CellList;
+  int *MapList = NULL;
+  size_t *SortMap = NULL;
+  //atom *Walker = NULL, *OtherWalker = NULL;
+  //molecule *LinkedCellContainer = new molecule(NULL);  // container for all the center of gravities stored as atoms
+  
+  /// Allocated MapList with range NumberOfMolecules. 
+  MapList = (int *) Malloc(sizeof(int)*NumberOfMolecules, "MoleculeListClass::GetMappingToUniqueFragments: *MapList");
+  SortMap = (size_t *) Malloc(sizeof(size_t)*NumberOfMolecules, "MoleculeListClass::GetMappingToUniqueFragments: *MapList");
+  for (j=0;j<NumberOfMolecules;j++) {
+    if (ListOfMolecules[j] ==  NULL)
+      cerr << "ERROR: Molecule " << j << " is NULL!" << endl;
+    //else 
+      //cerr << "ERROR: Molecule " << j << " is " << ListOfMolecules[j] << " with count " << ListOfMolecules[j]->AtomCount << "." << endl;
+    MapList[j] = -1;
+    SortMap[j] = 0;
+  }
+  *out << Verbose(1) << "Get mapping to unique fragments with " << NumberOfMolecules << " fragments total." << endl;
+  
+  // sort the list with heapsort according to sort function
+  gsl_heapsort_index(SortMap, ListOfMolecules, NumberOfMolecules, sizeof(molecule *), MolCompare);
+  // check next neighbours and remap
+  Counter = 0;
+  MapList[SortMap[0]] = Counter++;
+  for(int i=1;i<NumberOfMolecules;i++) {
+    if (MolCompare(&ListOfMolecules[SortMap[i]], &ListOfMolecules[SortMap[i-1]]) == 0)
+      MapList[SortMap[i]] = MapList[SortMap[i-1]];
+    else
+      MapList[SortMap[i]] = Counter++; 
+  } 
+  Free((void **)&SortMap, "MoleculeListClass::GetMappingToUniqueFragments: *SortMap");
+
+  *out << Verbose(2) << "Map: ";
+  for(int i=0;i<NumberOfMolecules;i++)
+    *out << MapList[i] << " ";
+  *out << endl;
+
+  // bring MapList indices into an ascending order
+  HighestNumber = Counter;
+  *out << Verbose(3) << "HighestNumber: " << HighestNumber << "." << endl;
+  SortMap = (size_t *) Malloc(sizeof(size_t)*NumberOfMolecules, "MoleculeListClass::GetMappingToUniqueFragments: *SortMap");
+  for(int i=0;i<NumberOfMolecules;i++)
+    SortMap[i] = HighestNumber;   // is the first number that will not appear anymore in list   
+  UniqueIndex = 0;
+  for(int i=0;i<NumberOfMolecules;i++)
+    if (MapList[i] != -1) {
+      if ((unsigned int)SortMap[MapList[i]] == (unsigned int)HighestNumber)
+        SortMap[MapList[i]] = UniqueIndex++;
+      MapList[i] = SortMap[MapList[i]];
+    } else {
+      MapList[i] = -1;
+    }
+  *out << Verbose(2) << "Ascending Map: ";
+  for(int i=0;i<NumberOfMolecules;i++)
+    *out << MapList[i] << " ";
+  *out << endl;
+  Free((void **)&SortMap, "MoleculeListClass::GetMappingToUniqueFragments: *SortMap");
+
+  /// Return the constructed list.
+  return MapList;
+};
+
+
+/** Takes a list of molecules and returns the list with doubles removed.
+ * Checks by using molecule::IsEqualToWithinThreshold() whether fragments within the list
+ * are actually doubles. If not, the pointer are copied to a new list, if so,
+ * they are dropped. The new list is then copied back to the reallocated \a **FragmentList
+ * and the new number of elements therein returned.
+ * \param *out output stream for debugging
+ * \param *Map mapping of which index goes on which (from molecule::GetMappingToUniqueFragments())
+ * \return number of molecules in the new realloacted **FragmentList
+ */
+int MoleculeListClass::ReduceFragmentToUniqueOnes(ofstream *out, int *Map)
+{
+  *out << Verbose(2) << "Begin of ReduceFragmentToUniqueOnes" << endl;
+  /// Allocate temporary lists of size \a Num.
+  molecule **NewMolList = (molecule **) Malloc(sizeof(molecule *)*NumberOfMolecules, "MoleculeListClass::ReduceFragmentToUniqueOnes: NewList");
+  double *NewTEList = (double *) Malloc(sizeof(double)*NumberOfMolecules, "MoleculeListClass::ReduceFragmentToUniqueOnes: *NewTEList");
+  for(int i=0;i<NumberOfMolecules;i++) {
+    NewTEList[i] = 0;
+    NewMolList[i] = NULL;
+  }
+  int ReducedNum = 0, j;
+  *out << Verbose(3) << "Reducing TE and Forces lists." << endl;
+  for(int i=0;i<NumberOfMolecules;i++) {                       /// Count new reduced number of molecules ...
+    //*out << Verbose(4) << i << "th TE Value " << " goes to " << Map[i] << ": " << TEList[i] << "." << endl;
+    NewTEList[Map[i]] += TEList[i];
+    if (Map[i] == i) {                           /// ... by checking if Map[i] != i, then Fragment[i] is double of Fragment[Map[i]].
+      *out << Verbose(4) << "Copying molecule " << i << " as it is unique so far ... " << ListOfMolecules[i]<< endl;
+      NewMolList[ReducedNum++] = ListOfMolecules[i];   /// ..., whilst copying each value to temporary list, ...
+    } else {  // else free molecule cause it appears doubly
+      *out << Verbose(4) << "Removing molecule " << i << "." << endl;
+      delete(ListOfMolecules[i]);
+      ListOfMolecules[i] = NULL;
+    }
+  }
+  /// Reallocate \a **FragmentList ...
+  *out << Verbose(3) << "Reallocating to Unique Fragments:" << endl;
+  if ((ReducedNum != 0) && (TEList != 0)) {
+    // factor list
+    *out << Verbose(4) << "Reallocating TEList [" << TEList << "] to " << ReducedNum << endl;
+    TEList = (double *) ReAlloc(TEList, sizeof(double)*ReducedNum, "MoleculeListClass::ReduceFragmentToUniqueOnes: *TEList");
+
+    *out << Verbose(4) << "Copying values to new list: " << endl;
+    j = 0;  // is ReducedNum index
+    for(int i=0;i<NumberOfMolecules;i++) {/// copy value from temporary to return list
+      if (Map[i] == i) {
+      //if (fabs(NewTEList[i]) > MYEPSILON) { // this is a good check also, if TEList[i] = 0 then fragment cancels and may be dropped!
+        TEList[j] = NewTEList[i];
+        *out << Verbose(5) << "TE [i" << i << "<->j" << j << "]:" << NewTEList[i] << "->" << TEList[j];
+        j++;
+      }
+      *out << endl;
+    }
+    if (j != ReducedNum)
+      *out << "Panic:  j " << j << " != ReducedNum " << ReducedNum << "." << endl;
+      
+
+    // molecule list
+    *out << Verbose(4) << "Reallocating ListOfMolecules ... " << endl;
+    ListOfMolecules = (molecule **) ReAlloc(ListOfMolecules, sizeof(molecule *)*ReducedNum, "MoleculeListClass::ReduceFragmentToUniqueOnes: ListOfMolecules");
+    NumberOfMolecules = ReducedNum;
+    /// ... and copy the reduced number back
+    *out << Verbose(5) << "Transfering to ListOfMolecules ... ";
+    for(int i=0;i<ReducedNum;i++) {
+      ListOfMolecules[i] = NewMolList[i];
+      *out << NewMolList[i] << " -> " << ListOfMolecules[i] << "\t";
+    }
+    *out << endl;
+
+
+  } else {
+    Free((void **)&ListOfMolecules, "MoleculeListClass::ReduceFragmentToUniqueOnes: ListOfMolecules");
+    NumberOfMolecules = ReducedNum;
+    *out << Verbose(3) << "ReducedNum is " << ReducedNum << ", Number of Molecules is " << NumberOfMolecules << "." << endl;
+  }
+  // free all the lists again
+  *out << Verbose(3) << "Freeing temporary lists." << endl;
+  Free((void **)&NewTEList, "MoleculeListClass::ReduceFragmentToUniqueOnes: *NewTEList");      /// free temporary list again
+  Free((void **)&NewMolList, "MoleculeListClass::ReduceFragmentToUniqueOnes: *NewMolList");
+  *out << Verbose(2) << "End of ReduceFragmentToUniqueOnes" << endl;
+  return(ReducedNum);
+};
+
+/** Simple output of the pointers in ListOfMolecules.
+ * \param *out output stream
+ */
+void MoleculeListClass::Output(ofstream *out)
+{
+  *out<< Verbose(1) << "MoleculeList: ";
+  for (int i=0;i<NumberOfMolecules;i++)
+    *out << ListOfMolecules[i] << "\t";
+  *out << endl;
+};
+
+/** Writes a config file for each molecule in the given \a **FragmentList.
+ * Note that molecules with a TEList factor of 0 are not stored!
+ * \param *prefix prefix for the file name
+ * \param *configuration standard configuration to attach atoms in fragment molecule to.
+ * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
+ * \return true - success (each file was written), false - something went wrong.
+ */
+bool MoleculeListClass::OutputConfigForListOfFragments(char *prefix, config *configuration, int *SortIndex)
+{
+  ofstream outputFragment;
+  char FragmentName[255];
+  char PathBackup[255];
+  bool result = true;
+  bool intermediateResult = true;
+  atom *Walker = NULL;
+  vector BoxDimension;
+  char TEFilename[255];
+  char *FragmentNumber;
+  int FragmentCounter = 0;
+  ofstream TEFile;
+  ofstream ForcesFile;
+  ofstream KeySetFile;
+  element *runner = NULL;
+  
+  // store the fragments as config and as xyz
+  for(int i=0;i<NumberOfMolecules;i++) {
+    //if (TEList[i] != 0) {
+      strcpy(PathBackup, configuration->GetDefaultPath());
+
+      // scan all atoms in the current molecule for their fathers and write each vertex index to forces file
+
+      // correct periodic
+      ListOfMolecules[i]->ScanForPeriodicCorrection((ofstream *)&cout);
+
+      // output xyz file
+      FragmentNumber = FixedDigitNumber(NumberOfMolecules, FragmentCounter++);
+      sprintf(FragmentName, "%s/%s%s.conf.xyz", PathBackup, prefix, FragmentNumber);
+      outputFragment.open(FragmentName, ios::out);
+      cout << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << " as XYZ ...";
+      if (intermediateResult = ListOfMolecules[i]->OutputXYZ(&outputFragment))
+        cout << " done." << endl;
+      else
+        cout << " failed." << endl;
+      result = result && intermediateResult;
+      outputFragment.close();
+      outputFragment.clear();
+  
+      cout << Verbose(2) << "Contained atoms: ";
+      Walker = ListOfMolecules[i]->start;
+      while (Walker->next != ListOfMolecules[i]->end) {
+        Walker = Walker->next;
+        cout << Walker->Name << " ";
+      }
+      cout << endl;
+      // prepare output of config file
+      sprintf(FragmentName, "%s/%s%s.conf", PathBackup, prefix, FragmentNumber);
+      outputFragment.open(FragmentName, ios::out);
+      strcpy(PathBackup, configuration->GetDefaultPath());
+      sprintf(FragmentName, "%s/%s%s/", PathBackup, prefix, FragmentNumber);
+      
+      // center on edge
+      ListOfMolecules[i]->CenterEdge((ofstream *)&cout, &BoxDimension);
+      ListOfMolecules[i]->SetBoxDimension(&BoxDimension);  // update Box of atoms by boundary
+      int j = -1;
+      for (int k=0;k<3;k++) {
+        j += k+1;
+        BoxDimension.x[k] = 5.;
+        ListOfMolecules[i]->cell_size[j] += BoxDimension.x[k]*2.;
+      }
+      ListOfMolecules[i]->Translate(&BoxDimension);
+
+      // also calculate necessary orbitals
+      ListOfMolecules[i]->CountElements();  // this is a bugfix, atoms should should actually be added correctly to this fragment 
+      ListOfMolecules[i]->CalculateOrbitals(*configuration);
+      
+      // change path in config
+      configuration->SetDefaultPath(FragmentName);
+      cout << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << " as config ...";
+      if (intermediateResult = configuration->Save(&outputFragment, ListOfMolecules[i]->elemente, ListOfMolecules[i]))
+        cout << " done." << endl;
+      else
+        cout << " failed." << endl;
+      // restore old config
+      configuration->SetDefaultPath(PathBackup);
+      
+      result = result && intermediateResult;
+      outputFragment.close();
+      outputFragment.clear();
+      Free((void **)&FragmentNumber, "MoleculeListClass::OutputConfigForListOfFragments: *FragmentNumber");
+    }
+
+  strcpy(PathBackup, configuration->GetDefaultPath());
+  // open file for the total energy factor
+  sprintf(TEFilename, "%s/%s%s", PathBackup, prefix, "TE-Factors.dat");
+  TEFile.open(TEFilename, ios::out);
+  // output TEList (later to file AtomicTEList.dat)
+  cout << Verbose(2) << "Saving " << prefix << " energy factors ...";
+  //cout << Verbose(1) << "Final ATEList: ";
+  //less TEFile << prefix << "TE\t";
+  for(int i=0;i<NumberOfMolecules;i++) {
+    //cout << TEList[i] << "\t";
+    //if (TEList[i] != 0)
+      TEFile << TEList[i] << "\t";
+  }
+  //cout << endl;
+  TEFile << endl;
+  TEFile.close();
+  cout << " done." << endl;
+  
+  // open file for the force factors
+  sprintf(TEFilename, "%s/%s%s", PathBackup, prefix, "Forces-Factors.dat");
+  ForcesFile.open(TEFilename, ios::out);
+  //cout << Verbose(1) << "Final AtomicForcesList: ";
+  cout << Verbose(2) << "Saving " << prefix << " force factors ...";
+  //ForcesFile << prefix << "Forces" << endl;
+  for(int j=0;j<NumberOfMolecules;j++) {
+    //if (TEList[j] != 0) {
+    runner = ListOfMolecules[j]->elemente->start;
+    while (runner->next != ListOfMolecules[j]->elemente->end) { // go through every element
+      runner = runner->next;
+      if (ListOfMolecules[j]->ElementsInMolecule[runner->Z]) { // if this element got atoms
+        Walker = ListOfMolecules[j]->start;
+        while (Walker->next != ListOfMolecules[j]->end) { // go through every atom of this element
+          Walker = Walker->next;
+          if (Walker->type->Z == runner->Z) {
+            if ((Walker->GetTrueFather() != NULL) && (Walker->GetTrueFather() != Walker)) {// if there is a real father, prints its index
+              cerr << "Walker is " << *Walker << " with true father " << *( Walker->GetTrueFather()) << ", its number " << Walker->GetTrueFather()->nr << " and index " << SortIndex[Walker->GetTrueFather()->nr] << "." << endl;  
+              ForcesFile <<  SortIndex[Walker->GetTrueFather()->nr] << "\t";
+            } else  // otherwise a -1 to indicate an added saturation hydrogen
+              ForcesFile << "-1\t";
+          }
+        }
+      }
+    }
+    //cout << endl << endl;
+    ForcesFile << endl;
+  }
+  ForcesFile.close();
+  cout << " done." << endl;
+
+  // open KeySet file
+  sprintf(TEFilename, "%s/%s%s", PathBackup, prefix, "KeySets.dat");
+  KeySetFile.open(TEFilename, ios::out);
+  cout << Verbose(2) << "Saving " << prefix << " key sets of each subgraph ...";
+  for(int j=0;j<NumberOfMolecules;j++) {
+    //if (TEList[j] != 0) {
+      Walker = ListOfMolecules[j]->start;
+      while(Walker->next != ListOfMolecules[j]->end) {
+        Walker = Walker->next;        
+#ifdef ADDHYDROGEN
+        if ((Walker->GetTrueFather() != NULL) && (Walker->type->Z != 1)) // if there is a real father, prints its index
+#else
+        if ((Walker->GetTrueFather() != NULL)) // if there is a real father, prints its index
+#endif 
+          KeySetFile <<  Walker->GetTrueFather()->nr << "\t";
+#ifdef ADDHYDROGEN
+        else  // otherwise a -1 to indicate an added saturation hydrogen
+          KeySetFile << "-1\t";
+#endif 
+      }
+      //cout << endl << endl;
+      KeySetFile << endl;
+    }
+  KeySetFile.close();
+  cout << " done." << endl;
+  
+  // printing final number
+  cout << "Final number of fragments: " << FragmentCounter << "." << endl;
+      
+  return result;
+};
+
+/** Reduce the list of molecules to unique pieces.
+ * molecule::IsEqualToWithinThreshold() is used by GetMappingToUniqueFragments() to provide a mapping for
+ * ReduceFragmentToUniqueOnes(). 
+ * \param *out output stream for debugging
+ * \param cell_size 6 entries specifying the unit cell vectors (matrix is symmetric) for getting the map
+ * \param celldistance needed for linked-cell technique when getting the map
+ */
+void MoleculeListClass::ReduceToUniqueList(ofstream *out, double *cell_size, double celldistance)
+{
+  int *ReduceMapping = NULL;
+  
+  *out << Verbose(0) << "Begin of ReduceToUniqueList." << endl; 
+  // again, check whether there are equal fragments by ReduceToUniqueOnes
+  *out << Verbose(1) << "Get reduce mapping." << endl;
+  ReduceMapping = GetMappingToUniqueFragments(out, 0.05, cell_size, celldistance);
+  *out << Verbose(1) << "MapList: ";
+  for(int i=0;i<NumberOfMolecules;i++)
+    *out << ReduceMapping[i] << " ";
+  *out << endl << endl;
+  *out << Verbose(1) << "Apply reduce mapping." << endl;
+  ReduceFragmentToUniqueOnes(out, ReduceMapping);
+  Free((void **)&ReduceMapping, "MoleculeListClass::FragmentTopDown: *ReduceMapping");  // free map after reduce
+  *out << Verbose(1) << "Number of Fragments after Reducing is " << NumberOfMolecules << "." << endl;
+  *out << Verbose(0) << "End of ReduceToUniqueList." << endl; 
+};
+
+/** Fragments a molecule and resulting pieces recursively until the number of bonds
+ * Here the idea is similar to the FragmentBottomUp() approach, only that we split up the molecule
+ * bond per bond into left and right fragments and this recursively also with each yielded
+ * fragment until there is no fragment with continuous number of bonds greater than \a BondDegree.
+ * are below the given \a BondDegree.
+ * \param *out output stream for debugging
+ * \param BondDegree maximum number of continuous bonds in a fragment
+ * \param bonddistance typical bond distance
+ * \param *configuration configuration for writing config files for each fragment
+ * \param CutCyclic cut cyclic bonds (saturate with hydrogen) or add 
+ * \return pointer to MoleculeListClass with all the fragments or NULL if something went wrong.
+ * \todo so far we volontarily mix up the above BondDegree definition and molecule::NoNonBonds
+ * 
+ * \bug  FragmentTopDown does not work right now due to NULL being given as cell_size to ReduceToUniqueOnes()
+ */
+MoleculeListClass * MoleculeListClass::FragmentTopDown(ofstream *out, int BondDegree, double bonddistance, config *configuration, enum CutCyclicBond CutCyclic)
+{
+  int Num, No, Cyclic, NoBonds;
+  MoleculeListClass *ReturnList = NULL;
+  MoleculeListClass **FragmentsList = NULL;
+  molecule *CurrentMolecule = NULL;
+  bond *Binder = NULL;
+ 
+  *out << Verbose(0) << "Begin of FragmentTopDown:" << this << "." << endl; 
+  Num = 0;
+  FragmentsList = (MoleculeListClass **) Malloc(sizeof(MoleculeListClass *)*NumberOfMolecules, "MoleculeListClass::FragmentTopDown: **FragmentsList");
+  // fragment each molecule into its own MoleculeListClass
+  for(int i=0;i<NumberOfMolecules;i++) {
+    CurrentMolecule = ListOfMolecules[i];
+    CurrentMolecule->CountAtoms(out);
+    Cyclic = CurrentMolecule->CountCyclicBonds(out);
+    NoBonds = 
+#ifdef ADDHYDROGEN
+CurrentMolecule->NoNonBonds
+#else 
+CurrentMolecule->BondCount
+#endif 
+                - ((CutCyclic == KeepBond) ? Cyclic : 0);
+    // check if NoNonBonds < BondDegree, then don't split any further: Here, correct for greatest continuous bond length!
+    *out << Verbose(0) << "Checking on Number of true Bonds " << NoBonds << " (i.e. no -H, if chosen no cyclic) greater than " << BondDegree << "." << endl;
+    if (NoBonds > BondDegree) {
+      //cerr << Verbose(1) << "TopDown Level of Molecule " << CurrentMolecule << ": " << (CurrentMolecule->NoNonBonds - BondDegree) << "." << endl; 
+      *out << Verbose(1) << "Breaking up molecule " << i << " in fragment list." << endl;
+      CurrentMolecule->CreateListOfBondsPerAtom(out);
+      // Get atomic fragments for the list
+      *out << Verbose(1) << "Getting Atomic fragments for molecule " << i << "." << endl;
+      MoleculeListClass *AtomicFragments = CurrentMolecule->GetAtomicFragments(out, NumberOfTopAtoms, configuration->GetIsAngstroem(), TEList[i]/(1. - NoBonds), CutCyclic);
+      
+      // build the atomic part of the list of molecules
+      *out << Verbose(1) << "Putting atomic fragment into list of molecules." << endl;
+      
+      // cutting cyclic bonds yields only a single fragment, not two as non-cyclic!
+      No = (CutCyclic == KeepBond) ? ((
+#ifdef ADDHYDROGEN
+CurrentMolecule->NoNonBonds - Cyclic)*2) : CurrentMolecule->NoNonBonds*2 - Cyclic; 
+#else 
+CurrentMolecule->BondCount - Cyclic)*2) : CurrentMolecule->BondCount*2 - Cyclic; 
+#endif 
+      
+      if (AtomicFragments != NULL) {
+        ReturnList = new MoleculeListClass(No+AtomicFragments->NumberOfMolecules, NumberOfTopAtoms);
+        for (int j=0;j<AtomicFragments->NumberOfMolecules;j++) { // shift all Atomic Fragments into this one here
+          ReturnList->ListOfMolecules[j+No] = AtomicFragments->ListOfMolecules[j];
+          AtomicFragments->ListOfMolecules[j] = NULL;
+          ReturnList->ListOfMolecules[j+No]->NoNonBonds = 0;
+          ReturnList->ListOfMolecules[j+No]->NoNonHydrogen = 1;
+          ReturnList->TEList[j+No] = AtomicFragments->TEList[j];
+        }
+        *out << Verbose(3) << "Freeing Atomic memory" << endl;
+        delete(AtomicFragments);
+        AtomicFragments = NULL;
+      } else {
+        *out << Verbose(2) << "AtomicFragments is NULL, filling list with whole molecule only." << endl; 
+        ReturnList = new MoleculeListClass(No, NumberOfTopAtoms);
+      }
+
+      // build the side pieces part of the list of molecules
+      *out << Verbose(1) << "Building side piece fragments and putting into list of molecules." << endl;
+      No = 0;
+      Binder = CurrentMolecule->first;
+      while(Binder->next != CurrentMolecule->last) {
+        Binder = Binder->next;
+#ifdef ADDHYDROGEN
+        if (Binder->HydrogenBond == 0)
+#endif        
+          if ((CutCyclic == SaturateBond) || (!Binder->Cyclic)) {
+            // split each bond into left and right side piece
+            if (Binder->Cyclic) {
+              molecule *dummy = NULL; // we lazily hand FragmentMoleculeByBond() a dummy as second fragment and ... 
+              *out << Verbose(1) << "Breaking up " << Binder->nr << "th and " << No << "th non-hydrogen, CYCLIC bond " << *Binder << " of molecule " << i << " [" << CurrentMolecule << "] into a single pieces." << endl; 
+              CurrentMolecule->FragmentMoleculeByBond(out, Binder, &(ReturnList->ListOfMolecules[No]), &(dummy), configuration->GetIsAngstroem(), CutCyclic);
+              delete(dummy);  // ... free the dummy which is due to the cyclic bond the exacy same fragment
+              *out << Verbose(1) << "Single fragment is " << ReturnList->ListOfMolecules[No] << "." << endl;
+      
+              // write down the necessary TE-summation in order to regain TE of whole molecule
+              *out << Verbose(2) << "Creating TEList for Fragment " << i << " of Bond " << No << "." << endl;
+#ifdef ADDHYDROGEN
+              ReturnList->TEList[No] = -TEList[i]/(1. -CurrentMolecule->NoNonBonds);
+#else              
+              ReturnList->TEList[No] = -TEList[i]/(1. -CurrentMolecule->BondCount);
+#endif
+            } else {
+              *out << Verbose(1) << "Breaking up " << Binder->nr << "th and " << No << "th non-hydrogen, non-cyclic bond " << *Binder << " of molecule " << i << " [" << CurrentMolecule << "] into left and right side pieces." << endl; 
+              CurrentMolecule->FragmentMoleculeByBond(out, Binder, &(ReturnList->ListOfMolecules[No]), &(ReturnList->ListOfMolecules[No+1]), configuration->GetIsAngstroem(), CutCyclic);
+              *out << Verbose(1) << "Left Fragment is " << ReturnList->ListOfMolecules[No] << ", right Fragment is " << ReturnList->ListOfMolecules[No+1] << "." << endl;
+      
+              // write down the necessary TE-summation in order to regain TE of whole molecule
+              *out << Verbose(2) << "Creating TEList for Fragment " << i << " of Bond " << No << "." << endl;
+              ReturnList->TEList[No] = -TEList[i]/(1. - NoBonds);
+              ReturnList->TEList[No+1] = -TEList[i]/(1. - NoBonds);
+            }
+            No += ((Binder->Cyclic) ? 1 : 2);
+          }
+      }
+
+      // Reduce this list
+      ReturnList->ReduceToUniqueList(out, NULL, bonddistance);
+
+      // recurse and receive List
+      *out << Verbose(1) << "Calling TopDown " << ReturnList<< " with filled list: ";
+      ReturnList->Output(out);
+      FragmentsList[i] = ReturnList->FragmentTopDown(out, BondDegree, bonddistance, configuration, CutCyclic);
+      *out << Verbose(1) << "Returning from TopDown " << ReturnList<< " with filled list: ";
+      ReturnList->Output(out);
+      
+      // remove list after we're done
+      *out << Verbose(2) << "Removing caller list." << endl;
+      delete(ReturnList);
+      ReturnList = NULL;
+      
+    } else {  // create a list with only a single molecule inside, transfer everything from "this" list to return list
+      *out << Verbose(1) << "Not breaking up molecule " << i << " in fragment list." << endl;
+      FragmentsList[i] = new MoleculeListClass(1, NumberOfTopAtoms);
+      FragmentsList[i]->ListOfMolecules[0] = ListOfMolecules[i];
+      ListOfMolecules[i] = NULL;
+      FragmentsList[i]->TEList[0] = TEList[i]; 
+    }
+    Num += FragmentsList[i]->NumberOfMolecules;
+  }
+  
+  // now, we have a list of MoleculeListClasses: combine all fragments list into one single list
+  *out << Verbose(2) << "Combining to a list of " << Num << " molecules and Memory cleanup of old list of lists." << endl; 
+  ReturnList = new MoleculeListClass(Num, NumberOfTopAtoms);
+  No = 0;
+  for(int i=0;i<NumberOfMolecules;i++) {
+    for(int j=0;j<FragmentsList[i]->NumberOfMolecules;j++) {
+      // transfer molecule
+      ReturnList->ListOfMolecules[No] = FragmentsList[i]->ListOfMolecules[j];
+      FragmentsList[i]->ListOfMolecules[j] = NULL;
+      // transfer TE factor
+      ReturnList->TEList[No] = FragmentsList[i]->TEList[j];
+      No++;
+    }
+    delete(FragmentsList[i]);
+    FragmentsList[i] = NULL;
+  }
+  Free((void **)&FragmentsList, "MoleculeListClass::FragmentTopDown: **FragmentsList");
+  
+  // Reduce the list to unique fragments
+  ReturnList->ReduceToUniqueList(out, NULL, bonddistance);
+  
+  // return pointer to list
+  *out << Verbose(0) << "Return with filled list: ";
+  ReturnList->Output(out);
+  
+  *out << Verbose(0) << "End of FragmentTopDown:" << this << "." << endl; 
+  return (ReturnList);
+}; 
+
+/******************************************* Class MoleculeLeafClass ************************************************/
+
+/** Constructor for MoleculeLeafClass root leaf.
+ * \param *Up Leaf on upper level
+ * \param *PreviousLeaf NULL - We are the first leaf on this level, otherwise points to previous in list
+ */
+//MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *Up = NULL, MoleculeLeafClass *Previous = NULL)
+MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *PreviousLeaf = NULL)
+{
+//  if (Up != NULL)
+//    if (Up->DownLeaf == NULL) // are we the first down leaf for the upper leaf?
+//      Up->DownLeaf = this;
+//  UpLeaf = Up;
+//  DownLeaf = NULL;
+  Leaf = NULL;
+  previous = PreviousLeaf;
+  if (previous != NULL) {
+    MoleculeLeafClass *Walker = previous->next;
+    previous->next = this;
+    next = Walker;
+  } else {
+    next = NULL;
+  }
+};
+
+/** Destructor for MoleculeLeafClass.
+ */
+MoleculeLeafClass::~MoleculeLeafClass()
+{
+//  if (DownLeaf != NULL) {// drop leaves further down
+//    MoleculeLeafClass *Walker = DownLeaf;
+//    MoleculeLeafClass *Next;
+//    do {
+//      Next = Walker->NextLeaf;
+//      delete(Walker);
+//      Walker = Next;
+//    } while (Walker != NULL);
+//    // Last Walker sets DownLeaf automatically to NULL
+//  }
+  // remove the leaf itself
+  if (Leaf != NULL) {
+    delete(Leaf);
+    Leaf = NULL;
+  }
+  // remove this Leaf from level list
+  if (previous != NULL)   
+    previous->next = next;
+//  } else { // we are first in list (connects to UpLeaf->DownLeaf)
+//    if ((NextLeaf != NULL) && (NextLeaf->UpLeaf == NULL))
+//      NextLeaf->UpLeaf = UpLeaf;  // either null as we are top level or the upleaf of the first node
+//    if (UpLeaf != NULL)
+//      UpLeaf->DownLeaf = NextLeaf;  // either null as we are only leaf or NextLeaf if we are just the first
+//  }
+//  UpLeaf = NULL;
+  if (next != NULL) // are we last in list
+    next->previous = previous;
+  next = NULL;
+  previous = NULL;
+};
+
+/** Adds \a molecule leaf to the tree.
+ * \param *ptr ptr to molecule to be added
+ * \param *Previous previous MoleculeLeafClass referencing level and which on the level
+ * \return true - success, false - something went wrong
+ */
+bool MoleculeLeafClass::AddLeaf(molecule *ptr, MoleculeLeafClass *Previous)
+{
+  return false;
+};
Index: molecuilder/src/molecules.cpp
===================================================================
--- molecuilder/src/molecules.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/molecules.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,3835 @@
+/** \file molecules.cpp
+ * 
+ * Functions for the class molecule.
+ * 
+ */
+
+#include "molecules.hpp"
+
+
+/************************************* Other Functions *************************************/
+
+/** Determines sum of squared distances of \a X to all \a **vectors.
+ * \param *x reference vector
+ * \param *params
+ * \return sum of square distances
+ */
+double LSQ (const gsl_vector * x, void * params)
+{
+  double sum = 0.;
+  struct LSQ_params *par = (struct LSQ_params *)params;
+  vector **vectors = par->vectors;
+  int num = par->num;
+
+  for (int i=0;i<num;i++) {
+    for(int j=0;j<NDIM;j++)
+      sum += (gsl_vector_get(x,j) - (vectors[i])->x[j])*(gsl_vector_get(x,j) - (vectors[i])->x[j]);
+  }
+  
+  return sum;
+};
+
+/************************************* Functions for class molecule *********************************/
+
+/** Constructor of class molecule.
+ * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
+ */
+molecule::molecule(periodentafel *teil) 
+{ 
+  // init atom chain list
+  start = new atom; 
+  end = new atom;
+  start->father = NULL; 
+  end->father = NULL;
+  link(start,end);
+  // init bond chain list
+  first = new bond(start, end, 1, -1);
+  last = new bond(start, end, 1, -1);
+  link(first,last);
+  // other stuff 
+  last_atom = 0; 
+  elemente = teil;
+  AtomCount = 0;
+  BondCount = 0;
+  NoNonBonds = 0;
+	NoNonHydrogen = 0;
+  NoCyclicBonds = 0;
+  ListOfBondsPerAtom = NULL;
+  NumberOfBondsPerAtom = NULL;
+  ElementCount = 0;
+  for(int i=0;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.;
+};
+
+/** Destructor of class molecule.
+ * Initialises molecule list with correctly referenced start and end, and sets molecule::last_atom to zero.
+ */
+molecule::~molecule() 
+{
+  if (ListOfBondsPerAtom != NULL)
+    for(int i=0;i<AtomCount;i++)
+      Free((void **)&ListOfBondsPerAtom[i], "molecule::~molecule: ListOfBondsPerAtom[i]");
+  Free((void **)&ListOfBondsPerAtom, "molecule::~molecule: ListOfBondsPerAtom");
+  Free((void **)&NumberOfBondsPerAtom, "molecule::~molecule: NumberOfBondsPerAtom");
+  CleanupMolecule();
+  delete(first);
+  delete(last);
+  delete(end);
+  delete(start); 
+};
+
+/** Adds given atom \a *pointer from molecule list.
+ * Increases molecule::last_atom and gives last number to added atom and names it according to its element::abbrev and molecule::AtomCount 
+ * \param *pointer allocated and set atom
+ * \return true - succeeded, false - atom not found in list
+ */
+bool molecule::AddAtom(atom *pointer)
+{ 
+  if (pointer != NULL) {
+    pointer->sort = &pointer->nr; 
+    pointer->nr = last_atom++;  // increase number within molecule
+    AtomCount++;
+    if (pointer->type != NULL) {
+      if (ElementsInMolecule[pointer->type->Z] == 0)
+        ElementCount++;
+      ElementsInMolecule[pointer->type->Z]++; // increase number of elements
+      if (pointer->type->Z != 1)
+        NoNonHydrogen++;
+      if (pointer->Name == NULL) {
+        Free((void **)&pointer->Name, "molecule::AddAtom: *pointer->Name");
+        pointer->Name = (char *) Malloc(sizeof(char)*6, "molecule::AddAtom: *pointer->Name");
+        sprintf(pointer->Name, "%2s%02d", pointer->type->symbol, pointer->nr+1);
+      }
+    }
+    return add(pointer, end);
+  } else
+    return false; 
+};
+
+/** Adds a copy of the given atom \a *pointer from molecule list.
+ * Increases molecule::last_atom and gives last number to added atom.
+ * \param *pointer allocated and set atom
+ * \return true - succeeded, false - atom not found in list
+ */
+atom * molecule::AddCopyAtom(atom *pointer)
+{ 
+  if (pointer != NULL) {
+  	atom *walker = new atom();
+  	walker->type = pointer->type;	// copy element of atom
+  	walker->x.CopyVector(&pointer->x); // copy coordination
+    walker->sort = &walker->nr; 
+    walker->nr = last_atom++;  // increase number within molecule
+    walker->father = pointer; //->GetTrueFather();
+    walker->Name = (char *) Malloc(sizeof(char)*strlen(pointer->Name)+1, "molecule::AddCopyAtom: *Name");
+    strcpy (walker->Name, pointer->Name);
+    add(walker, end);
+    if ((pointer->type != NULL) && (pointer->type->Z != 1))
+      NoNonHydrogen++;
+    AtomCount++;
+    return walker;
+  } else
+    return NULL; 
+};
+
+/** Adds a Hydrogen atom in replacement for the given atom \a *partner in bond with a *origin.
+ * Here, we have to distinguish between single, double or triple bonds as stated by \a BondDegree, that each demand
+ * a different scheme when adding \a *replacement atom for the given one.
+ * -# Single Bond: Simply add new atom with bond distance rescaled to typical hydrogen one
+ * -# Double Bond: Here, we need the **BondList of the \a *origin atom, by scanning for the other bonds instead of
+ *    *Bond, we use the through these connected atoms to determine the plane they lie in, vector::MakeNormalVector().
+ *    The orthonormal vector to this plane along with the vector in *Bond direction determines the plane the two
+ *    replacing hydrogens shall lie in. Now, all remains to do is take the usual hydrogen double bond angle for the
+ *    element of *origin and form the sin/cos admixture of both plane vectors for the new coordinates of the two
+ *    hydrogens forming this angle with *origin.
+ * -# Triple Bond: The idea is to set up a tetraoid (C1-H1-H2-H3) (however the lengths \f$b\f$ of the sides of the base
+ *    triangle formed by the to be added hydrogens are not equal to the typical bond distance \f$l\f$ but have to be
+ *    determined from the typical angle \f$\alpha\f$ for a hydrogen triple connected to the element of *origin):
+ *    We have the height \f$d\f$ as the vector in *Bond direction (from triangle C1-H1-H2).
+ *    \f[ h = l \cdot \cos{\left (\frac{\alpha}{2} \right )} \qquad b = 2l \cdot \sin{\left (\frac{\alpha}{2} \right)} \quad \rightarrow \quad d = l \cdot \sqrt{\cos^2{\left (\frac{\alpha}{2} \right)}-\frac{1}{3}\cdot\sin^2{\left (\frac{\alpha}{2}\right )}}
+ *    \f]
+ *    vector::GetNormalVector() creates one orthonormal vector from this *Bond vector and vector::MakeNormalVector creates
+ *    the third one from the former two vectors. The latter ones form the plane of the base triangle mentioned above.
+ *    The lengths for these are \f$f\f$ and \f$g\f$ (from triangle H1-H2-(center of H1-H2-H3)) with knowledge that
+ *    the median lines in an isosceles triangle meet in the center point with a ratio 2:1.
+ *    \f[ f = \frac{b}{\sqrt{3}} \qquad g = \frac{b}{2} 
+ *    \f]
+ *    as the coordination of all three atoms in the coordinate system of these three vectors: 
+ *    \f$\pmatrix{d & f & 0}\f$, \f$\pmatrix{d & -0.5 \cdot f & g}\f$ and \f$\pmatrix{d & -0.5 \cdot f & -g}\f$.
+ * 
+ * \param *out output stream for debugging
+ * \param *Bond pointer to bond between \a *origin and \a *replacement 
+ * \param *TopOrigin son of \a *origin of upper level molecule (the atom added to this molecule as a copy of \a *origin) 
+ * \param *origin pointer to atom which acts as the origin for scaling the added hydrogen to correct bond length
+ * \param *replacement pointer to the atom which shall be copied as a hydrogen atom in this molecule
+ * \param **BondList list of bonds \a *replacement has (necessary to determine plane for double and triple bonds)
+ * \param NumBond  number of bonds in \a **BondList
+ * \param isAngstroem whether the coordination of the given atoms is in AtomicLength (false) or Angstrom(true)
+ * \return number of atoms added, if < bond::BondDegree then something went wrong
+ * \todo double and triple bonds splitting (always use the tetraeder angle!)
+ */
+bool molecule::AddHydrogenReplacementAtom(ofstream *out, bond *TopBond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bond **BondList, int NumBond, bool IsAngstroem)
+{
+  double bondlength;  // bond length of the bond to be replaced/cut
+  double bondangle;  // bond angle of the bond to be replaced/cut
+  double BondRescale;   // rescale value for the hydrogen bond length
+  bool AllWentWell = true;    // flag gathering the boolean return value of molecule::AddAtom and other functions, as return value on exit
+  bond *FirstBond = NULL, *SecondBond = NULL; // Other bonds in double bond case to determine "other" plane
+  atom *FirstOtherAtom = NULL, *SecondOtherAtom = NULL, *ThirdOtherAtom = NULL; // pointer to hydrogen atoms to be added
+  int i;  // loop variable
+  double b,l,d,f,g, alpha, factors[NDIM];    // hold temporary values in triple bond case for coordination determination
+  vector OrthoVector1, OrthoVector2;  // temporary vectors in coordination construction
+  vector InBondVector;    // vector in direction of *Bond
+  bond *Binder = NULL;
+  double *matrix;
+
+	*out << Verbose(3) << "Begin of AddHydrogenReplacementAtom." << endl;
+  // create vector in direction of bond
+  InBondVector.CopyVector(&TopReplacement->x);
+  InBondVector.SubtractVector(&TopOrigin->x);
+  bondlength = InBondVector.Norm();
+   
+   // is greater than typical bond distance? Then we have to correct periodically
+   // the problem is not the H being out of the box, but InBondVector have the wrong direction
+   // due to TopReplacement or Origin being on the wrong side! 
+  if (bondlength > BondDistance) { 
+    *out << Verbose(4) << "InBondVector is: ";
+    InBondVector.Output(out);
+    *out << endl;
+    OrthoVector1.Zero();
+    for (int i=0;i<NDIM;i++) {
+      l = TopReplacement->x.x[i] - TopOrigin->x.x[i];
+      if (fabs(l) > BondDistance) { // is component greater than bond distance
+        OrthoVector1.x[i] = (l < 0) ? -1. : +1.;
+      } // (signs are correct, was tested!)
+    }
+    matrix = ReturnFullMatrixforSymmetric(cell_size);
+    OrthoVector1.MatrixMultiplication(matrix);
+    InBondVector.SubtractVector(&OrthoVector1); // subtract just the additional translation
+    Free((void **)&matrix, "molecule::AddHydrogenReplacementAtom: *matrix");
+    bondlength = InBondVector.Norm();
+    *out << Verbose(4) << "Corrected InBondVector is now: ";
+    InBondVector.Output(out);
+    *out << endl;
+  } // periodic correction finished
+  
+  InBondVector.Normalize();
+  // get typical bond length and store as scale factor for later
+  BondRescale = TopOrigin->type->HBondDistance[TopBond->BondDegree-1];
+  if (BondRescale == -1) {
+    cerr << Verbose(3) << "WARNING: There is no typical bond distance for bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
+    BondRescale = bondlength; 
+  } else {
+    if (!IsAngstroem)
+      BondRescale /= (1.*AtomicLengthToAngstroem);
+  }
+
+  // discern single, double and triple bonds
+  switch(TopBond->BondDegree) {
+    case 1:
+      FirstOtherAtom = new atom();    // new atom
+      FirstOtherAtom->type = elemente->FindElement(1);  // element is Hydrogen
+      if (TopReplacement->type->Z == 1) { // neither rescale nor replace if it's already hydrogen
+        FirstOtherAtom->father = TopReplacement;
+        BondRescale = bondlength;
+      } else {
+        FirstOtherAtom->father = NULL;  // if we replace hydrogen, we mark it as our father, otherwise we are just an added hydrogen with no father
+      }
+      InBondVector.Scale(&BondRescale);   // rescale the distance vector to Hydrogen bond length
+      FirstOtherAtom->x.CopyVector(&TopOrigin->x); // set coordination to origin ...
+      FirstOtherAtom->x.AddVector(&InBondVector);  // ... and add distance vector to replacement atom
+      AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
+      *out << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
+      FirstOtherAtom->x.Output(out);
+      *out << endl;
+      Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
+      Binder->Cyclic = false;
+      Binder->Type = TreeEdge;
+      break;
+    case 2:
+      // determine two other bonds (warning if there are more than two other) plus valence sanity check
+      for (i=0;i<NumBond;i++) {
+        if (BondList[i] != TopBond) {
+          if (FirstBond == NULL) {
+            FirstBond = BondList[i];
+            FirstOtherAtom = BondList[i]->GetOtherAtom(TopOrigin);
+          } else if (SecondBond == NULL) {
+            SecondBond = BondList[i];
+            SecondOtherAtom = BondList[i]->GetOtherAtom(TopOrigin);
+          } else {
+            *out << Verbose(3) << "WARNING: Detected more than four bonds for atom " << TopOrigin->Name;
+          }
+        }
+      }
+      if (SecondOtherAtom == NULL) {  // then we have an atom with valence four, but only 3 bonds: one to replace and one which is TopBond (third is FirstBond)
+        SecondBond = TopBond;
+        SecondOtherAtom = TopReplacement;
+      }
+      if (FirstOtherAtom != NULL) { // then we just have this double bond and the plane does not matter at all
+        *out << Verbose(3) << "Regarding the double bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") to be constructed: Taking " << FirstOtherAtom->Name << " and " << SecondOtherAtom->Name << " along with " << TopOrigin->Name << " to determine orthogonal plane." << endl;
+        
+        // determine the plane of these two with the *origin
+        AllWentWell = AllWentWell && OrthoVector1.MakeNormalVector(&TopOrigin->x, &FirstOtherAtom->x, &SecondOtherAtom->x);
+      } else {
+        OrthoVector1.GetOneNormalVector(&InBondVector);
+      }
+      //*out << Verbose(3)<< "Orthovector1: ";
+      //OrthoVector1.Output(out);
+      //*out << endl;
+      // orthogonal vector and bond vector between origin and replacement form the new plane
+      OrthoVector1.MakeNormalVector(&InBondVector);
+      OrthoVector1.Normalize();
+      //*out << Verbose(3) << "ReScaleCheck: " << OrthoVector1.Norm() << " and " << InBondVector.Norm() << "." << endl;
+      
+      // create the two Hydrogens ...
+      FirstOtherAtom = new atom();
+      SecondOtherAtom = new atom();
+      FirstOtherAtom->type = elemente->FindElement(1);
+      SecondOtherAtom->type = elemente->FindElement(1);
+      FirstOtherAtom->father = NULL;  // we are just an added hydrogen with no father
+      SecondOtherAtom->father = NULL;  //  we are just an added hydrogen with no father
+      bondangle = TopOrigin->type->HBondAngle[1];
+      if (bondangle == -1) {
+        *out << Verbose(3) << "WARNING: There is no typical bond angle for bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
+        bondangle = 0;
+      }
+      bondangle *= M_PI/180./2.;
+//      *out << Verbose(3) << "ReScaleCheck: InBondVector ";
+//      InBondVector.Output(out);
+//      *out << endl;
+//      *out << Verbose(3) << "ReScaleCheck: Orthovector ";
+//      OrthoVector1.Output(out);
+//      *out << endl;
+      *out << Verbose(3) << "Half the bond angle is " << bondangle << ", sin and cos of it: " << sin(bondangle) << ", " << cos(bondangle) << endl;
+      FirstOtherAtom->x.Zero();
+      SecondOtherAtom->x.Zero();
+      for(i=0;i<NDIM;i++) { // rotate by half the bond angle in both directions (InBondVector is bondangle = 0 direction)
+        FirstOtherAtom->x.x[i] = InBondVector.x[i] * cos(bondangle) + OrthoVector1.x[i] * (sin(bondangle));
+        SecondOtherAtom->x.x[i] = InBondVector.x[i] * cos(bondangle) + OrthoVector1.x[i] * (-sin(bondangle));
+      }
+      FirstOtherAtom->x.Scale(&BondRescale);  // rescale by correct BondDistance 
+      SecondOtherAtom->x.Scale(&BondRescale);
+      //*out << Verbose(3) << "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << "." << endl;
+      for(i=0;i<NDIM;i++) { // and make relative to origin atom
+        FirstOtherAtom->x.x[i] += TopOrigin->x.x[i]; 
+        SecondOtherAtom->x.x[i] += TopOrigin->x.x[i];
+      }
+      // ... and add to molecule
+      AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
+      AllWentWell = AllWentWell && AddAtom(SecondOtherAtom);
+      *out << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
+      FirstOtherAtom->x.Output(out);
+      *out << endl;
+      *out << Verbose(4) << "Added " << *SecondOtherAtom << " at: ";
+      SecondOtherAtom->x.Output(out);
+      *out << endl;
+      Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
+      Binder->Cyclic = false;
+      Binder->Type = TreeEdge;
+      Binder = AddBond(BottomOrigin, SecondOtherAtom, 1);
+      Binder->Cyclic = false;
+      Binder->Type = TreeEdge;
+      break;
+    case 3:
+      // take the "usual" tetraoidal angle and add the three Hydrogen in direction of the bond (height of the tetraoid)
+      FirstOtherAtom = new atom();
+      SecondOtherAtom = new atom();
+      ThirdOtherAtom = new atom();
+      FirstOtherAtom->type = elemente->FindElement(1);
+      SecondOtherAtom->type = elemente->FindElement(1);
+      ThirdOtherAtom->type = elemente->FindElement(1);
+      FirstOtherAtom->father = NULL;  //  we are just an added hydrogen with no father
+      SecondOtherAtom->father = NULL;  //  we are just an added hydrogen with no father
+      ThirdOtherAtom->father = NULL;  //  we are just an added hydrogen with no father
+
+      // we need to vectors orthonormal the InBondVector
+      AllWentWell = AllWentWell && OrthoVector1.GetOneNormalVector(&InBondVector);
+      *out << Verbose(3) << "Orthovector1: ";
+      OrthoVector1.Output(out);
+      *out << endl;
+      AllWentWell = AllWentWell && OrthoVector2.MakeNormalVector(&InBondVector, &OrthoVector1);
+      *out << Verbose(3) << "Orthovector2: "; 
+      OrthoVector2.Output(out);
+      *out << endl;
+      
+      // create correct coordination for the three atoms
+      alpha = (TopOrigin->type->HBondAngle[2])/180.*M_PI/2.;  // retrieve triple bond angle from database
+      l = BondRescale;        // desired bond length
+      b = 2.*l*sin(alpha);    // base length of isosceles triangle
+      d = l*sqrt(cos(alpha)*cos(alpha) - sin(alpha)*sin(alpha)/3.);   // length for InBondvector
+      f = b/sqrt(3.);   // length for OrthVector1
+      g = b/2.;         // length for OrthVector2
+      *out << Verbose(3) << "Bond length and half-angle: " << l << ", " << alpha << "\t (b,d,f,g) = " << b << ", " << d << ", " << f << ", " << g << ", " << endl;
+      *out << Verbose(3) << "The three Bond lengths: " << sqrt(d*d+f*f) << ", " << sqrt(d*d+(-0.5*f)*(-0.5*f)+g*g) << ", "  << sqrt(d*d+(-0.5*f)*(-0.5*f)+g*g) << endl;
+      factors[0] = d;
+      factors[1] = f;
+      factors[2] = 0.; 
+      FirstOtherAtom->x.LinearCombinationOfVectors(&InBondVector, &OrthoVector1, &OrthoVector2, factors);
+      factors[1] = -0.5*f;
+      factors[2] = g; 
+      SecondOtherAtom->x.LinearCombinationOfVectors(&InBondVector, &OrthoVector1, &OrthoVector2, factors);
+      factors[2] = -g; 
+      ThirdOtherAtom->x.LinearCombinationOfVectors(&InBondVector, &OrthoVector1, &OrthoVector2, factors);
+
+      // rescale each to correct BondDistance
+//      FirstOtherAtom->x.Scale(&BondRescale);
+//      SecondOtherAtom->x.Scale(&BondRescale);
+//      ThirdOtherAtom->x.Scale(&BondRescale);
+
+      // and relative to *origin atom
+      FirstOtherAtom->x.AddVector(&TopOrigin->x);
+      SecondOtherAtom->x.AddVector(&TopOrigin->x);
+      ThirdOtherAtom->x.AddVector(&TopOrigin->x);
+
+      // ... and add to molecule
+      AllWentWell = AllWentWell && AddAtom(FirstOtherAtom);
+      AllWentWell = AllWentWell && AddAtom(SecondOtherAtom);
+      AllWentWell = AllWentWell && AddAtom(ThirdOtherAtom);
+      *out << Verbose(4) << "Added " << *FirstOtherAtom << " at: ";
+      FirstOtherAtom->x.Output(out);
+      *out << endl;
+      *out << Verbose(4) << "Added " << *SecondOtherAtom << " at: ";
+      SecondOtherAtom->x.Output(out);
+      *out << endl;
+      *out << Verbose(4) << "Added " << *ThirdOtherAtom << " at: ";
+      ThirdOtherAtom->x.Output(out);
+      *out << endl;
+      Binder = AddBond(BottomOrigin, FirstOtherAtom, 1);
+      Binder->Cyclic = false;
+      Binder->Type = TreeEdge;
+      Binder = AddBond(BottomOrigin, SecondOtherAtom, 1);
+      Binder->Cyclic = false;
+      Binder->Type = TreeEdge;
+      Binder = AddBond(BottomOrigin, ThirdOtherAtom, 1);
+      Binder->Cyclic = false;
+      Binder->Type = TreeEdge;
+      break;
+    default:
+      cerr << "ERROR: BondDegree does not state single, double or triple bond!" << endl;
+      AllWentWell = false;
+      break;
+  }
+
+	*out << Verbose(3) << "End of AddHydrogenReplacementAtom." << endl;
+  return AllWentWell;
+};
+
+/** Adds given atom \a *pointer from molecule list.
+ * Increases molecule::last_atom and gives last number to added atom.
+ * \param filename name and path of xyz file
+ * \return true - succeeded, false - file not found
+ */
+bool molecule::AddXYZFile(string filename)
+{ 
+  istringstream *input = NULL;
+  int NumberOfAtoms = 0; // atom number in xyz read
+  int i, j; // loop variables
+  atom *first = NULL;  // pointer to added atom
+  char shorthand[3];  // shorthand for atom name
+  ifstream xyzfile;   // xyz file
+  string line;    // currently parsed line
+  double x[3];    // atom coordinates
+  
+  xyzfile.open(filename.c_str());
+  if (!xyzfile)
+    return false;
+
+  getline(xyzfile,line,'\n'); // Read numer of atoms in file
+  input = new istringstream(line);
+  *input >> NumberOfAtoms;
+  cout << Verbose(0) << "Parsing " << NumberOfAtoms << " atoms in file." << endl; 
+  getline(xyzfile,line,'\n'); // Read comment
+  cout << Verbose(1) << "Comment: " << line << endl;
+
+  for(i=0;i<NumberOfAtoms;i++){
+    first = new atom;
+    getline(xyzfile,line,'\n');
+    istringstream *item = new istringstream(line);
+    //istringstream input(line);
+    cout << Verbose(1) << "Reading: " << line << endl;
+    *item >> shorthand;
+    *item >> x[0];
+    *item >> x[1];
+    *item >> x[2];
+    first->type = elemente->FindElement(shorthand);
+    for(j=0;j<NDIM;j++)
+      first->x.x[j] = x[j];
+     AddAtom(first);  // add to molecule
+    delete(item);
+  }
+  xyzfile.close();
+  delete(input);
+  return true; 
+};
+
+/** Creates a copy of this molecule.
+ * \return copy of molecule
+ */
+molecule *molecule::CopyMolecule()
+{
+  molecule *copy = new molecule(elemente);
+  atom *CurrentAtom = NULL;
+  atom *LeftAtom = NULL, *RightAtom = NULL;
+  atom *Walker = NULL;
+  
+  // copy all atoms
+  Walker = start;
+  while(Walker->next != end) {
+    Walker = Walker->next;
+    CurrentAtom = copy->AddCopyAtom(Walker);
+  }
+  
+  // copy all bonds
+  bond *Binder = first;
+  bond *NewBond = NULL;
+  while(Binder->next != last) {
+    Binder = Binder->next;
+    // get the pendant atoms of current bond in the copy molecule
+    LeftAtom = copy->start;
+    while (LeftAtom->next != copy->end) {
+      LeftAtom = LeftAtom->next;
+      if (LeftAtom->father == Binder->leftatom)
+        break;
+    }
+    RightAtom = copy->start;
+    while (RightAtom->next != copy->end) {
+      RightAtom = RightAtom->next;
+      if (RightAtom->father == Binder->rightatom)
+        break;
+    }
+    NewBond = copy->AddBond(LeftAtom, RightAtom, Binder->BondDegree);
+    NewBond->Cyclic = Binder->Cyclic;
+    if (Binder->Cyclic)
+      copy->NoCyclicBonds++;
+    NewBond->Type = Binder->Type;
+  }  
+  // correct fathers
+  Walker = copy->start;
+  while(Walker->next != copy->end) {
+    Walker = Walker->next;
+    if (Walker->father->father == Walker->father)   // same atom in copy's father points to itself
+      Walker->father = Walker;  // set father to itself (copy of a whole molecule)
+    else
+     Walker->father = Walker->father->father;  // set father to original's father
+  }
+  // copy values
+  copy->CountAtoms((ofstream *)&cout);
+  copy->CountElements();
+  if (first->next != last) {  // if adjaceny list is present
+    copy->BondDistance = BondDistance;
+    copy->CreateListOfBondsPerAtom((ofstream *)&cout);
+  }
+  
+  return copy;
+};
+
+/** Adds a bond to a the molecule specified by two atoms, \a *first and \a *second.
+ * Also updates molecule::BondCount and molecule::NoNonBonds.
+ * \param *first first atom in bond
+ * \param *second atom in bond
+ * \return pointer to bond or NULL on failure
+ */
+bond * molecule::AddBond(atom *atom1, atom *atom2, int degree=1)
+{
+  bond *Binder = NULL;
+  if ((atom1 != NULL) && (FindAtom(atom1->nr) != NULL) && (atom2 != NULL) && (FindAtom(atom2->nr) != NULL)) {
+    Binder = new bond(atom1, atom2, degree, BondCount++);
+    if ((atom1->type != NULL) && (atom1->type->Z != 1) && (atom2->type != NULL) && (atom2->type->Z != 1))
+      NoNonBonds++;
+    add(Binder, last);
+  } else {
+    cerr << Verbose(1) << "ERROR: Could not add bond between " << atom1->Name << " and " << atom2->Name << " as one or both are not present in the molecule." << endl;
+  }
+  return Binder;
+};
+
+/** Remove bond from bond chain list.
+ * \todo Function not implemented yet 
+ * \param *pointer bond pointer
+ * \return true - bound found and removed, false - bond not found/removed
+ */
+bool molecule::RemoveBond(bond *pointer)
+{
+  //cerr << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
+  removewithoutcheck(pointer);
+  return true;
+};
+
+/** Remove every bond from bond chain list that atom \a *BondPartner is a constituent of.
+ * \todo Function not implemented yet 
+ * \param *BondPartner atom to be removed
+ * \return true - bounds found and removed, false - bonds not found/removed
+ */
+bool molecule::RemoveBonds(atom *BondPartner)
+{
+  cerr << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
+  return false;
+};
+
+/** Sets the molecule::cell_size to the components of \a *dim (rectangular box)
+ * \param *dim vector class
+ */
+void molecule::SetBoxDimension(vector *dim)
+{
+  cell_size[0] = dim->x[0];
+  cell_size[1] = 0.;
+  cell_size[2] = dim->x[1];
+  cell_size[3] = 0.;
+  cell_size[4] = 0.;
+  cell_size[5] = dim->x[2];
+};
+
+/** Centers the edge of the atoms at (0,0,0).
+ * \param *out output stream for debugging
+ * \param *max coordinates of other edge, specifying box dimensions.
+ */
+void molecule::CenterEdge(ofstream *out, vector *max)
+{
+  vector *min = new vector;
+  
+  *out << Verbose(3) << "Begin of CenterEdge." << endl;
+  atom *ptr = start->next;  // start at first in list
+  if (ptr != end) {   //list not empty?
+    for (int i=0;i<NDIM;i++) {
+      max->x[i] = ptr->x.x[i];
+      min->x[i] = ptr->x.x[i];
+    }
+    while (ptr->next != end) {  // continue with second if present
+      ptr = ptr->next;
+      //ptr->Output(1,1,out);
+      for (int i=0;i<NDIM;i++) {
+        max->x[i] = (max->x[i] < ptr->x.x[i]) ? ptr->x.x[i] : max->x[i];
+        min->x[i] = (min->x[i] > ptr->x.x[i]) ? ptr->x.x[i] : min->x[i];
+      }
+    }
+    *out << Verbose(4) << "Maximum is "; 
+    max->Output(out);
+    *out << ", Minimum is ";
+    min->Output(out);
+    *out << endl;
+    
+    for (int i=0;i<NDIM;i++) {
+      min->x[i] *= -1.;
+      max->x[i] += min->x[i];
+    } 
+    Translate(min);
+  } 
+  delete(min);
+  *out << Verbose(3) << "End of CenterEdge." << endl;
+}; 
+
+/** Centers the center of the atoms at (0,0,0).
+ * \param *out output stream for debugging
+ * \param *center return vector for translation vector
+ */
+void molecule::CenterOrigin(ofstream *out, vector *center)
+{
+  int Num = 0;
+  atom *ptr = start->next;  // start at first in list
+ 
+  for(int i=0;i<NDIM;i++) // zero center vector
+    center->x[i] = 0.;
+    
+  if (ptr != end) {   //list not empty?
+    while (ptr->next != end) {  // continue with second if present
+      ptr = ptr->next;
+      Num++;
+      center->AddVector(&ptr->x);       
+    }
+    center->Scale(-1./Num); // divide through total number (and sign for direction)
+    Translate(center);
+  }
+}; 
+
+/** Centers the center of gravity of the atoms at (0,0,0).
+ * \param *out output stream for debugging
+ * \param *center return vector for translation vector
+ */
+void molecule::CenterGravity(ofstream *out, vector *center)
+{
+  double Num = 0;
+  atom *ptr = start->next;  // start at first in list
+  vector tmp;
+  
+  for(int i=0;i<NDIM;i++) // zero center vector
+    center->x[i] = 0.;
+    
+  if (ptr != end) {   //list not empty?
+    while (ptr->next != end) {  // continue with second if present
+      ptr = ptr->next;
+      Num += ptr->type->mass;
+      tmp.CopyVector(&ptr->x);
+      tmp.Scale(ptr->type->mass);  // scale by mass
+      center->AddVector(&tmp);       
+    }
+    center->Scale(-1./Num); // divide through total mass (and sign for direction)
+    Translate(center);
+  }
+}; 
+
+/** Scales all atoms by \a *factor.
+ * \param *factor pointer to scaling factor
+ */
+void molecule::Scale(double **factor)
+{
+  atom *ptr = start;
+
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    ptr->x.Scale(factor);
+  }      
+};
+
+/** Translate all atoms by given vector. 
+ * \param trans[] translation vector.
+ */
+void molecule::Translate(const vector *trans)
+{
+  atom *ptr = start;
+
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    ptr->x.Translate(trans);
+  }      
+};
+
+/** Mirrors all atoms against a given plane. 
+ * \param n[] normal vector of mirror plane.
+ */
+void molecule::Mirror(const vector *n)
+{
+  atom *ptr = start;
+
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    ptr->x.Mirror(n);
+  }      
+};
+
+/** Determines center of gravity (yet not considering atom masses).
+ * \param CenterOfGravity reference to return vector
+ */
+void molecule::DetermineCenterOfGravity(vector &CenterOfGravity)
+{
+  atom *Walker = start;
+  bond *Binder = NULL;
+  double *matrix = ReturnFullMatrixforSymmetric(cell_size);
+  double tmp;
+  bool flag;
+  vector TestVector, TranslationVector;
+  
+  do {
+    CenterOfGravity.Zero();
+    flag = true;
+    while (Walker->next != end) {
+      Walker = Walker->next;
+#ifdef ADDHYDROGEN
+      if (Walker->type->Z != 1) {
+#endif
+        TestVector.CopyVector(&Walker->x);
+        TestVector.InverseMatrixMultiplication(matrix);
+        TranslationVector.Zero();
+        for (int i=0;i<NumberOfBondsPerAtom[Walker->nr]; i++) {
+          Binder = ListOfBondsPerAtom[Walker->nr][i];
+          if (Walker->nr < Binder->GetOtherAtom(Walker)->nr) // otherwise we shift one to, the other fro and gain nothing
+            for (int j=0;j<NDIM;j++) {
+              tmp = Walker->x.x[j] - Binder->GetOtherAtom(Walker)->x.x[j]; 
+              if ((fabs(tmp)) > BondDistance) {
+                flag = false;
+                cout << Verbose(0) << "Hit: atom " << Walker->Name << " in bond " << *Binder << " has to be shifted due to " << tmp << "." << endl;
+                if (tmp > 0)
+                  TranslationVector.x[j] -= 1.;
+                else
+                  TranslationVector.x[j] += 1.;
+              }
+            }
+        }
+        TestVector.AddVector(&TranslationVector);
+        TestVector.MatrixMultiplication(matrix);
+        CenterOfGravity.AddVector(&TestVector);
+        cout << Verbose(1) << "Vector is: ";
+        TestVector.Output((ofstream *)&cout);
+        cout << endl;     
+#ifdef ADDHYDROGEN
+        // now also change all hydrogens
+        for (int i=0;i<NumberOfBondsPerAtom[Walker->nr]; i++) {
+          Binder = ListOfBondsPerAtom[Walker->nr][i];
+          if (Binder->GetOtherAtom(Walker)->type->Z == 1) {
+            TestVector.CopyVector(&Binder->GetOtherAtom(Walker)->x);
+            TestVector.InverseMatrixMultiplication(matrix);
+            TestVector.AddVector(&TranslationVector);
+            TestVector.MatrixMultiplication(matrix);
+            CenterOfGravity.AddVector(&TestVector);
+            cout << Verbose(1) << "Hydrogen Vector is: ";
+            TestVector.Output((ofstream *)&cout);
+            cout << endl;     
+          }
+        }
+      }
+#endif
+    }
+  } while (!flag);
+  Free((void **)&matrix, "molecule::DetermineCenterOfGravity: *matrix");
+  CenterOfGravity.Scale(1./(double)AtomCount);
+};
+
+/** Align all atoms in such a manner that given vector \a *n is along z axis. 
+ * \param n[] alignment vector.
+ */
+void molecule::Align(vector *n)
+{
+  atom *ptr = start;
+  double alpha, tmp;
+  vector z_axis;
+  z_axis.x[0] = 0.;
+  z_axis.x[1] = 0.;
+  z_axis.x[2] = 1.;
+
+  // rotate on z-x plane
+  cout << Verbose(0) << "Begin of Aligning all atoms." << endl;
+  alpha = atan(-n->x[0]/n->x[2]);
+  cout << Verbose(1) << "Z-X-angle: " << alpha << " ... ";
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    tmp = ptr->x.x[0];
+    ptr->x.x[0] =  cos(alpha) * tmp + sin(alpha) * ptr->x.x[2]; 
+    ptr->x.x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->x.x[2];
+  }      
+  // rotate n vector
+  tmp = n->x[0];
+  n->x[0] =  cos(alpha) * tmp +  sin(alpha) * n->x[2];
+  n->x[2] = -sin(alpha) * tmp +  cos(alpha) * n->x[2];
+  cout << Verbose(1) << "alignment vector after first rotation: ";
+  n->Output((ofstream *)&cout);
+  cout << endl;
+  
+  // rotate on z-y plane
+  ptr = start;
+  alpha = atan(-n->x[1]/n->x[2]);
+  cout << Verbose(1) << "Z-Y-angle: " << alpha << " ... ";
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    tmp = ptr->x.x[1];
+    ptr->x.x[1] =  cos(alpha) * tmp + sin(alpha) * ptr->x.x[2]; 
+    ptr->x.x[2] = -sin(alpha) * tmp + cos(alpha) * ptr->x.x[2];
+  }      
+  // rotate n vector (for consistency check)
+  tmp = n->x[1];
+  n->x[1] =  cos(alpha) * tmp +  sin(alpha) * n->x[2];
+  n->x[2] = -sin(alpha) * tmp +  cos(alpha) * n->x[2];
+  
+  cout << Verbose(1) << "alignment vector after second rotation: ";
+  n->Output((ofstream *)&cout);
+  cout << Verbose(1) << endl;
+  cout << Verbose(0) << "End of Aligning all atoms." << endl;
+};
+
+/** Removes atom from molecule list.
+ * \param *pointer atom to be removed
+ * \return true - succeeded, false - atom not found in list
+ */
+bool molecule::RemoveAtom(atom *pointer)  
+{ 
+  if (ElementsInMolecule[pointer->type->Z] != 0)  // this would indicate an error
+    ElementsInMolecule[pointer->type->Z]--;  // decrease number of atom of this element
+  else
+    cerr << "ERROR: 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--;
+  return remove(pointer, start, end);
+};
+
+/** Removes every atom from molecule list.
+ * \return true - succeeded, false - atom not found in list
+ */
+bool molecule::CleanupMolecule() 
+{ 
+  return (cleanup(start,end) && cleanup(first,last)); 
+};
+
+/** Finds an atom specified by its continuous number.
+ * \param Nr number of atom withim molecule
+ * \return pointer to atom or NULL
+ */
+atom * molecule::FindAtom(int Nr)  const{
+  atom * walker = find(&Nr, start,end);
+  if (walker != NULL) {
+    //cout << Verbose(0) << "Found Atom Nr. " << walker->nr << endl;
+    return walker;
+  } else {
+    cout << Verbose(0) << "Atom not found in list." << endl;
+    return NULL;  
+  }
+};
+
+/** Asks for atom number, and checks whether in list.
+ * \param *text question before entering
+ */
+atom * molecule::AskAtom(char *text)
+{
+  int No;
+  atom *ion = NULL;
+  do {
+    //cout << Verbose(0) << "============Atom list==========================" << endl;
+    //mol->Output((ofstream *)&cout);
+    //cout << Verbose(0) << "===============================================" << endl;
+    cout << Verbose(0) << text;
+    cin >> No;
+    ion = this->FindAtom(No);
+  } while (ion == NULL);
+  return ion;
+};
+
+/** Checks if given coordinates are within cell volume.
+ * \param *x array of coordinates
+ * \return true - is within, false - out of cell
+ */
+bool molecule::CheckBounds(const vector *x) const
+{
+  bool result = true;
+  int j =-1;
+  for (int i=0;i<3;i++) {
+    j += i+1;
+    result = result && ((x->x[i] >= 0) && (x->x[i] < cell_size[j]));
+  }
+  //return result;
+  return true; /// probably not gonna use the check no more
+};
+
+/** Calculates sum over least square distance to line hidden in \a *x.
+ * \param *x offset and direction vector
+ * \param *params pointer to lsq_params structure
+ * \return \f$ sum_i^N | y_i - (a + t_i b)|^2\f$
+ */
+double LeastSquareDistance (const gsl_vector * x, void * params)
+{
+  double res = 0, t;
+  vector a,b,c,d;
+  struct lsq_params *par = (struct lsq_params *)params;
+  atom *ptr = par->mol->start;
+  
+  // initialize vectors
+  a.x[0] = gsl_vector_get(x,0);
+  a.x[1] = gsl_vector_get(x,1);
+  a.x[2] = gsl_vector_get(x,2);
+  b.x[0] = gsl_vector_get(x,3);
+  b.x[1] = gsl_vector_get(x,4);
+  b.x[2] = gsl_vector_get(x,5);
+  // go through all atoms
+  while (ptr != par->mol->end) {
+    ptr = ptr->next;
+    if (ptr->type == ((struct lsq_params *)params)->type) { // for specific type
+      c.CopyVector(&ptr->x);  // copy vector to temporary one
+      c.SubtractVector(&a);   // subtract offset vector
+      t = c.ScalarProduct(&b);           // get direction parameter
+      d.CopyVector(&b);       // and create vector
+      d.Scale(&t);
+      c.SubtractVector(&d);   // ... yielding distance vector
+      res += d.ScalarProduct((const vector *)&d);        // add squared distance
+    }
+  }
+  return res;
+};
+
+/** By minimizing the least square distance gains alignment vector.
+ * \bug this is not yet working properly it seems
+ */
+void molecule::GetAlignVector(struct lsq_params * par) const
+{
+    int np = 6;
+    
+   const gsl_multimin_fminimizer_type *T =
+     gsl_multimin_fminimizer_nmsimplex;
+   gsl_multimin_fminimizer *s = NULL;
+   gsl_vector *ss;
+   gsl_multimin_function minex_func;
+ 
+   size_t iter = 0, i;
+   int status;
+   double size;
+ 
+   /* Initial vertex size vector */
+   ss = gsl_vector_alloc (np);
+ 
+   /* Set all step sizes to 1 */
+   gsl_vector_set_all (ss, 1.0);
+ 
+   /* Starting point */
+   par->x = gsl_vector_alloc (np);
+   par->mol = this;
+ 
+   gsl_vector_set (par->x, 0, 0.0);  // offset
+   gsl_vector_set (par->x, 1, 0.0);
+   gsl_vector_set (par->x, 2, 0.0);
+   gsl_vector_set (par->x, 3, 0.0);  // direction
+   gsl_vector_set (par->x, 4, 0.0);
+   gsl_vector_set (par->x, 5, 1.0);
+ 
+   /* Initialize method and iterate */
+   minex_func.f = &LeastSquareDistance;
+   minex_func.n = np;
+   minex_func.params = (void *)par;
+ 
+   s = gsl_multimin_fminimizer_alloc (T, np);
+   gsl_multimin_fminimizer_set (s, &minex_func, par->x, ss);
+ 
+   do
+     {
+       iter++;
+       status = gsl_multimin_fminimizer_iterate(s);
+ 
+       if (status)
+         break;
+ 
+       size = gsl_multimin_fminimizer_size (s);
+       status = gsl_multimin_test_size (size, 1e-2);
+ 
+       if (status == GSL_SUCCESS)
+         {
+           printf ("converged to minimum at\n");
+         }
+ 
+       printf ("%5d ", (int)iter);
+       for (i = 0; i < (size_t)np; i++)
+         {
+           printf ("%10.3e ", gsl_vector_get (s->x, i));
+         }
+       printf ("f() = %7.3f size = %.3f\n", s->fval, size);
+     }
+   while (status == GSL_CONTINUE && iter < 100);
+ 
+  for (i=0;i<(size_t)np;i++)
+    gsl_vector_set(par->x, i, gsl_vector_get(s->x, i));
+   //gsl_vector_free(par->x);
+   gsl_vector_free(ss);
+   gsl_multimin_fminimizer_free (s);
+};
+
+/** Prints molecule to *out.
+ * \param *out output stream
+ */
+bool molecule::Output(ofstream *out)
+{
+  element *runner = elemente->start;
+  atom *walker = NULL;
+  int ElementNo, AtomNo;
+  CountElements();
+  
+  if (out == NULL) {
+    return false;
+  } else {
+    *out << "#Ion_TypeNr._Nr.R[0]    R[1]    R[2]    MoveType (0 MoveIon, 1 FixedIon)" << endl;
+    ElementNo = 0;
+    while (runner->next != elemente->end) { // go through every element
+  		runner = runner->next;
+      if (ElementsInMolecule[runner->Z]) { // if this element got atoms
+        ElementNo++;
+        AtomNo = 0;
+        walker = start;
+        while (walker->next != end) { // go through every atom of this element
+          walker = walker->next;
+          if (walker->type == runner) { // if this atom fits to element
+            AtomNo++;
+            walker->Output(ElementNo, AtomNo, out);
+          }
+        }
+      }
+    }
+    return true;
+  }
+};
+
+/** Output of element before the actual coordination list.
+ * \param *out stream pointer
+ */
+bool molecule::Checkout(ofstream *out)  const
+{
+	return elemente->Checkout(out, ElementsInMolecule);
+};
+
+/** Prints molecule to *out as xyz file.
+ * \param *out output stream
+ */
+bool molecule::OutputXYZ(ofstream *out) const
+{
+  atom *walker = NULL;
+  int No = 0;
+  time_t now;
+  
+  now = time((time_t *)NULL);   // Get the system time and put it into 'now' as 'calender time'
+  walker = start;
+  while (walker->next != end) { // go through every atom and count
+    walker = walker->next;
+    No++;
+  }
+  if (out != NULL) {
+    *out << No << "\n\tCreated by molecuilder on " << ctime(&now);
+    walker = start;
+    while (walker->next != end) { // go through every atom of this element
+      walker = walker->next;
+      walker->OutputXYZLine(out);
+    }
+    return true;
+  } else
+    return false;
+};
+
+/** Brings molecule::AtomCount and atom::*Name up-to-date.
+ * \param *out output stream for debugging
+ */
+void molecule::CountAtoms(ofstream *out)
+{
+	int i = 0;
+	atom *Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    i++;
+  }
+  if ((AtomCount == 0) || (i != AtomCount)) {
+    *out << Verbose(3) << "Mismatch in AtomCount " << AtomCount << " and recounted number " << i << ", renaming all." << endl;
+  	AtomCount = i;
+
+    // count NonHydrogen atoms and give each atom a unique name
+    if (AtomCount != 0) {
+	    i=0;
+	    NoNonHydrogen = 0;
+      Walker = start;
+	    while (Walker->next != end) {
+	      Walker = Walker->next;
+	      Walker->nr = i;   // update number in molecule (for easier referencing in FragmentMolecule lateron)
+	      if (Walker->type->Z != 1) // count non-hydrogen atoms whilst at it
+	        NoNonHydrogen++; 
+	      Free((void **)&Walker->Name, "molecule::CountAtoms: *walker->Name");
+	      Walker->Name = (char *) Malloc(sizeof(char)*6, "molecule::CountAtoms: *walker->Name");
+	      sprintf(Walker->Name, "%2s%02d", Walker->type->symbol, Walker->nr+1);
+        *out << "Naming atom nr. " << Walker->nr << " " << Walker->Name << "." << endl;
+	      i++;
+	    }
+    } else
+    	*out << Verbose(3) << "AtomCount is still " << AtomCount << ", thus counting nothing." << endl; 
+  }
+};
+
+/** Brings molecule::ElementCount and molecule::ElementsInMolecule up-to-date.
+ */
+void molecule::CountElements()
+{
+	int i = 0;
+  for(i=0;i<MAX_ELEMENTS;i++)
+  	ElementsInMolecule[i] = 0;
+	ElementCount = 0;
+	
+  atom *walker = start;
+  while (walker->next != end) {
+    walker = walker->next;
+    ElementsInMolecule[walker->type->Z]++;
+    i++;
+  }
+  for(i=0;i<MAX_ELEMENTS;i++)
+  	ElementCount += (ElementsInMolecule[i] != 0 ? 1 : 0);
+};
+
+/** Counts all cyclic bonds and returns their number.
+ * \note Hydrogen bonds can never by cyclic, thus no check for that
+ * \param *out output stream for debugging
+ * \return number opf cyclic bonds
+ */
+int molecule::CountCyclicBonds(ofstream *out)
+{
+  int No = 0;
+  int MinimumRingSize;
+  MoleculeLeafClass *Subgraphs = NULL;
+  bond *Binder = first;
+  if ((Binder->next != last) && (Binder->next->Type == Undetermined)) {
+    *out << Verbose(0) << "No Depth-First-Search analysis performed so far, calling ..." << endl;
+    Subgraphs = DepthFirstSearchAnalysis(out, false, MinimumRingSize);
+    while (Subgraphs->next != NULL) {
+      Subgraphs = Subgraphs->next;
+      delete(Subgraphs->previous);
+    }
+    delete(Subgraphs);
+  }
+  while(Binder->next != last) {
+    Binder = Binder->next;
+    if (Binder->Cyclic)
+      No++;    
+  }
+  return No;
+};
+
+/** Returns Shading as a char string.
+ * \param color the Shading
+ * \return string of the flag
+ */
+char * molecule::GetColor(enum Shading color)
+{
+  switch(color) {
+    case white:
+      return "white";
+      break;
+    case lightgray:
+      return "lightgray";
+      break;
+    case darkgray:
+      return "darkgray";
+      break;
+    case black:
+      return "black";
+      break;
+    default:
+      return "uncolored";
+      break;
+  };
+};
+
+
+/** Counts necessary number of valence electrons and returns number and SpinType.
+ * \param configuration containing everything
+ */
+void molecule::CalculateOrbitals(class config &configuration)
+{
+  configuration.MaxPsiDouble = configuration.PsiMaxNoDown = configuration.PsiMaxNoUp = configuration.PsiType = 0;
+  for(int i=0;i<MAX_ELEMENTS;i++) {
+    if (ElementsInMolecule[i] != 0) {
+      //cout << "CalculateOrbitals: " << elemente->FindElement(i)->name << " has a valence of " << (int)elemente->FindElement(i)->Valence << " and there are " << ElementsInMolecule[i] << " of it." << endl;
+      configuration.MaxPsiDouble += ElementsInMolecule[i]*((int)elemente->FindElement(i)->Valence);
+    }
+  }
+  configuration.PsiMaxNoDown = configuration.MaxPsiDouble/2 + (configuration.MaxPsiDouble % 2);
+  configuration.PsiMaxNoUp = configuration.MaxPsiDouble/2;
+  configuration.MaxPsiDouble /= 2;
+  configuration.PsiType = (configuration.PsiMaxNoDown == configuration.PsiMaxNoUp) ? 0 : 1;
+  if ((configuration.PsiType == 1) && (configuration.ProcPEPsi < 2)) {
+    configuration.ProcPEGamma /= 2;
+    configuration.ProcPEPsi *= 2;
+  } else {
+    configuration.ProcPEGamma *= configuration.ProcPEPsi;
+    configuration.ProcPEPsi = 1;
+  }
+  configuration.InitMaxMinStopStep = configuration.MaxMinStopStep = configuration.MaxPsiDouble;
+};
+
+/** Creates an adjacency list of the molecule.
+ * Generally, we use the CSD approach to bond recognition, that is the the distance
+ * between two atoms A and B must be within [Rcov(A)+Rcov(B)-t,Rcov(A)+Rcov(B)+t] with
+ * a threshold t = 0.4 Angstroem. 
+ * To make it O(N log N) the function uses the linked-cell technique as follows:
+ * The procedure is step-wise:
+ *  -# Remove every bond in list
+ *  -# Count the atoms in the molecule with CountAtoms()
+ *  -# partition cell into smaller linked cells of size \a bonddistance
+ *  -# put each atom into its corresponding cell
+ *  -# go through every cell, check the atoms therein against all possible bond partners in the 27 adjacent cells, add bond if true
+ *  -# create the list of bonds via CreateListOfBondsPerAtom()
+ *  -# correct the bond degree iteratively (single->double->triple bond)
+ *  -# finally print the bond list to \a *out if desired
+ * \param *out out stream for printing the matrix, NULL if no output
+ * \param bonddistance length of linked cells (i.e. maximum minimal length checked)
+ */
+void molecule::CreateAdjacencyList(ofstream *out, double bonddistance)
+{
+  atom *Walker = NULL, *OtherWalker = NULL;
+  int No, NoBonds;
+  bond *Binder = NULL;
+  int NumberCells, divisor[NDIM], n[NDIM], N[NDIM], index, Index, j;
+  molecule **CellList;
+  double distance, MinDistance, MaxDistance;
+  double *matrix = ReturnFullMatrixforSymmetric(cell_size);
+  vector x;
+ 
+  BondDistance = bonddistance;
+  *out << Verbose(0) << "Begin of CreateAdjacencyList." << endl;
+  // remove every bond from the list
+  if ((first->next != last) && (last->previous != first)) {  // there are bonds present
+    cleanup(first,last);
+  }
+	
+  // count atoms in molecule = dimension of matrix (also give each unique name and continuous numbering)
+  CountAtoms(out);
+  *out << Verbose(1) << "AtomCount " << AtomCount << "." << endl;
+
+  if (AtomCount != 0) {
+    // 1. find divisor for each axis, such that a sphere with radius of at least bonddistance can be placed into each cell
+    j=-1;
+    for (int i=0;i<NDIM;i++) {
+      j += i+1;
+      divisor[i] = (int)floor(cell_size[j]/bonddistance); // take smaller value such that size of linked cell is at least bonddistance
+      *out << Verbose(1) << "divisor[" << i << "]  = " << divisor[i] << "." << endl;
+    }
+    // 2a. allocate memory for the cell list
+    NumberCells = divisor[0]*divisor[1]*divisor[2];
+    *out << Verbose(1) << "Allocating " << NumberCells << " cells." << endl;
+    CellList = (molecule **) Malloc(sizeof(molecule *)*NumberCells, "molecule::CreateAdjacencyList - ** CellList");
+    for (int i=0;i<NumberCells;i++)
+      CellList[i] = NULL;
+  
+    // 2b. put all atoms into its corresponding list
+    Walker = start;
+    while(Walker->next != end) {
+      Walker = Walker->next;
+      //*out << Verbose(1) << "Current atom is " << *Walker << " with coordinates ";
+      //Walker->x.Output(out);
+      //*out << "." << endl;
+      // compute the cell by the atom's coordinates
+      j=-1;
+      for (int i=0;i<NDIM;i++) {
+        j += i+1;
+        x.CopyVector(&(Walker->x));
+        x.KeepPeriodic(out, matrix);
+        n[i] = (int)floor(x.x[i]/cell_size[j]*(double)divisor[i]);
+      }
+      index = n[2] + (n[1] + n[0] * divisor[1]) * divisor[2];
+      *out << Verbose(1) << "Atom " << *Walker << " goes into cell number [" << n[0] << "," << n[1] << "," << n[2] << "] = " << index << "." << endl;
+      // add copy atom to this cell
+      if (CellList[index] == NULL)  // allocate molecule if not done
+        CellList[index] = new molecule(elemente);
+      OtherWalker = CellList[index]->AddCopyAtom(Walker); // add a copy of walker to this atom, father will be walker for later reference 
+      //*out << Verbose(1) << "Copy Atom is " << *OtherWalker << "." << endl; 
+    }
+    //for (int i=0;i<NumberCells;i++)
+      //*out << Verbose(1) << "Cell number " << i << ": " << CellList[i] << "." << endl;
+      
+    // 3a. go through every cell
+    for (N[0]=0;N[0]<divisor[0];N[0]++)
+      for (N[1]=0;N[1]<divisor[1];N[1]++)
+        for (N[2]=0;N[2]<divisor[2];N[2]++) {
+          Index = N[2] + (N[1] + N[0] * divisor[1]) * divisor[2];
+          if (CellList[Index] != NULL) { // if there atoms in this cell
+            //*out << Verbose(1) << "Current cell is " << Index << "." << endl;
+            // 3b. for every atom therein
+            Walker = CellList[Index]->start;
+            while (Walker->next != CellList[Index]->end) {  // go through every atom
+              Walker = Walker->next;
+              //*out << 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]++) {
+                     // compute the index of this comparison cell and make it periodic
+                    index = ((N[2]+n[2]+divisor[2])%divisor[2]) + (((N[1]+n[1]+divisor[1])%divisor[1]) + ((N[0]+n[0]+divisor[0])%divisor[0]) * divisor[1]) * divisor[2];
+                    //*out << Verbose(1) << "Number of comparison cell is " << index << "." << endl;
+                    if (CellList[index] != NULL) {  // if there are any atoms in this cell
+                      OtherWalker = CellList[index]->start;
+                      while(OtherWalker->next != CellList[index]->end) {  // go through every atom in this cell
+                        OtherWalker = OtherWalker->next;
+                        //*out << Verbose(0) << "Current comparison atom is " << *OtherWalker << "." << endl;
+                        /// \todo periodic check is missing here!
+                        //*out << Verbose(1) << "Checking distance " << OtherWalker->x.PeriodicDistance(&(Walker->x), cell_size) << " against typical bond length of " << bonddistance*bonddistance << "." << endl;
+                        MinDistance = OtherWalker->type->CovalentRadius + Walker->type->CovalentRadius;  
+                        MaxDistance = MinDistance + BONDTHRESHOLD;
+                        MinDistance -= BONDTHRESHOLD;
+                        distance =   OtherWalker->x.PeriodicDistance(&(Walker->x), cell_size);
+                        if ((OtherWalker->father->nr > Walker->father->nr) && (distance <= MaxDistance*MaxDistance) && (distance >= MinDistance*MinDistance)) { // create bond if distance is smaller
+                          *out << Verbose(0) << "Adding Bond between " << *Walker << " and " << *OtherWalker << "." << endl;
+                          AddBond(Walker->father, OtherWalker->father, 1);  // also increases molecule::BondCount
+                        } else {
+                          //*out << Verbose(1) << "Not Adding: Wrong label order or distance too great." << endl;
+                        }
+                      }
+                    }
+                  }
+            }
+          }
+        }
+    // 4. free the cell again
+    for (int i=0;i<NumberCells;i++)
+      if (CellList[i] != NULL) {
+        delete(CellList[i]);
+      }
+    Free((void **)&CellList, "molecule::CreateAdjacencyList - ** CellList"); 
+  
+    // create the adjacency list per atom
+    CreateListOfBondsPerAtom(out);
+  		
+    // correct Bond degree of each bond by checking of updated(!) sum of bond degree for an atom match its valence count
+    // bond degrres are correctled iteratively by one, so that 2-2 instead of 1-3 or 3-1 corrections are favoured: We want
+    // a rather symmetric distribution of higher bond degrees
+		if (BondCount != 0) {
+      NoCyclicBonds = 0;
+		  *out << Verbose(1) << "correct Bond degree of each bond" << endl;
+		  do {
+		    No = 0; // No acts as breakup flag (if 1 we still continue)
+        Walker = start;
+        while (Walker->next != end) { // go through every atom
+          Walker = Walker->next;
+          for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) { // go through each of its bond partners
+            OtherWalker = ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker);
+	          // count valence of first partner (updated!), might have changed during last bond partner
+	          NoBonds = 0;
+            for(j=0;j<NumberOfBondsPerAtom[Walker->nr];j++)
+              NoBonds += ListOfBondsPerAtom[Walker->nr][j]->BondDegree;
+	          *out << Verbose(3) << "Walker: " << (int)Walker->type->NoValenceOrbitals << " > " << NoBonds << "?" << endl;
+	          if ((int)(Walker->type->NoValenceOrbitals) > NoBonds) { // we have a mismatch, check NoBonds of other atom
+	            // count valence of second partner
+              NoBonds = 0;
+              for(j=0;j<NumberOfBondsPerAtom[OtherWalker->nr];j++)
+                NoBonds += ListOfBondsPerAtom[OtherWalker->nr][j]->BondDegree;
+              *out << Verbose(3) << "OtherWalker: " << (int)OtherWalker->type->NoValenceOrbitals << " > " << NoBonds << "?" << endl;
+	            if ((int)(OtherWalker->type->NoValenceOrbitals) > NoBonds) // increase bond degree by one
+                ListOfBondsPerAtom[Walker->nr][i]->BondDegree++;
+	          }
+          }
+		    }
+		  } while (No);
+		
+		} else
+			*out << Verbose(1) << "BondCount is " << BondCount << ", no bonds between any of the " << AtomCount << " atoms." << endl;
+	  *out << Verbose(1) << "I detected " << BondCount << " bonds in the molecule with distance " << bonddistance << "." << endl;
+		
+	  // output bonds for debugging (if bond chain list was correctly installed)
+	  *out << Verbose(1) << endl << "From contents of bond chain list:";
+    Binder = first;
+    while(Binder->next != last) {
+      Binder = Binder->next;
+			*out << *Binder << "\t" << endl;
+    }
+    *out << endl;
+  } else
+  	*out << Verbose(1) << "AtomCount is " << AtomCount << ", thus no bonds, no connections!." << endl; 
+  *out << Verbose(0) << "End of CreateAdjacencyList." << endl;
+  Free((void **)&matrix, "molecule::CreateAdjacencyList: *matrix");
+};
+
+/** Performs a Depth-First search on this molecule.
+ * Marks bonds in molecule as cyclic, bridge, ... and atoms as
+ * articulations points, ...
+ * We use the algorithm from [Even, Graph Algorithms, p.62].
+ * \param *out output stream for debugging
+ * \param ReturnStack true - return pointer to atom stack of separable components, false - return NULL
+ * \param MinimumRingSize contains smallest ring size in molecular structure on return or -1 if no rings were found
+ * \return list of each disconnected subgraph as an individual molecule class structure
+ */
+MoleculeLeafClass * molecule::DepthFirstSearchAnalysis(ofstream *out, bool ReturnStack, int &MinimumRingSize)
+{
+  AtomStackClass *AtomStack = new AtomStackClass(AtomCount);
+  MoleculeLeafClass *SubGraphs = new MoleculeLeafClass(NULL);
+  MoleculeLeafClass *LeafWalker = SubGraphs;
+  int CurrentGraphNr = 0, OldGraphNr;
+  int CyclicBonds;
+  int ComponentNumber = 0;
+  atom *Walker = NULL, *OtherAtom = NULL, *Root = start->next;
+  bond *Binder = NULL;
+  bool BackStepping = false;
+  
+  *out << Verbose(0) << "Begin of DepthFirstSearchAnalysis" << endl;
+  
+  ResetAllBondsToUnused();
+  ResetAllAtomNumbers();
+  InitComponentNumbers();
+  while (Root != end) { // if there any atoms at all
+    // (1) mark all edges unused, empty stack, set atom->GraphNr = 0 for all
+    AtomStack->ClearStack();
+
+    // put into new subgraph molecule and add this to list of subgraphs
+    LeafWalker = new MoleculeLeafClass(LeafWalker);
+    LeafWalker->Leaf = new molecule(elemente);
+    LeafWalker->Leaf->AddCopyAtom(Root);
+    
+    OldGraphNr = CurrentGraphNr;
+    Walker = Root;
+    do { // (10)
+      do { // (2) set number and Lowpoint of Atom to i, increase i, push current atom
+        if (!BackStepping) { // if we don't just return from (8)
+          Walker->GraphNr = CurrentGraphNr;
+          Walker->LowpointNr = CurrentGraphNr;
+          *out << Verbose(1) << "Setting Walker[" << Walker->Name << "]'s number to " << Walker->GraphNr << " with Lowpoint " << Walker->LowpointNr << "." << endl;
+          AtomStack->Push(Walker);
+          CurrentGraphNr++;
+        }      
+        do { // (3) if Walker has no unused egdes, go to (5)
+          BackStepping = false; // reset backstepping flag for (8)
+          if (Binder == NULL) // if we don't just return from (11), Binder is already set to next unused
+            Binder = FindNextUnused(Walker);
+          if (Binder == NULL)
+            break;
+          *out << Verbose(2) << "Current Unused Bond is " << *Binder << "." << endl;
+          // (4) Mark Binder used, ...
+          Binder->MarkUsed(black);
+          OtherAtom = Binder->GetOtherAtom(Walker);
+          *out << 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)
+            Binder->Type = BackEdge;
+            Walker->LowpointNr = ( Walker->LowpointNr < OtherAtom->GraphNr ) ? Walker->LowpointNr : OtherAtom->GraphNr;
+            *out << 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)
+            Binder->Type = TreeEdge;
+            OtherAtom->Ancestor = Walker;
+            Walker = OtherAtom;
+            *out << Verbose(3) << "(4b) Not Visited: OtherAtom[" << OtherAtom->Name << "]'s Ancestor is now " << OtherAtom->Ancestor->Name << ", Walker is OtherAtom " << OtherAtom->Name << "." << endl;
+            break;
+          }
+          Binder = NULL;
+        } while (1);  // (3)
+        if (Binder == NULL) {
+          *out << Verbose(2) << "No more Unused Bonds." << endl;
+          break;
+        } else
+          Binder = NULL;
+      } while (1);  // (2)
+      
+      // if we came from backstepping, yet there were no more unused bonds, we end up here with no Ancestor, because Walker is Root! Then we are finished!
+      if ((Walker == Root) && (Binder == NULL))
+        break;
+        
+      // (5) if Ancestor of Walker is ... 
+      *out << Verbose(1) << "(5) Number of Walker[" << Walker->Name << "]'s Ancestor[" << Walker->Ancestor->Name << "] is " << Walker->Ancestor->GraphNr << "." << endl;
+      if (Walker->Ancestor->GraphNr != Root->GraphNr) {
+        // (6)  (Ancestor of Walker is not Root)
+        if (Walker->LowpointNr < Walker->Ancestor->GraphNr) {
+          // (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;
+          *out << 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;
+          *out << Verbose(2) << "(7) Walker[" << Walker->Name << "]'s Ancestor[" << Walker->Ancestor->Name << "]'s is a separating vertex, creating component." << endl;
+          SetNextComponentNumber(Walker->Ancestor, ComponentNumber);
+          *out << Verbose(3) << "(7) Walker[" << Walker->Name << "]'s Ancestor's Compont is " << ComponentNumber << "." << endl;
+          SetNextComponentNumber(Walker, ComponentNumber);
+          *out << Verbose(3) << "(7) Walker[" << Walker->Name << "]'s Compont is " << ComponentNumber << "." << endl;
+          do {
+            OtherAtom = AtomStack->PopLast();
+            LeafWalker->Leaf->AddCopyAtom(OtherAtom);
+            SetNextComponentNumber(OtherAtom, ComponentNumber);
+            *out << Verbose(3) << "(7) Other[" << OtherAtom->Name << "]'s Compont is " << ComponentNumber << "." << endl;
+          } while (OtherAtom != Walker);
+          ComponentNumber++;
+        }
+        // (8) Walker becomes its Ancestor, go to (3)
+        *out << Verbose(2) << "(8) Walker[" << Walker->Name << "] is now its Ancestor " << Walker->Ancestor->Name << ", backstepping. " << endl;
+        Walker = Walker->Ancestor;
+        BackStepping = true;
+      }
+      if (!BackStepping) {  // coming from (8) want to go to (3)
+        // (9) remove all from stack till Walker (including), these and Root form a component
+        AtomStack->Output(out);
+        SetNextComponentNumber(Root, ComponentNumber);
+        *out << Verbose(3) << "(9) Root[" << Root->Name << "]'s Component is " << ComponentNumber << "." << endl;
+        SetNextComponentNumber(Walker, ComponentNumber);
+        *out << Verbose(3) << "(9) Walker[" << Walker->Name << "]'s Component is " << ComponentNumber << "." << endl;
+        do {
+          OtherAtom = AtomStack->PopLast();
+          LeafWalker->Leaf->AddCopyAtom(OtherAtom);
+          SetNextComponentNumber(OtherAtom, ComponentNumber);
+          *out << Verbose(3) << "(7) Other[" << OtherAtom->Name << "]'s Compont is " << ComponentNumber << "." << endl;
+        } while (OtherAtom != Walker);
+        ComponentNumber++;
+    
+        // (11) Root is separation vertex,  set Walker to Root and go to (4)
+        Walker = Root;
+        Binder = FindNextUnused(Walker);
+        *out << Verbose(1) << "(10) Walker is Root[" << Root->Name << "], next Unused Bond is " << Binder << "." << endl;
+        if (Binder != NULL) { // Root is separation vertex
+          *out << Verbose(1) << "(11) Root is a separation vertex." << endl;
+          Walker->SeparationVertex = true;
+        }
+      }
+    } while ((BackStepping) || (Binder != NULL)); // (10) halt only if Root has no unused edges
+
+    // From OldGraphNr to CurrentGraphNr ranges an disconnected subgraph
+    *out << Verbose(0) << "Disconnected subgraph ranges from " << OldGraphNr << " to " << CurrentGraphNr << "." << endl;    
+    LeafWalker->Leaf->Output(out);
+    *out << endl;
+    
+    // step on to next root
+    while ((Root != end) && (Root->GraphNr != -1)) {
+      //*out << Verbose(1) << "Current next subgraph root candidate is " << Root->Name << "." << endl;
+      if (Root->GraphNr != -1) // if already discovered, step on
+        Root = Root->next; 
+    }
+  }
+  // set cyclic bond criterium on "same LP" basis
+  Binder = first;
+  while(Binder->next != last) {
+    Binder = Binder->next;
+    if (Binder->rightatom->LowpointNr == Binder->leftatom->LowpointNr) { // cyclic ??
+      Binder->Cyclic = true;
+      NoCyclicBonds++;
+    }
+  }
+
+  // correct cyclic bonds that are not included in "same LP" argument
+  Binder = first;
+  while (Binder->next != last) {
+    Binder = Binder->next;
+    Walker = Binder->leftatom;
+    OtherAtom = Binder->rightatom;
+    // now check whether both have a cyclic bond in their list
+    CyclicBonds = 0;   // counts cyclic bonds;
+    for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++)
+      if ((CyclicBonds == 0) && (ListOfBondsPerAtom[Walker->nr][i]->Cyclic))
+        CyclicBonds = 1;  
+    for(int i=0;i<NumberOfBondsPerAtom[OtherAtom->nr];i++)
+      if ((CyclicBonds == 1) && (ListOfBondsPerAtom[OtherAtom->nr][i]->Cyclic))
+        CyclicBonds = 2;  
+    Binder->Cyclic = (Binder->Cyclic) || (CyclicBonds == 2); // set the Cyclic criterium either or ... 
+  }
+  
+  // further analysis of the found cycles (print rings, get minimum cycle length)
+  CyclicStructureAnalysis(out, MinimumRingSize);
+  *out << Verbose(1) << "Final graph info for each atom is:" << endl;
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    *out << Verbose(2) << "Atom " << Walker->Name << " is " << ((Walker->SeparationVertex) ? "a" : "not a") << " separation vertex, components are ";
+    OutputComponentNumber(out, Walker);
+    *out << " with Lowpoint " << Walker->LowpointNr << " and Graph Nr. " << Walker->GraphNr << "." << endl;
+  }
+  
+  *out << Verbose(1) << "Final graph info for each bond is:" << endl;
+  Binder = first;
+  while(Binder->next != last) {
+    Binder = Binder->next;
+    *out << Verbose(2) << ((Binder->Type == TreeEdge) ? "TreeEdge " : "BackEdge ") << *Binder << ": <";
+    *out << ((Binder->leftatom->SeparationVertex) ? "SP," : "") << "L" << Binder->leftatom->LowpointNr << " G" << Binder->leftatom->GraphNr << " Comp.";
+    OutputComponentNumber(out, Binder->leftatom);
+    *out << " ===  ";
+    *out << ((Binder->rightatom->SeparationVertex) ? "SP," : "") << "L" << Binder->rightatom->LowpointNr << " G" << Binder->rightatom->GraphNr << " Comp.";
+    OutputComponentNumber(out, Binder->rightatom);
+    *out << ">." << endl; 
+    if (Binder->Cyclic) // cyclic ??
+      *out << Verbose(3) << "Lowpoint at each side are equal: CYCLIC!" << endl;
+  }
+
+  // further analysis of the found cycles (print rings, get minimum cycle length)
+  CyclicStructureAnalysis(out, MinimumRingSize);
+  
+  // free all and exit
+  delete(AtomStack);
+  *out << Verbose(0) << "End of DepthFirstSearchAnalysis" << endl;
+  return SubGraphs;
+};
+
+/** Analyses the cycles found and returns minimum of all cycle lengths.
+ * \param *out output stream for debugging
+ * \param MinimumRingSize contains smallest ring size in molecular structure on return or -1 if no rings were found
+ * \todo BFS from the not-same-LP to find back to starting point of tributary cycle over more than one bond
+ */
+void molecule::CyclicStructureAnalysis(ofstream *out, int &MinimumRingSize)
+{
+  AtomStackClass *AtomStack = new AtomStackClass(AtomCount);
+  int LP;
+  atom *Walker = NULL, *OtherAtom = NULL, *Root = NULL, *Runner = NULL;
+  bond *Binder = NULL;
+  int RingSize, NumCycles;
+
+  // go through every atom
+  AtomStack->ClearStack();
+  int *NoCyclicBondsPerAtom = (int *) Malloc(sizeof(int)*AtomCount, "molecule::CyclicStructureAnalysis: *NoCyclicBondsPerAtom");
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    NoCyclicBondsPerAtom[Walker->nr] = 0;
+    // check whether it's connected to cyclic bonds and count per atom
+    // 0 means not part of a cycle, 2 means in a cycle, 3 or more means interconnection site of cycles
+    for (int i=0;i<NumberOfBondsPerAtom[Walker->nr]; i++) {
+      Binder = ListOfBondsPerAtom[Walker->nr][i];
+      NoCyclicBondsPerAtom[Walker->nr] += (int) Binder->Cyclic;
+      if (NoCyclicBondsPerAtom[Walker->nr] == 3)  //push all intersections
+        AtomStack->Push(Walker);
+    }
+  }
+  *out << Verbose(1) << "NoCyclicBondsPerAtom: ";
+  for(int i=0;i<AtomCount;i++) {
+    *out << NoCyclicBondsPerAtom[i] << " ";
+  }
+  *out << endl;
+  *out << Verbose(1) << "Analysing cycles ... " << endl;
+  MinimumRingSize = -1;
+  NumCycles = 0;
+  while (!AtomStack->IsEmpty()) {
+    Walker = AtomStack->PopFirst();
+    if (NoCyclicBondsPerAtom[Walker->nr] > 1) {
+      NoCyclicBondsPerAtom[Walker->nr]--; // remove one for being intersection
+      RingSize = 0;
+      *out << Verbose(2) << "Current intersection is " << *Walker << ", expect to find " << NoCyclicBondsPerAtom[Walker->nr] << " cycles." << endl;
+      for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {
+        Binder = ListOfBondsPerAtom[Walker->nr][i];
+        OtherAtom = Binder->GetOtherAtom(Walker);
+        // note down the LowPoint number of this cycle
+        if (NoCyclicBondsPerAtom[OtherAtom->nr] > 1) {
+          LP = OtherAtom->LowpointNr;
+          NoCyclicBondsPerAtom[Walker->nr]--; // walker is start of cycle
+          if (LP != Walker->LowpointNr)
+            *out << Verbose(2) << "Tributary cycle: ... <-> " << Walker->Name;
+          else 
+            *out << Verbose(2) << "Main cycle: ... <-> " << Walker->Name;
+          Root = Walker;  // root acts as predecessor marker so that we don't step back accidentally
+          RingSize = 1;
+          do {
+            for(int j=0;j<NumberOfBondsPerAtom[OtherAtom->nr];j++) {  // search among its bonds for next in cycle (same lowpoint nr)
+              Runner = ListOfBondsPerAtom[OtherAtom->nr][j]->GetOtherAtom(OtherAtom);
+              if (((Runner->LowpointNr == LP) || (Runner->LowpointNr == Walker->LowpointNr)) && (Runner != Root)) {
+                // first check is to stay in the cycle
+                // middle check is allow for getting back into main cycle briefly from tributary cycle (just one step, then while further down stops)
+                // last check is not step back
+                *out << " <-> " << OtherAtom->Name;
+                NoCyclicBondsPerAtom[OtherAtom->nr]--;
+                Root = OtherAtom;
+                OtherAtom = Runner;
+                NoCyclicBondsPerAtom[Root->nr]--;
+                RingSize++;
+                break;
+              }
+            }
+          } while ((OtherAtom->LowpointNr == LP) && (Walker != OtherAtom) && (Root->LowpointNr == OtherAtom->LowpointNr));
+          // now check if the LP is different from Walker's, as then there is one more bond to follow
+          if (LP != Walker->LowpointNr) {
+            // find last bond to home base
+            for(int j=0;j<NumberOfBondsPerAtom[OtherAtom->nr];j++)
+              if (ListOfBondsPerAtom[OtherAtom->nr][j]->GetOtherAtom(OtherAtom) == Root) {
+                *out << " <-> " << OtherAtom->Name;
+                RingSize++;
+                NoCyclicBondsPerAtom[OtherAtom->nr]--;
+              }
+          } else {
+            // we have made the complete cycle
+          }
+          *out << " <-> ... with cycle length of " << RingSize << "." << endl;
+          NumCycles++;
+          if ((RingSize < MinimumRingSize) || (MinimumRingSize == -1))
+            MinimumRingSize = RingSize;
+        }
+      }
+    }
+  }
+
+  // print NoCyclicBondsPerAtom to visually check of all are zero
+  *out << Verbose(1) << "NoCyclicBondsPerAtom: ";
+  for(int i=0;i<AtomCount;i++) {
+    if (NoCyclicBondsPerAtom[i] > 0)
+      cerr << "There was an error in  molecule::CyclicStructureAnalysis!" << endl;
+    *out << NoCyclicBondsPerAtom[i] << " ";
+  }
+  *out << endl;
+
+  if (MinimumRingSize != -1)
+    *out << Verbose(1) << "Minimum ring size is " << MinimumRingSize << ", over " << NumCycles << " cycles total." << endl;
+  else
+    *out << Verbose(1) << "No rings were detected in the molecular structure." << endl;
+
+  Free((void **)&NoCyclicBondsPerAtom, "molecule::CyclicStructureAnalysis: *NoCyclicBondsPerAtom");
+  delete(AtomStack);
+};
+
+/** Sets the next component number.
+ * This is O(N) as the number of bonds per atom is bound.
+ * \param *vertex atom whose next atom::*ComponentNr is to be set
+ * \param nr number to use
+ */
+void molecule::SetNextComponentNumber(atom *vertex, int nr)
+{
+  int i=0;
+  if (vertex != NULL) {
+    for(;i<NumberOfBondsPerAtom[vertex->nr];i++) {
+      if (vertex->ComponentNr[i] == -1) {   // check if not yet used
+        vertex->ComponentNr[i] = nr;
+        break;
+      }
+      else if (vertex->ComponentNr[i] == nr) // if number is already present, don't add another time
+        break;  // breaking here will not cause error!
+    }
+    if (i == NumberOfBondsPerAtom[vertex->nr])
+      cerr << "Error: All Component entries are already occupied!" << endl;
+  } else
+      cerr << "Error: Given vertex is NULL!" << endl;
+};
+
+/** Output a list of flags, stating whether the bond was visited or not.
+ * \param *out output stream for debugging
+ */
+void molecule::OutputComponentNumber(ofstream *out, atom *vertex)
+{
+  for(int i=0;i<NumberOfBondsPerAtom[vertex->nr];i++) 
+    *out << vertex->ComponentNr[i] << "  ";
+};
+
+/** Allocates memory for all atom::*ComponentNr in this molecule and sets each entry to -1.
+ */
+void molecule::InitComponentNumbers()
+{
+  atom *Walker = start;
+  while(Walker->next != end) {
+    Walker = Walker->next;
+    if (Walker->ComponentNr != NULL)
+      Free((void **)&Walker->ComponentNr, "molecule::InitComponentNumbers: **Walker->ComponentNr");
+    Walker->ComponentNr = (int *) Malloc(sizeof(int)*NumberOfBondsPerAtom[Walker->nr], "molecule::InitComponentNumbers: *Walker->ComponentNr");
+    for (int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++)
+      Walker->ComponentNr[i] = -1;
+  }
+};
+
+/** Returns next unused bond for this atom \a *vertex or NULL of none exists.
+ * \param *vertex atom to regard
+ * \return bond class or NULL
+ */
+bond * molecule::FindNextUnused(atom *vertex)
+{
+  for(int i=0;i<NumberOfBondsPerAtom[vertex->nr];i++)
+    if (ListOfBondsPerAtom[vertex->nr][i]->IsUsed() == white)
+      return(ListOfBondsPerAtom[vertex->nr][i]);
+  return NULL;
+};
+
+/** Resets bond::Used flag of all bonds in this molecule.
+ * \return true - success, false - -failure
+ */
+void molecule::ResetAllBondsToUnused()
+{
+  bond *Binder = first;
+  while (Binder->next != last) {
+    Binder = Binder->next;
+    Binder->ResetUsed();
+  }
+};
+
+/** Resets atom::nr to -1 of all atoms in this molecule.
+ */
+void molecule::ResetAllAtomNumbers()
+{
+  atom *Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    Walker->GraphNr  = -1;
+  }
+};
+
+/** Output a list of flags, stating whether the bond was visited or not.
+ * \param *out output stream for debugging
+ * \param *list
+ */
+void OutputAlreadyVisited(ofstream *out, int *list)
+{
+  *out << Verbose(4) << "Already Visited Bonds:\t";
+  for(int i=1;i<=list[0];i++) *out << Verbose(0) << list[i] << "  ";
+  *out << endl;
+};
+
+/** Estimates by educated guessing (using upper limit) the expected number of fragments.
+ * The upper limit is
+ * \f[
+ *  n = N \cdot C^k
+ * \f]
+ * where \f$C=2^c\f$ and c is the maximum bond degree over N number of atoms.
+ * \param *out output stream for debugging
+ * \param order bond order k
+ * \return number n of fragments
+ */
+int molecule::GuesstimateFragmentCount(ofstream *out, int order)
+{
+  int c = 0;
+  int FragmentCount; 
+  // get maximum bond degree
+  atom *Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    c = (NumberOfBondsPerAtom[Walker->nr] > c) ? NumberOfBondsPerAtom[Walker->nr] : c;
+  }
+  FragmentCount = NoNonHydrogen*(1 << (c*order));
+  *out << Verbose(1) << "Upper limit for this subgraph is " << FragmentCount << " for " << NoNonHydrogen << " non-H atoms with maximum bond degree of " << c << "." << endl;
+  return FragmentCount;
+};  
+
+/** Performs a many-body bond order analysis for a given bond order.
+ * Writes for each fragment a config file.
+ * \param *out output stream for debugging
+ * \param BottomUpOrder up to how many neighbouring bonds a fragment contains in BondOrderScheme::BottumUp scheme
+ * \param TopDownOrder up to how many neighbouring bonds a fragment contains in BondOrderScheme::TopDown scheme
+ * \param Scheme which BondOrderScheme to use for the fragmentation
+ * \param *configuration configuration for writing config files for each fragment
+ * \param CutCyclic whether to add cut cyclic bond or to saturate
+ */
+void molecule::FragmentMolecule(ofstream *out, int BottomUpOrder, int TopDownOrder, enum BondOrderScheme Scheme, config *configuration, enum CutCyclicBond CutCyclic)
+{
+	MoleculeListClass **BondFragments = NULL;
+  MoleculeListClass *FragmentList = NULL;
+  atom *Walker = NULL;
+  int *SortIndex = NULL;
+  element *runner = NULL;
+  int AtomNo;
+  int MinimumRingSize;
+  int TotalFragmentCounter = 0;
+  int FragmentCounter = 0;
+  MoleculeLeafClass *MolecularWalker = NULL;
+  MoleculeLeafClass *Subgraphs = NULL;      // list of subgraphs from DFS analysis
+
+  CreateListOfBondsPerAtom(out);
+
+  // first perform a DFS analysis to gather info on cyclic structure and a list of disconnected subgraphs
+  Subgraphs = DepthFirstSearchAnalysis((ofstream *)&cout, false, MinimumRingSize);
+  MolecularWalker = Subgraphs;
+  // fill the bond structure of the individually stored subgraphs
+  while (MolecularWalker->next != NULL) {
+    MolecularWalker = MolecularWalker->next;
+    cout << Verbose(1) << "Creating adjacency list for subgraph " << MolecularWalker << "." << endl;
+    MolecularWalker->Leaf->CreateAdjacencyList((ofstream *)&cout, BondDistance);
+    MolecularWalker->Leaf->CreateListOfBondsPerAtom((ofstream *)&cout);
+  }
+  // fragment all subgraphs
+  if ((MinimumRingSize != -1) && ((BottomUpOrder >= MinimumRingSize) || (TopDownOrder >= MinimumRingSize))) {
+    cout << Verbose(0) << "Bond order greater than or equal to Minimum Ring size of " << MinimumRingSize << " found is not allowed." << endl;
+  } else {
+    FragmentCounter = 0;
+    MolecularWalker = Subgraphs;
+    // count subgraphs
+    while (MolecularWalker->next != NULL) {
+      MolecularWalker = MolecularWalker->next;
+      FragmentCounter++;
+    }
+    BondFragments = (MoleculeListClass **) Malloc(sizeof(MoleculeListClass *)*FragmentCounter, "molecule::FragmentMolecule - **BondFragments");
+    // fill the bond fragment list
+    FragmentCounter = 0;
+    MolecularWalker = Subgraphs;
+    while (MolecularWalker->next != NULL) {
+      MolecularWalker = MolecularWalker->next;
+      cout << Verbose(1) << "Fragmenting subgraph " << MolecularWalker << "." << endl;
+      if (MolecularWalker->Leaf->first->next != MolecularWalker->Leaf->last) {
+          // output ListOfBondsPerAtom for debugging
+        *out << Verbose(0) << endl << "From Contents of ListOfBondsPerAtom, all non-hydrogen atoms:" << endl;
+        Walker = MolecularWalker->Leaf->start;
+        while (Walker->next != MolecularWalker->Leaf->end) {
+          Walker = Walker->next; 
+#ifdef ADDHYDROGEN
+          if (Walker->type->Z != 1) {   // regard only non-hydrogen
+#endif
+            *out << Verbose(0) << "Atom " << Walker->Name << " has Bonds: "<<endl;
+            for(int j=0;j<MolecularWalker->Leaf->NumberOfBondsPerAtom[Walker->nr];j++) {
+              *out << Verbose(1) << *(MolecularWalker->Leaf->ListOfBondsPerAtom)[Walker->nr][j] << endl;
+            }
+#ifdef ADDHYDROGEN
+          }
+#endif
+        }
+        *out << endl;
+      
+        *out << Verbose(0) << endl << " ========== BOND ENERGY ========================= " << endl;
+        *out << Verbose(0) << "Begin of bond fragmentation." << endl;
+        BondFragments[FragmentCounter] = NULL;
+        if (Scheme == ANOVA) {
+          BondFragments[FragmentCounter] = MolecularWalker->Leaf->FragmentBOSSANOVA(out,BottomUpOrder,configuration);
+        }  
+        if ((Scheme == BottomUp) || (Scheme == Combined)) { // get overlapping subgraphs
+          BondFragments[FragmentCounter] = FragmentList = MolecularWalker->Leaf->FragmentBottomUp(out, BottomUpOrder, configuration, CutCyclic);
+        }
+        if (Scheme == TopDown) { // initialise top level with whole molecule
+          *out << Verbose(2) << "Initial memory allocating and initialising for whole molecule." << endl;
+          FragmentList = new MoleculeListClass(1, MolecularWalker->Leaf->AtomCount);
+          FragmentList->ListOfMolecules[0] = MolecularWalker->Leaf->CopyMolecule();
+          FragmentList->TEList[0] = 1.;
+        }
+        if ((Scheme == Combined) || (Scheme == TopDown)) {
+          *out << Verbose(1) << "Calling TopDown." << endl;
+          BondFragments[FragmentCounter] = FragmentList->FragmentTopDown(out, TopDownOrder, BondDistance, configuration, CutCyclic);
+          // remove this molecule from list again and free wrapper list
+          delete(FragmentList);
+          FragmentList = NULL;
+        }
+      } else {
+        cout << Verbose(0) << "Connection matrix has not yet been generated!" << endl;
+      }
+      TotalFragmentCounter += BondFragments[FragmentCounter]->NumberOfMolecules;
+      FragmentCounter++;  // next fragment list
+    }
+  }
+
+  // combine bond fragments list into a single one
+  FragmentList = new MoleculeListClass(TotalFragmentCounter, AtomCount);
+  TotalFragmentCounter = 0;
+  for (int i=0;i<FragmentCounter;i++) {
+    for(int j=0;j<BondFragments[i]->NumberOfMolecules;j++) {
+      FragmentList->ListOfMolecules[TotalFragmentCounter] =  BondFragments[i]->ListOfMolecules[j];
+      BondFragments[i]->ListOfMolecules[j] = NULL;
+      FragmentList->TEList[TotalFragmentCounter++] = BondFragments[i]->TEList[j];
+    }
+    delete(BondFragments[i]);
+  }
+  Free((void **)&BondFragments, "molecule::FragmentMolecule - **BondFragments");
+  
+  // now if there are actually any fragments to save on disk ...
+  if (FragmentList != NULL) {
+    // create a SortIndex to map from BFS labels to the sequence in which the atoms are given in the config file
+    SortIndex = (int *) Malloc(sizeof(int)*AtomCount, "molecule::FragmentMolecule: *SortIndex");
+    for(int i=0;i<AtomCount;i++)
+      SortIndex[i] = -1;
+    runner = elemente->start;
+    AtomNo = 0;
+    while (runner->next != elemente->end) { // go through every element
+      runner = runner->next;
+      if (ElementsInMolecule[runner->Z]) { // if this element got atoms
+        Walker = start;
+        while (Walker->next != end) { // go through every atom of this element
+          Walker = Walker->next;
+          if (Walker->type->Z == runner->Z) // if this atom fits to element
+            SortIndex[Walker->nr] = AtomNo++;
+        }
+      }
+    }
+    *out << Verbose(1) << "Writing " << FragmentList->NumberOfMolecules << " possible bond fragmentation configs" << endl;
+    if (FragmentList->OutputConfigForListOfFragments("BondFragment", configuration, SortIndex))
+      *out << Verbose(1) << "All configs written." << endl;
+    else
+      *out << Verbose(1) << "Some configs' writing failed." << endl;
+    Free((void **)&SortIndex, "molecule::FragmentMolecule: *SortIndex"); 
+    
+    // restore orbital and Stop values
+    CalculateOrbitals(*configuration);
+    
+    // free memory for bond part
+    *out << Verbose(1) << "Freeing bond memory" << endl;
+    delete(FragmentList); // remove bond molecule from memory
+    FragmentList = NULL;
+  } else
+    *out << Verbose(1) << "FragmentList is zero on return, splitting failed." << endl;
+  // free subgraph memory again
+  while (Subgraphs->next != NULL) {
+    Subgraphs = Subgraphs->next;
+    delete(Subgraphs->previous);
+  }
+  delete(Subgraphs);
+
+  *out << Verbose(0) << "End of bond fragmentation." << endl;
+};
+
+/** Creates an 2d array of pointer with an entry for each atom and each bond it has.
+ * Updates molecule::ListOfBondsPerAtom, molecule::NumberOfBondsPerAtom by parsing through
+ * bond chain list, using molecule::AtomCount and molecule::BondCount.
+ * Allocates memory, fills the array and exits
+ * \param *out output stream for debugging
+ */
+void molecule::CreateListOfBondsPerAtom(ofstream *out)
+{
+  bond *Binder = NULL;
+  atom *Walker = NULL;
+  int TotalDegree;
+  *out << Verbose(1) << "Begin of Creating ListOfBondsPerAtom: AtomCount = " << AtomCount << "\tBondCount = " << BondCount << "\tNoNonBonds = " << NoNonBonds << "." << endl;
+
+  // re-allocate memory
+  *out << Verbose(2) << "(Re-)Allocating memory." << endl;
+  if (ListOfBondsPerAtom != NULL) {
+    for(int i=0;i<AtomCount;i++)
+      Free((void **)&ListOfBondsPerAtom[i], "molecule::CreateListOfBondsPerAtom: ListOfBondsPerAtom[i]");
+    Free((void **)&ListOfBondsPerAtom, "molecule::CreateListOfBondsPerAtom: ListOfBondsPerAtom");
+  }
+  if (NumberOfBondsPerAtom != NULL)
+    Free((void **)&NumberOfBondsPerAtom, "molecule::CreateListOfBondsPerAtom: NumberOfBondsPerAtom");
+  ListOfBondsPerAtom = (bond ***) Malloc(sizeof(bond **)*AtomCount, "molecule::CreateListOfBondsPerAtom: ***ListOfBondsPerAtom");
+  NumberOfBondsPerAtom = (int *) Malloc(sizeof(int)*AtomCount, "molecule::CreateListOfBondsPerAtom: *NumberOfBondsPerAtom");
+
+  // reset bond counts per atom
+  for(int i=0;i<AtomCount;i++)
+    NumberOfBondsPerAtom[i] = 0;
+  // count bonds per atom
+  Binder = first;
+  while (Binder->next != last) {
+    Binder = Binder->next;
+    NumberOfBondsPerAtom[Binder->leftatom->nr]++;
+    NumberOfBondsPerAtom[Binder->rightatom->nr]++;
+  }
+  // allocate list of bonds per atom
+  for(int i=0;i<AtomCount;i++)
+    ListOfBondsPerAtom[i] = (bond **) Malloc(sizeof(bond *)*NumberOfBondsPerAtom[i], "molecule::CreateListOfBondsPerAtom: **ListOfBondsPerAtom[]");
+  // clear the list again, now each NumberOfBondsPerAtom marks current free field
+  for(int i=0;i<AtomCount;i++)
+    NumberOfBondsPerAtom[i] = 0;
+  // fill the list
+  Binder = first;
+  while (Binder->next != last) {
+    Binder = Binder->next;
+    ListOfBondsPerAtom[Binder->leftatom->nr][NumberOfBondsPerAtom[Binder->leftatom->nr]++] = Binder;
+    ListOfBondsPerAtom[Binder->rightatom->nr][NumberOfBondsPerAtom[Binder->rightatom->nr]++] = Binder;
+  }
+
+  // output list for debugging
+  *out << Verbose(3) << "ListOfBondsPerAtom for each atom:" << endl;
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next; 
+    *out << Verbose(4) << "Atom " << Walker->Name << " with " << NumberOfBondsPerAtom[Walker->nr] << " bonds: ";
+    TotalDegree = 0;
+    for (int j=0;j<NumberOfBondsPerAtom[Walker->nr];j++) {
+      *out << *ListOfBondsPerAtom[Walker->nr][j] << "\t";
+      TotalDegree += ListOfBondsPerAtom[Walker->nr][j]->BondDegree;
+    }
+    *out << " -- TotalDegree: " << TotalDegree << endl;
+  }      
+  *out << Verbose(1) << "End of Creating ListOfBondsPerAtom." << endl << endl;
+};
+
+/** Splits up a molecule into atomic, non-hydrogen, hydrogen-saturated fragments.
+ * \param *out output stream for debugging
+ * \param NumberOfTopAtoms number to initialise second parameter of MoleculeListClass with
+ * \param IsAngstroem whether atomic coordination is in Angstroem (true) or atomic length/bohrradous (false)
+ * \param factor additional factor TE and forces factors are multiplied with
+ * \param CutCyclic whether to add cut cyclic bond or to saturate
+ * \return MoleculelistClass of pointer to each atomic fragment.
+ */
+MoleculeListClass * molecule::GetAtomicFragments(ofstream *out, int NumberOfTopAtoms, bool IsAngstroem, double factor, enum CutCyclicBond CutCyclic)
+{
+  atom *TopAtom = NULL, *BottomAtom = NULL; // Top = this, Bottom = AtomicFragment->ListOfMolecules[No]
+  atom *Walker = NULL;
+  MoleculeListClass *AtomicFragments = NULL;
+  atom **AtomList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::GetAtomicFragments: **AtomList");
+  for (int i=0;i<AtomCount;i++)
+    AtomList[i] = NULL;
+  bond **BondList = (bond **) Malloc(sizeof(bond *)*BondCount, "molecule::GetAtomicFragments: **AtomList");
+  for (int i=0;i<BondCount;i++)
+    BondList[i] = NULL;
+  int No = 0, Cyclic;
+
+  *out << Verbose(0) << "Begin of GetAtomicFragments." << endl;
+
+  *out << Verbose(1) << "Atoms in Molecule: ";
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    *out << Walker << "\t";
+  } 
+  *out << endl;
+#ifdef ADDHYDROGEN
+  if (NoNonHydrogen != 0) {
+    AtomicFragments = new MoleculeListClass(NoNonHydrogen, NumberOfTopAtoms);
+  } else {
+    *out << Verbose(1) << "NoNonHydrogen is " << NoNonHydrogen << ", can't allocated MoleculeListClass." << endl;
+#else
+  if (AtomCount != 0) {
+    AtomicFragments = new MoleculeListClass(AtomCount, NumberOfTopAtoms);
+  } else {
+    *out << Verbose(1) << "AtomCount is " << AtomCount << ", can't allocated MoleculeListClass." << endl;
+#endif
+    return (AtomicFragments);
+  }
+  
+  TopAtom = start;
+  while (TopAtom->next != end) {
+    TopAtom = TopAtom->next;
+  //for(int i=0;i<AtomCount;i++) {
+#ifdef ADDHYDROGEN
+    if (TopAtom->type->Z != 1) {   // regard only non-hydrogen
+#endif
+      //TopAtom = AtomsInMolecule[i];
+      *out << Verbose(1) << "Current non-Hydrogen Atom: " << TopAtom->Name << endl;
+
+      // go through all bonds to check if cyclic
+      Cyclic = 0;
+      for(int i=0;i<NumberOfBondsPerAtom[TopAtom->nr];i++)
+        Cyclic += (ListOfBondsPerAtom[TopAtom->nr][i]->Cyclic) ? 1 : 0;
+
+#ifdef ADDHYDROGEN
+      if (No > NoNonHydrogen) {
+#else
+      if (No > AtomCount) {
+#endif
+        *out << Verbose(1) << "Access on created AtomicFragmentsListOfMolecules[" << No << "] beyond NumberOfMolecules " << AtomicFragments->NumberOfMolecules << "." << endl;
+        break;
+      }
+      if (AtomList[TopAtom->nr] == NULL) {
+        // create new molecule
+        AtomicFragments->ListOfMolecules[No] = new molecule(elemente); // allocate memory
+        AtomicFragments->TEList[No] = factor;
+        AtomicFragments->ListOfMolecules[No]->BondDistance = BondDistance;
+        
+        // add central atom
+        BottomAtom = AtomicFragments->ListOfMolecules[No]->AddCopyAtom(TopAtom); // add this central atom to molecule
+        AtomList[TopAtom->nr] = BottomAtom; // mark down in list
+
+        // create fragment          
+        *out << Verbose(1) << "New fragment around atom: " << TopAtom->Name << endl;
+        BreadthFirstSearchAdd(out,AtomicFragments->ListOfMolecules[No], AtomList, BondList, TopAtom, NULL, 0, IsAngstroem, (Cyclic == 0) ? SaturateBond : CutCyclic);
+        AtomicFragments->ListOfMolecules[No]->CountAtoms(out);
+        // actually we now have to reset both arrays to NULL again, but BFS is overkill anyway for getting the atomic fragments
+        // thus we do it in O(1) and avoid the O(n) which would make this routine O(N^2)!  
+        AtomList[TopAtom->nr] = NULL;  // remove this fragment's central atom again from the list
+        
+        *out << Verbose(1) << "Atoms in Fragment " << TopAtom->nr << ": ";
+        Walker = AtomicFragments->ListOfMolecules[No]->start;
+        while (Walker->next != AtomicFragments->ListOfMolecules[No]->end) {
+          Walker = Walker->next; 
+        //for(int k=0;k<AtomicFragments->ListOfMolecules[No]->AtomCount;k++)
+          *out << Walker << "(" << Walker->father << ")\t";
+        }
+        *out << endl;
+        No++;
+      }
+#ifdef ADDHYDROGEN
+    } else
+      *out << Verbose(1) << "Current Hydrogen Atom: " << TopAtom->Name << endl;
+#endif
+  }
+
+  // output of full list before reduction
+  if (AtomicFragments != NULL) {
+    *out << "AtomicFragments: ";
+    AtomicFragments->Output(out);
+    *out << endl;
+  } else 
+    *out << Verbose(1) << "AtomicFragments is zero on return, splitting failed." << endl;
+
+  // Reducing the atomic fragments
+  if (AtomicFragments != NULL) {
+    // check whether there are equal fragments by GetMappingToUniqueFragments
+    AtomicFragments->ReduceToUniqueList(out, &cell_size[0], BondDistance);
+  } else
+    *out << Verbose(1) << "AtomicFragments is zero, reducing failed." << endl;
+  Free((void **)&BondList, "molecule::GetAtomicFragments: **BondList");
+  Free((void **)&AtomList, "molecule::GetAtomicFragments: **AtomList");
+  *out << Verbose(0) << "End of GetAtomicFragments." << endl;
+  return (AtomicFragments);
+};
+
+/** Splits up the bond in a molecule into a left and a right fragment.
+ * \param *out output stream for debugging
+ * \param *Bond bond to broken up into getting allocated ...
+ * \param *LeftFragment ... left fragment molecule ... (ptr to the memory cell wherein the adress for the Fragment is to be stored)
+ * \param *RightFragment ... and right fragment molecule to be returned.(ptr to the memory cell wherein the adress for the Fragment is to be stored)
+ * \param IsAngstroem whether atomic coordination is in Angstroem (true) or atomic length/bohrradous (false)
+ * \param CutCyclic whether to add cut cyclic bond or not
+ * \sa FragmentTopDown()
+ */
+void molecule::FragmentMoleculeByBond(ofstream *out, bond *Bond, molecule **LeftFragment, molecule **RightFragment, bool IsAngstroem, enum CutCyclicBond CutCyclic)
+{
+  *out << Verbose(0) << "Begin of FragmentMoleculeByBond." << endl; 
+#ifdef ADDHYDROGEN
+  if ((Bond->leftatom->type->Z != 1) && (Bond->rightatom->type->Z != 1)) { // if both bond partners aren't hydrogen ...
+#endif    
+    *out << Verbose(1) << "Current Non-Hydrogen Bond: " << Bond->leftatom->Name << " and " << Bond->rightatom->Name << endl;
+    *LeftFragment = new molecule(elemente);
+    *RightFragment = new molecule(elemente);
+    // initialise marker list for all atoms
+    atom **AddedAtomListLeft = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::FragmentMoleculeByBond: **AddedAtomListLeft");
+    atom **AddedAtomListRight = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::FragmentMoleculeByBond: **AddedAtomListRight");
+    for (int i=0;i<AtomCount;i++) {
+      AddedAtomListLeft[i] = NULL;
+      AddedAtomListRight[i] = NULL;
+    }
+    bond **AddedBondListLeft = (bond **) Malloc(sizeof(bond *)*BondCount, "molecule::FragmentMoleculeByBond: **AddedBondListLeft");
+    bond **AddedBondListRight = (bond **) Malloc(sizeof(bond *)*BondCount, "molecule::FragmentMoleculeByBond: **AddedBondListRight");
+    for (int i=0;i<BondCount;i++) {
+      AddedBondListLeft[i] = NULL;
+      AddedBondListRight[i] = NULL;
+    }
+  
+    // tag and add all atoms that have to be included
+    *out << Verbose(1) << "Adding BFS-wise on left hand side with Bond Order " << NoNonBonds-1 << "." << endl;
+    AddedAtomListLeft[Bond->leftatom->nr] = (*LeftFragment)->AddCopyAtom(Bond->leftatom);
+    BreadthFirstSearchAdd(out, *LeftFragment, AddedAtomListLeft, AddedBondListLeft, Bond->leftatom, Bond, 
+#ifdef ADDHYDROGEN
+    NoNonBonds
+#else
+    BondCount
+#endif    
+                                                                                                            , IsAngstroem, CutCyclic);
+    *out << Verbose(1) << "Adding BFS-wise on right hand side with Bond Order " << NoNonBonds-1 << "." << endl;
+    AddedAtomListRight[Bond->rightatom->nr] = (*RightFragment)->AddCopyAtom(Bond->rightatom);
+    BreadthFirstSearchAdd(out, *RightFragment, AddedAtomListRight, AddedBondListRight, Bond->rightatom, Bond, 
+#ifdef ADDHYDROGEN
+    NoNonBonds
+#else
+    BondCount
+#endif    
+                                                                                                            , IsAngstroem, CutCyclic);  
+ 
+    // count atoms
+    (*LeftFragment)->CountAtoms(out);
+    (*RightFragment)->CountAtoms(out);
+    // free all and exit
+    Free((void **)&AddedAtomListLeft, "molecule::FragmentMoleculeByBond: **AddedAtomListLeft");
+    Free((void **)&AddedAtomListRight, "molecule::FragmentMoleculeByBond: **AddedAtomListRight");
+    Free((void **)&AddedBondListLeft, "molecule::FragmentMoleculeByBond: **AddedBondListLeft");
+    Free((void **)&AddedBondListRight, "molecule::FragmentMoleculeByBond: **AddedBondListRight");
+#ifdef ADDHYDROGEN
+  }
+#endif
+  *out << Verbose(0) << "End of FragmentMoleculeByBond." << endl;
+};
+
+/** Returns the given \a **FragmentList filled with molecules around each bond including up to \a BondDegree neighbours.
+ * \param *out output stream for debugging
+ * \param BondOrder neighbours on each side to be ...
+ * \param IsAngstroem whether atomic coordination is in Angstroem (true) or atomic length/bohrradous (false)
+ * \param CutCyclic whether to add cut cyclic bond or to saturate
+ * \sa FragmentBottomUp(), molecule::AddBondOrdertoMolecule()
+ */
+MoleculeListClass * molecule::GetEachBondFragmentOfOrder(ofstream *out, int BondOrder, bool IsAngstroem, enum CutCyclicBond CutCyclic)
+{
+  /// Allocate memory for Bond list and go through each bond and fragment molecule up to bond order and fill the list to be returned.
+  MoleculeListClass *FragmentList = NULL;
+  atom **AddedAtomList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::GetBondFragmentOfOrder: **AddedAtomList");
+  bond **AddedBondList = (bond **) Malloc(sizeof(bond *)*BondCount, "molecule::GetBondFragmentOfOrder: **AddedBondList");
+  bond *Binder = NULL;
+
+  *out << Verbose(0) << "Begin of GetEachBondFragmentOfOrder." << endl;
+#ifdef ADDHYDROGEN
+  if (NoNonBonds != 0) {
+    FragmentList = new MoleculeListClass(NoNonBonds, AtomCount);
+  } else {
+    *out << Verbose(1) << "NoNonBonds is " << NoNonBonds << ", can't allocate list." << endl;
+#else
+  if (BondCount != 0) {
+    FragmentList = new MoleculeListClass(BondCount, AtomCount);
+  } else {
+    *out << Verbose(1) << "BondCount is " << BondCount << ", can't allocate list." << endl;
+#endif
+  }
+  int No = 0;
+  Binder = first;
+  while (Binder->next != last) { // get each bond, NULL is returned if it is a H-H bond
+    Binder = Binder->next;
+#ifdef ADDHYDROGEN
+    if ((Binder->leftatom->type->Z != 1) && (Binder->rightatom->type->Z != 1))  // if both bond partners aren't hydrogen ...
+#endif
+      if ((CutCyclic == SaturateBond) || (!Binder->Cyclic)) {
+        *out << Verbose(1) << "Getting Fragment for Non-Hydrogen Bond: " << Binder->leftatom->Name << " and " << Binder->rightatom->Name << endl;
+        FragmentList->ListOfMolecules[No] = new molecule(elemente);
+        // initialise marker list for all atoms
+        for (int i=0;i<AtomCount;i++)
+          AddedAtomList[i] = NULL;
+        for (int i=0;i<BondCount;i++)
+          AddedBondList[i] = NULL;
+      
+        // add root bond as first bond (this is needed later on fragmenting)
+        *out << Verbose(1) << "Adding Root Bond " << *Binder << " and its atom." << endl;
+        AddedAtomList[Binder->leftatom->nr] = FragmentList->ListOfMolecules[No]->AddCopyAtom(Binder->leftatom);
+        AddedAtomList[Binder->rightatom->nr] = FragmentList->ListOfMolecules[No]->AddCopyAtom(Binder->rightatom);
+        AddedBondList[Binder->nr] = FragmentList->ListOfMolecules[No]->AddBond(AddedAtomList[Binder->leftatom->nr], AddedAtomList[Binder->rightatom->nr], Binder->BondDegree);
+    
+        // tag and add all atoms that have to be included
+        *out << Verbose(1) << "Adding BFS-wise on left hand side." << endl;
+        BreadthFirstSearchAdd(out, FragmentList->ListOfMolecules[No], AddedAtomList, AddedBondList, Binder->leftatom, NULL, BondOrder, IsAngstroem, CutCyclic);  
+        *out << Verbose(1) << "Adding BFS-wise on right hand side." << endl;
+        BreadthFirstSearchAdd(out, FragmentList->ListOfMolecules[No], AddedAtomList, AddedBondList, Binder->rightatom, NULL, BondOrder, IsAngstroem, CutCyclic);  
+        
+        // count atoms
+        FragmentList->ListOfMolecules[No]->CountAtoms(out);
+        FragmentList->TEList[No] = 1.;
+        *out << Verbose(1) << "GetBondFragmentOfOrder: " << Binder->nr << "th Fragment: " << FragmentList->ListOfMolecules[No] << "." << endl;
+        No++;
+      }
+  }
+  // free all lists
+  Free((void **)&AddedAtomList, "molecule::GetBondFragmentOfOrder: **AddedAtomList");
+  Free((void **)&AddedBondList, "molecule::GetBondFragmentOfOrder: **AddedBondList");
+  // output and exit
+  FragmentList->Output(out);
+  *out << Verbose(0) << "End of GetEachBondFragmentOfOrder." << endl;
+  return (FragmentList);
+}; 
+
+/** Adds atoms up to \a BondCount distance from \a *Root and notes them down in \a **AddedAtomList.
+ * Gray vertices are always enqueued in an AtomStackClass FIFO queue, the rest is usual BFS with adding vertices found was
+ * white and putting into queue. 
+ * \param *out output stream for debugging
+ * \param *Mol Molecule class to add atoms to
+ * \param **AddedAtomList list with added atom pointers, index is atom father's number
+ * \param **AddedBondList list with added bond pointers, index is bond father's number
+ * \param *Root root vertex for BFS
+ * \param *Bond bond not to look beyond
+ * \param BondOrder maximum distance for vertices to add
+ * \param IsAngstroem lengths are in angstroem or bohrradii
+ * \param CutCyclic whether to cut cyclic bonds (means saturate on need with hydrogen) or to always add
+ */  
+void molecule::BreadthFirstSearchAdd(ofstream *out, molecule *Mol, atom **&AddedAtomList, bond **&AddedBondList, atom *Root, bond *Bond, int BondOrder, bool IsAngstroem, enum CutCyclicBond CutCyclic)
+{
+  atom **PredecessorList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::BreadthFirstSearchAdd: **PredecessorList");
+  int *ShortestPathList = (int *) Malloc(sizeof(int)*AtomCount, "molecule::BreadthFirstSearchAdd: *ShortestPathList");
+  enum Shading *ColorList = (enum Shading *) Malloc(sizeof(enum Shading)*AtomCount, "molecule::BreadthFirstSearchAdd: *ColorList");
+  AtomStackClass *AtomStack = new AtomStackClass(AtomCount);
+  atom *Walker = NULL, *OtherAtom = NULL;
+  bond *Binder = NULL;
+
+  // add Root if not done yet
+  AtomStack->ClearStack();
+  if (AddedAtomList[Root->nr] == NULL)  // add Root if not yet present
+    AddedAtomList[Root->nr] = Mol->AddCopyAtom(Root);
+  AtomStack->Push(Root);
+
+  // initialise each vertex as white with no predecessor, empty queue, color Root lightgray
+  for (int i=0;i<AtomCount;i++) {
+    PredecessorList[i] = NULL;
+    ShortestPathList[i] = -1;
+    if (AddedAtomList[i] != NULL) // mark already present atoms (i.e. Root and maybe others) as visited
+      ColorList[i] = lightgray;
+    else
+      ColorList[i] = white;
+  }
+  ShortestPathList[Root->nr] = 0;
+  
+  // and go on ... Queue always contains all lightgray vertices
+  while (!AtomStack->IsEmpty()) {
+    // we have to pop the oldest atom from stack. This keeps the atoms on the stack always of the same ShortestPath distance.
+    // e.g. if current atom is 2, push to end of stack are of length 3, but first all of length 2 would be popped. They again
+    // append length of 3 (their neighbours). Thus on stack we have always atoms of a certain length n at bottom of stack and
+    // followed by n+1 till top of stack.
+    Walker = AtomStack->PopFirst(); // pop oldest added
+    *out << Verbose(1) << "Current Walker is: " << Walker->Name << ", and has " << NumberOfBondsPerAtom[Walker->nr] << " bonds." << endl; 
+    for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {
+      Binder = ListOfBondsPerAtom[Walker->nr][i];
+      if (Binder != NULL) { // don't look at bond equal NULL
+        OtherAtom = Binder->GetOtherAtom(Walker);
+        *out << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *Binder << "." << endl;
+        if (ColorList[OtherAtom->nr] == white) {
+          if (Binder != Bond) // let other atom white if it's via Root bond. In case it's cyclic it has to be reached again (yet Root is from OtherAtom already black, thus no problem) 
+            ColorList[OtherAtom->nr] = lightgray;
+          PredecessorList[OtherAtom->nr] = Walker;  // Walker is the predecessor
+          ShortestPathList[OtherAtom->nr] = ShortestPathList[Walker->nr]+1;
+          *out << Verbose(2) << "Coloring OtherAtom " << OtherAtom->Name << " " << ((ColorList[OtherAtom->nr] == white) ? "white" : "lightgray") << ", its predecessor is " << Walker->Name << " and its Shortest Path is " << ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl; 
+          if ((((ShortestPathList[OtherAtom->nr] < BondOrder) && (Binder != Bond)) || (Binder->Cyclic && (CutCyclic == KeepBond))) ) { // Check for maximum distance
+            *out << Verbose(3);
+            if (AddedAtomList[OtherAtom->nr] == NULL) { // add if it's not been so far
+              AddedAtomList[OtherAtom->nr] = Mol->AddCopyAtom(OtherAtom);
+              *out << "Added OtherAtom " << OtherAtom->Name;
+              AddedBondList[Binder->nr] = Mol->AddBond(AddedAtomList[Walker->nr], AddedAtomList[OtherAtom->nr], Binder->BondDegree);
+              AddedBondList[Binder->nr]->Cyclic = Binder->Cyclic;
+              AddedBondList[Binder->nr]->Type = Binder->Type;
+              *out << " 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)
+              *out << "Not adding OtherAtom " << OtherAtom->Name;
+              if (AddedBondList[Binder->nr] == NULL) {
+                AddedBondList[Binder->nr] = Mol->AddBond(AddedAtomList[Walker->nr], AddedAtomList[OtherAtom->nr], Binder->BondDegree);
+                AddedBondList[Binder->nr]->Cyclic = Binder->Cyclic;
+                AddedBondList[Binder->nr]->Type = Binder->Type;
+                *out << ", added Bond " << *(AddedBondList[Binder->nr]);
+              } else
+                *out << ", not added Bond ";
+            }
+            *out << ", putting OtherAtom into queue." << endl;
+            AtomStack->Push(OtherAtom);
+          } else { // out of bond order, then replace
+            if ((AddedAtomList[OtherAtom->nr] == NULL) && (Binder->Cyclic))
+              ColorList[OtherAtom->nr] = white; // unmark if it has not been queued/added, to make it available via its other bonds (cyclic)
+            if (Binder == Bond)
+              *out << Verbose(3) << "Not Queueing, is the Root bond";
+            else if (ShortestPathList[OtherAtom->nr] >= BondOrder)
+              *out << Verbose(3) << "Not Queueing, is out of Bond Count of " << BondOrder;
+            if ((Binder->Cyclic && (CutCyclic != KeepBond)))
+              *out << ", is part of a cyclic bond yet we don't keep them, saturating bond with Hydrogen." << endl;
+            if (!Binder->Cyclic)
+              *out << ", is not part of a cyclic bond, saturating bond with Hydrogen." << endl;
+            if (AddedBondList[Binder->nr] == NULL) {
+              if ((AddedAtomList[OtherAtom->nr] != NULL) && (CutCyclic == KeepBond)) { // .. whether we add or saturate
+                AddedBondList[Binder->nr] = Mol->AddBond(AddedAtomList[Walker->nr], AddedAtomList[OtherAtom->nr], Binder->BondDegree);
+                AddedBondList[Binder->nr]->Cyclic = Binder->Cyclic;
+                AddedBondList[Binder->nr]->Type = Binder->Type;
+              } else {
+#ifdef ADDHYDROGEN
+                Mol->AddHydrogenReplacementAtom(out, Binder, AddedAtomList[Walker->nr], Walker, OtherAtom, ListOfBondsPerAtom[Walker->nr], NumberOfBondsPerAtom[Walker->nr], IsAngstroem);
+#endif
+              }
+            }
+          }
+        } else {
+          *out << 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) {
+            if ((Binder != Bond) && (Binder->Cyclic) && (((ShortestPathList[Walker->nr]+1) < BondOrder) || (CutCyclic == KeepBond))) { 
+              AddedBondList[Binder->nr] = Mol->AddBond(AddedAtomList[Walker->nr], AddedAtomList[OtherAtom->nr], Binder->BondDegree);
+              AddedBondList[Binder->nr]->Cyclic = Binder->Cyclic;
+              AddedBondList[Binder->nr]->Type = Binder->Type;
+            } else { // if it's root bond it has to broken (otherwise we would not create the fragments)
+#ifdef ADDHYDROGEN
+              Mol->AddHydrogenReplacementAtom(out, Binder, AddedAtomList[Walker->nr], Walker, OtherAtom, ListOfBondsPerAtom[Walker->nr], NumberOfBondsPerAtom[Walker->nr], IsAngstroem);
+#endif
+            }
+          }
+        }
+      }
+    }
+    ColorList[Walker->nr] = black;
+    *out << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl; 
+  }
+  Free((void **)&PredecessorList, "molecule::BreadthFirstSearchAdd: **PredecessorList");
+  Free((void **)&ShortestPathList, "molecule::BreadthFirstSearchAdd: **ShortestPathList");
+  Free((void **)&ColorList, "molecule::BreadthFirstSearchAdd: **ColorList");
+  delete(AtomStack);
+};
+
+/** Adds bond structure to this molecule from \a Father molecule.
+ * This basically causes this molecule to become an induced subgraph of the \a Father, i.e. for every bond in Father
+ * with end points present in this molecule, bond is created in this molecule.
+ * Special care was taken to ensure that this is of complexity O(N), where N is the \a Father's molecule::AtomCount.
+ * \param *out output stream for debugging
+ * \param *Father father molecule
+ * \return true - is induced subgraph, false - there are atoms with fathers not in \a Father
+ * \todo not checked, not fully working probably
+ */
+bool molecule::BuildInducedSubgraph(ofstream *out, const molecule *Father)
+{
+  atom *Walker = NULL, *OtherAtom = NULL;
+  bool status = true;
+  atom **ParentList = (atom **) Malloc(sizeof(atom *)*Father->AtomCount, "molecule::BuildInducedSubgraph: **ParentList");
+
+  *out << Verbose(2) << "Begin of BuildInducedSubgraph." << endl;
+  
+  // reset parent list
+  *out << Verbose(3) << "Resetting ParentList." << endl;
+  for (int i=0;i<Father->AtomCount;i++)
+    ParentList[i] = NULL;
+  
+  // fill parent list with sons
+  *out << Verbose(3) << "Filling Parent List." << endl;
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    ParentList[Walker->father->nr] = Walker;
+    // Outputting List for debugging
+    *out << Verbose(4) << "Son["<< Walker->father->nr <<"] of " << Walker->father <<  " is " << ParentList[Walker->father->nr] << "." << endl;
+  }
+
+  // check each entry of parent list and if ok (one-to-and-onto matching) create bonds
+  *out << Verbose(3) << "Creating bonds." << endl;
+  Walker = Father->start;
+  while (Walker->next != Father->end) {
+    Walker = Walker->next;
+    if (ParentList[Walker->nr] != NULL) {
+      if (ParentList[Walker->nr]->father != Walker) {
+        status = false;
+      } else {
+        for (int i=0;i<Father->NumberOfBondsPerAtom[Walker->nr];i++) {
+          OtherAtom = Father->ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker);
+          if (ParentList[OtherAtom->nr] != NULL) { // if otheratom is also a father of an atom on this molecule, create the bond
+            *out << Verbose(4) << "Endpoints of Bond " << Father->ListOfBondsPerAtom[Walker->nr][i] << " are both present: " << ParentList[Walker->nr]->Name << " and " << ParentList[OtherAtom->nr]->Name << "." << endl;
+            AddBond(ParentList[Walker->nr], ParentList[OtherAtom->nr], Father->ListOfBondsPerAtom[Walker->nr][i]->BondDegree);
+          }
+        }
+      }
+    }
+  }
+
+  Free((void **)&ParentList, "molecule::BuildInducedSubgraph: **ParentList");
+  *out << Verbose(2) << "End of BuildInducedSubgraph." << endl;
+  return status;
+};
+
+
+/** Looks through a AtomStackClass and returns the likeliest removal candiate.
+ * \param *out output stream for debugging messages
+ * \param *&Leaf KeySet to look through
+ * \param *&ShortestPathList list of the shortest path to decide which atom to suggest as removal candidate in the end
+ * \param index of the atom suggested for removal 
+ */
+int molecule::LookForRemovalCandidate(ofstream *&out, KeySet *&Leaf, int *&ShortestPathList)
+{
+  atom *Runner = NULL;
+  int SP, Removal;
+  
+  *out << Verbose(2) << "Looking for removal candidate." << endl;
+  SP = -1; //0;  // not -1, so that Root is never removed
+  Removal = -1;
+  for (KeySet::iterator runner = Leaf->begin(); runner != Leaf->end(); runner++) {
+    Runner = FindAtom((*runner));
+    if (Runner->type->Z != 1) { // skip all those added hydrogens when re-filling snake stack
+      if (ShortestPathList[(*runner)] > SP) {  // remove the oldest one with longest shortest path
+        SP = ShortestPathList[(*runner)];
+        Removal = (*runner);
+      }
+    }
+  }
+  return Removal;
+};
+
+/** Stores a fragment from \a SnakeStack into \a molecule.
+ * First creates the minimal set of atoms from the KeySet, then creates the bond structure from the complete
+ * molecule and adds missing hydrogen where bonds were cut. 
+ * \param *out output stream for debugging messages
+ * \param &Leaflet pointer to KeySet structure 
+ * \param *configuration configuration for writing config files for each fragment
+ * \return pointer to constructed molecule
+ */
+molecule * molecule::StoreFragmentFromKeyset(ofstream *&out, KeySet &Leaflet, config *&configuration)
+{
+  atom *Runner = NULL, *FatherOfRunner = NULL, *OtherFather = NULL;
+  atom **SonList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::StoreFragmentFromStack: **SonList");
+  molecule *Leaf = new molecule(elemente);
+  
+  *out << Verbose(1) << "Begin of StoreFragmentFromKeyset." << endl;
+  
+  Leaf->BondDistance = BondDistance;
+  for(int i=0;i<NDIM*2;i++)
+    Leaf->cell_size[i] = cell_size[i]; 
+
+  // initialise SonList (indicates when we need to replace a bond with hydrogen instead)
+  for(int i=0;i<AtomCount;i++)
+    SonList[i] = NULL;
+
+  // first create the minimal set of atoms from the KeySet
+  for(KeySet::iterator runner = Leaflet.begin(); runner != Leaflet.end(); runner++) {
+    FatherOfRunner =  FindAtom((*runner));
+    SonList[FatherOfRunner->nr] = Leaf->AddCopyAtom(FatherOfRunner);
+  }
+  
+  // create the bonds between all: Make it an induced subgraph and add hydrogen
+  *out << Verbose(2) << "Creating bonds from father graph (i.e. induced subgraph creation)." << endl;
+  Runner = Leaf->start;
+  while (Runner->next != Leaf->end) {
+    Runner = Runner->next;
+    FatherOfRunner = Runner->father;
+    if (SonList[FatherOfRunner->nr] != NULL)  {  // check if this, our father, is present in list
+      // create all bonds
+      for (int i=0;i<NumberOfBondsPerAtom[FatherOfRunner->nr];i++) { // go through every bond of father 
+        OtherFather = ListOfBondsPerAtom[FatherOfRunner->nr][i]->GetOtherAtom(FatherOfRunner);
+        *out << Verbose(2) << "Father " << *FatherOfRunner << " of son " << *SonList[FatherOfRunner->nr] << " is bound to " << *OtherFather;
+        if (SonList[OtherFather->nr] != NULL) {
+          *out << ", whose son is " << *SonList[OtherFather->nr] << "." << endl; 
+          if (OtherFather->nr > FatherOfRunner->nr) { // add bond (nr check is for adding only one of both variants: ab, ba)
+            *out << Verbose(3) << "Adding Bond: " << Leaf->AddBond(Runner, SonList[OtherFather->nr], ListOfBondsPerAtom[FatherOfRunner->nr][i]->BondDegree) << "." << endl;
+            //NumBonds[Runner->nr]++;
+          } else { 
+            *out << Verbose(3) << "Not adding bond, labels in wrong order." << endl;
+          }
+        } else {
+          *out << ", who has no son in this fragment molecule." << endl; 
+#ifdef ADDHYDROGEN
+          *out << Verbose(3) << "Adding Hydrogen to " << Runner->Name << " and a bond in between." << endl;
+          Leaf->AddHydrogenReplacementAtom(out, ListOfBondsPerAtom[FatherOfRunner->nr][i], Runner, FatherOfRunner, OtherFather, ListOfBondsPerAtom[FatherOfRunner->nr],NumberOfBondsPerAtom[FatherOfRunner->nr], configuration->GetIsAngstroem());
+#endif
+          //NumBonds[Runner->nr] += ListOfBondsPerAtom[FatherOfRunner->nr][i]->BondDegree;
+        }
+      }
+    } else {
+      *out << Verbose(0) << "ERROR: Son " << Runner->Name << " has father " << FatherOfRunner->Name << " but its entry in SonList is " << SonList[FatherOfRunner->nr] << "!" << endl;
+    }
+#ifdef ADDHYDROGEN
+    while ((Runner->next != Leaf->end) && (Runner->next->type->Z == 1)) // skip added hydrogen
+      Runner = Runner->next;
+#endif       
+  }
+  Leaf->CreateListOfBondsPerAtom(out);
+  //Leaflet->Leaf->ScanForPeriodicCorrection(out);
+  Free((void **)&SonList, "molecule::StoreFragmentFromStack: **SonList");
+  *out << Verbose(1) << "End of StoreFragmentFromKeyset." << endl;
+  return Leaf;
+};
+
+/** Creates \a MoleculeListClass of all unique fragments of the \a molecule containing \a Order atoms or vertices.
+ * The picture to have in mind is that of a DFS "snake" of a certain length \a Order, i.e. as in the infamous
+ * computer game, that winds through the connected graph representing the molecule. Color (white,
+ * lightgray, darkgray, black) indicates whether a vertex has been discovered so far or not. Labels will help in
+ * creating only unique fragments and not additional ones with vertices simply in different sequence.
+ * The Predecessor is always the one that came before in discovering, needed on backstepping. And
+ * finally, the ShortestPath is needed for removing vertices from the snake stack during the back-
+ * stepping.
+ * \param *out output stream for debugging
+ * \param Order number of atoms in each fragment
+ * \param *configuration configuration for writing config files for each fragment
+ * \return List of all unique fragments with \a Order atoms
+ */
+/*
+MoleculeListClass * molecule::CreateListOfUniqueFragmentsOfOrder(ofstream *out, int Order, config *configuration)
+{
+  atom **PredecessorList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::CreateListOfUniqueFragmentsOfOrder: **PredecessorList");
+  int *ShortestPathList = (int *) Malloc(sizeof(int)*AtomCount, "molecule::CreateListOfUniqueFragmentsOfOrder: *ShortestPathList");
+  int *Labels = (int *) Malloc(sizeof(int)*AtomCount, "molecule::CreateListOfUniqueFragmentsOfOrder: *Labels");
+  enum Shading *ColorVertexList = (enum Shading *) Malloc(sizeof(enum Shading)*AtomCount, "molecule::CreateListOfUniqueFragmentsOfOrder: *ColorList");
+  enum Shading *ColorEdgeList = (enum Shading *) Malloc(sizeof(enum Shading)*BondCount, "molecule::CreateListOfUniqueFragmentsOfOrder: *ColorBondList");
+  AtomStackClass *RootStack = new AtomStackClass(AtomCount);
+  AtomStackClass *TouchedStack = new AtomStackClass((int)pow(4,Order)+2); // number of atoms reached from one with maximal 4 bonds plus Root itself
+  AtomStackClass *SnakeStack = new AtomStackClass(Order+1); // equal to Order is not possible, as then the AtomStackClass cannot discern between full and empty stack!
+  MoleculeLeafClass *Leaflet = NULL, *TempLeaf = NULL; 
+  MoleculeListClass *FragmentList = NULL;
+  atom *Walker = NULL, *OtherAtom = NULL, *Root = NULL, *Removal = NULL;
+  bond *Binder = NULL;
+  int RunningIndex = 0, FragmentCounter = 0;
+
+  *out << Verbose(1) << "Begin of CreateListOfUniqueFragmentsOfOrder." << endl;
+
+  // reset parent list
+  *out << Verbose(3) << "Resetting labels, parent, predecessor, color and shortest path lists." << endl;
+  for (int i=0;i<AtomCount;i++) { // reset all atom labels
+    // initialise each vertex as white with no predecessor, empty queue, color lightgray, not labelled, no sons
+		Labels[i] = -1;
+    SonList[i] = NULL;
+    PredecessorList[i] = NULL;
+    ColorVertexList[i] = white;
+    ShortestPathList[i] = -1;
+  }
+  for (int i=0;i<BondCount;i++)
+    ColorEdgeList[i] = white;
+	RootStack->ClearStack();	// clearstack and push first atom if exists
+  TouchedStack->ClearStack();
+  Walker = start->next;
+  while ((Walker != end)
+#ifdef ADDHYDROGEN
+   && (Walker->type->Z == 1)
+#endif
+                        ) { // search for first non-hydrogen atom
+    *out << Verbose(4) << "Current Root candidate is " << Walker->Name << "." << endl;
+    Walker = Walker->next;
+  }
+  if (Walker != end)
+    RootStack->Push(Walker);
+  else
+    *out << Verbose(0) << "ERROR: Could not find an appropriate Root atom!" << endl;
+  *out << Verbose(3) << "Root " << Walker->Name << " is on AtomStack, beginning loop through all vertices ..." << endl;
+
+  ///// OUTER LOOP ////////////
+  while (!RootStack->IsEmpty()) {
+  	// get new root vertex from atom stack
+  	Root = RootStack->PopFirst();
+    ShortestPathList[Root->nr] = 0;
+    if (Labels[Root->nr] == -1)
+      Labels[Root->nr] = RunningIndex++; // prevent it from getting again on AtomStack
+    PredecessorList[Root->nr] = Root;
+    TouchedStack->Push(Root);
+    *out << Verbose(0) << "Root for this loop is: " << Root->Name << ".\n";
+
+		// clear snake stack
+	  SnakeStack->ClearStack();
+    //SnakeStack->TestImplementation(out, start->next);    
+
+    ///// INNER LOOP ////////////
+    // Problems:
+    // - what about cyclic bonds?
+    Walker = Root;
+  	do {
+      *out << Verbose(1) << "Current Walker is: " << Walker->Name;
+      // initial setting of the new Walker: label, color, shortest path and put on stacks
+  		if (Labels[Walker->nr] == -1)	{	// give atom a unique, monotonely increasing number
+  			Labels[Walker->nr] = RunningIndex++;
+        RootStack->Push(Walker);
+      }
+      *out << ", has label " << Labels[Walker->nr];
+  		if ((ColorVertexList[Walker->nr] == white) || ((Binder != NULL) && (ColorEdgeList[Binder->nr] == white))) {	// color it if newly discovered and push on stacks (and if within reach!)
+        if ((Binder != NULL) && (ColorEdgeList[Binder->nr] == white)) {
+          // Binder ought to be set still from last neighbour search
+          *out << ", coloring bond " << *Binder << " black";
+          ColorEdgeList[Binder->nr] = black; // mark this bond as used
+        }
+        if (ShortestPathList[Walker->nr] == -1) {
+          ShortestPathList[Walker->nr] = ShortestPathList[PredecessorList[Walker->nr]->nr]+1; 
+          TouchedStack->Push(Walker); // mark every atom for lists cleanup later, whose shortest path has been changed
+        }
+        if ((ShortestPathList[Walker->nr] < Order) && (ColorVertexList[Walker->nr] != darkgray)) {  // if not already on snake stack
+          SnakeStack->Push(Walker);
+          ColorVertexList[Walker->nr] = darkgray; // mark as dark gray of on snake stack
+        }
+  		}
+      *out << ", SP of " << ShortestPathList[Walker->nr]  << " and its color is " << GetColor(ColorVertexList[Walker->nr]) << "." << endl;
+
+      // then check the stack for a newly stumbled upon fragment
+  		if (SnakeStack->ItemCount() == Order) { // is stack full?
+        // store the fragment if it is one and get a removal candidate
+        Removal = StoreFragmentFromStack(out, Root, Walker, Leaflet, SnakeStack, ShortestPathList, SonList, Labels, &FragmentCounter, configuration);
+        // remove the candidate if one was found
+        if (Removal != NULL) {
+          *out << Verbose(2) << "Removing item " << Removal->Name << " with SP of " << ShortestPathList[Removal->nr] << " from snake stack." << endl;
+          SnakeStack->RemoveItem(Removal);
+          ColorVertexList[Removal->nr] = lightgray; // return back to not on snake stack but explored marking
+          if (Walker == Removal) { // if the current atom is to be removed, we also have to take a step back
+            Walker = PredecessorList[Removal->nr];
+            *out << Verbose(2) << "Stepping back to " << Walker->Name << "." << endl;
+          }
+        }
+  		} else
+        Removal = NULL;
+
+      // finally, look for a white neighbour as the next Walker
+      Binder = NULL;
+      if ((Removal == NULL) || (Walker != PredecessorList[Removal->nr])) {  // don't look, if a new walker has been set above
+        *out << Verbose(2) << "Snake has currently " << SnakeStack->ItemCount() << " item(s)." << endl;
+  			OtherAtom = NULL; // this is actually not needed, every atom has at least one neighbour
+        if (ShortestPathList[Walker->nr] < Order) {
+    			for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {
+            Binder = ListOfBondsPerAtom[Walker->nr][i];
+            *out << Verbose(2) << "Current bond is " << *Binder << ": ";
+    				OtherAtom = Binder->GetOtherAtom(Walker);
+            if ((Labels[OtherAtom->nr] != -1) && (Labels[OtherAtom->nr] < Labels[Root->nr])) { // we don't step up to labels bigger than us
+              *out << "Label " << Labels[OtherAtom->nr] << " is smaller than Root's " << Labels[Root->nr] << "." << endl; 
+              //ColorVertexList[OtherAtom->nr] = lightgray;    // mark as explored
+            } else { // otherwise check its colour and element
+      				if (
+#ifdef ADDHYDROGEN
+              (OtherAtom->type->Z != 1) && 
+#endif
+                    (ColorEdgeList[Binder->nr] == white)) {  // skip hydrogen, look for unexplored vertices
+                *out << "Moving along " << GetColor(ColorEdgeList[Binder->nr]) << " bond " << Binder << " to " << ((ColorVertexList[OtherAtom->nr] == white) ? "unexplored" : "explored") << " item: " << OtherAtom->Name << "." << endl;
+                // i find it currently rather sensible to always set the predecessor in order to find one's way back
+                //if (PredecessorList[OtherAtom->nr] == NULL) {
+                PredecessorList[OtherAtom->nr] = Walker;
+                *out << Verbose(3) << "Setting Predecessor of " << OtherAtom->Name << " to " << PredecessorList[OtherAtom->nr]->Name << "." << endl;
+                //} else {
+                //  *out << Verbose(3) << "Predecessor of " << OtherAtom->Name << " is " << PredecessorList[OtherAtom->nr]->Name << "." << endl;
+                //} 
+                Walker = OtherAtom;
+                break;
+              } else {
+                if (OtherAtom->type->Z == 1) 
+                  *out << "Links to a hydrogen atom." << endl;
+                else                 
+                  *out << "Bond has not white but " << GetColor(ColorEdgeList[Binder->nr]) << " color." << endl;
+              }
+            }
+    			}
+        } else {  // means we have stepped beyond the horizon: Return!
+          Walker = PredecessorList[Walker->nr];
+          OtherAtom = Walker;
+          *out << Verbose(3) << "We have gone too far, stepping back to " << Walker->Name << "." << endl;
+        }
+  			if (Walker != OtherAtom) {	// if no white neighbours anymore, color it black 
+          *out << Verbose(2) << "Coloring " << Walker->Name << " black." << endl;
+  				ColorVertexList[Walker->nr] = black;
+  				Walker = PredecessorList[Walker->nr];
+  			}
+      }
+  	} while ((Walker != Root) || (ColorVertexList[Root->nr] != black));
+    *out << Verbose(2) << "Inner Looping is finished." << endl;    
+
+    // if we reset all AtomCount atoms, we have again technically O(N^2) ...
+    *out << Verbose(2) << "Resetting lists." << endl;
+    Walker = NULL;
+    Binder = NULL;
+    while (!TouchedStack->IsEmpty()) {
+      Walker = TouchedStack->PopLast();
+      *out << Verbose(3) << "Re-initialising entries of " << *Walker << "." << endl;
+      for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++)
+        ColorEdgeList[ListOfBondsPerAtom[Walker->nr][i]->nr] = white;
+      PredecessorList[Walker->nr] = NULL;
+      ColorVertexList[Walker->nr] = white;
+      ShortestPathList[Walker->nr] = -1;
+    }
+  }
+  *out << Verbose(1) << "Outer Looping over all vertices is done." << endl; 
+
+  // copy together
+  *out << Verbose(1) << "Copying all fragments into MoleculeList structure." << endl; 
+  FragmentList = new MoleculeListClass(FragmentCounter, AtomCount);
+  RunningIndex = 0;
+  while ((Leaflet != NULL) && (RunningIndex < FragmentCounter))  {
+    FragmentList->ListOfMolecules[RunningIndex++] = Leaflet->Leaf;
+    Leaflet->Leaf = NULL; // prevent molecule from being removed
+    TempLeaf = Leaflet;
+    Leaflet = Leaflet->previous;
+    delete(TempLeaf);
+  };
+
+  // free memory and exit
+  Free((void **)&PredecessorList, "molecule::CreateListOfUniqueFragmentsOfOrder: **PredecessorList");
+  Free((void **)&ShortestPathList, "molecule::CreateListOfUniqueFragmentsOfOrder: *ShortestPathList");
+  Free((void **)&Labels, "molecule::CreateListOfUniqueFragmentsOfOrder: *Labels");
+  Free((void **)&ColorVertexList, "molecule::CreateListOfUniqueFragmentsOfOrder: *ColorList");
+  delete(RootStack);
+  delete(TouchedStack);
+  delete(SnakeStack);
+
+  *out << Verbose(1) << "End of CreateListOfUniqueFragmentsOfOrder." << endl;
+  return FragmentList;
+};
+*/
+
+/** Structure containing all values in power set combination generation.
+ */
+struct UniqueFragments {
+  config *configuration;
+  atom *Root;
+  Graph *Leaflet;
+  KeySet *FragmentSet;
+  int ANOVAOrder;
+  int FragmentCounter;
+  int CurrentIndex;
+  int *Labels;
+  int *ShortestPathList;
+  bool **UsedList;
+  bond **BondsPerSPList;
+  double TEFactor;
+  int *BondsPerSPCount;
+};
+
+/** From a given set of Bond sorted by Shortest Path distance, create all possible fragments of size \a SetDimension.
+ * This basically involves recursion to create all power set combinations.
+ * \param *out output stream for debugging
+ * \param FragmentSearch UniqueFragments structure with all values needed
+ * \param RootDistance current shortest path level, whose set of edges is represented by **BondsSet
+ * \param SetDimension Number of possible bonds on this level (i.e. size of the array BondsSet[])
+ * \param SubOrder remaining number of allowed vertices to add
+ */
+void molecule::SPFragmentGenerator(ofstream *out, struct UniqueFragments *FragmentSearch, int RootDistance, bond **BondsSet, int SetDimension, int SubOrder)
+{
+  atom *OtherWalker = NULL;
+  int verbosity = 0; //FragmentSearch->ANOVAOrder-SubOrder;
+  int NumCombinations;
+  bool bit;
+  int bits, TouchedIndex, SubSetDimension, SP;
+  int Removal;
+  int *TouchedList = (int *) Malloc(sizeof(int)*(SubOrder+1), "molecule::SPFragmentGenerator: *TouchedList");
+  bond *Binder = NULL;
+  bond **BondsList = NULL;
+
+  NumCombinations = 1 << SetDimension;
+  
+  // Hier muessen von 1 bis NumberOfBondsPerAtom[Walker->nr] alle Kombinationen
+  // von Endstuecken (aus den Bonds) hinzugefÃŒgt werden und fÃŒr verbleibende ANOVAOrder
+  // rekursiv GraphCrawler in der nÃ€chsten Ebene aufgerufen werden
+  
+  *out << Verbose(1+verbosity) << "Begin of SPFragmentGenerator." << endl;
+  *out << Verbose(1+verbosity) << "We are " << RootDistance << " away from Root, which is " << *FragmentSearch->Root << ", SubOrder is " << SubOrder << ", SetDimension is " << SetDimension << " and this means " <<  NumCombinations-1 << " combination(s)." << endl;
+
+  // initialised touched list (stores added atoms on this level) 
+  *out << Verbose(1+verbosity) << "Clearing touched list." << endl;
+  for (TouchedIndex=0;TouchedIndex<=SubOrder;TouchedIndex++)  // empty touched list
+    TouchedList[TouchedIndex] = -1;
+  TouchedIndex = 0;
+  
+  // create every possible combination of the endpieces
+  *out << Verbose(1+verbosity) << "Going through all combinations of the power set." << endl;
+  for (int i=1;i<NumCombinations;i++) {  // sweep through all power set combinations (skip empty set!)
+    // count the set bit of i
+    bits = 0;
+    for (int j=0;j<SetDimension;j++)
+      bits += (i & (1 << j)) >> j;
+      
+    *out << Verbose(1+verbosity) << "Current set is " << Binary(i | (1 << SetDimension)) << ", number of bits is " << bits << "." << endl;
+    if (bits <= SubOrder) { // if not greater than additional atoms allowed on stack, continue
+      // --1-- add this set of the power set of bond partners to the snake stack
+      for (int j=0;j<SetDimension;j++) {  // pull out every bit by shifting
+        bit = ((i & (1 << j)) != 0);  // mask the bit for the j-th bond
+        if (bit) {  // if bit is set, we add this bond partner
+        	OtherWalker = BondsSet[j]->rightatom;	// rightatom is always the one more distant, i.e. the one to add 
+          //*out << Verbose(1+verbosity) << "Current Bond is " << ListOfBondsPerAtom[Walker->nr][i] << ", checking on " << *OtherWalker << "." << endl;
+          //if ((!FragmentSearch->UsedList[OtherWalker->nr][i]) && (FragmentSearch->Labels[OtherWalker->nr] > FragmentSearch->Labels[FragmentSearch->Root->nr])) { 
+            //*out << Verbose(2+verbosity) << "Not used so far, label " << FragmentSearch->Labels[OtherWalker->nr] << " is bigger than Root's " << FragmentSearch->Labels[FragmentSearch->Root->nr] << "." << endl;
+          *out << Verbose(2+verbosity) << "Adding " << *OtherWalker << "." << endl;
+          TouchedList[TouchedIndex++] = OtherWalker->nr;  // note as added
+          FragmentSearch->FragmentSet->insert( FragmentSearch->FragmentSet->end(), OtherWalker->nr);
+            //FragmentSearch->UsedList[OtherWalker->nr][i] = true;
+          //}
+        } else {
+          *out << Verbose(2+verbosity) << "Not adding." << endl;
+        }
+      }
+      
+      if (bits < SubOrder) {
+        *out << Verbose(1+verbosity) << "There's still some space left on stack: " << (SubOrder - bits) << "." << endl;
+        // --2-- look at all added end pieces of this combination, construct bond subsets and sweep through a power set of these by recursion
+        SP = RootDistance+1;	// this is the next level
+        // first count the members in the subset
+        SubSetDimension = 0;
+        Binder = FragmentSearch->BondsPerSPList[2*SP];		// start node for this level
+        while (Binder->next != FragmentSearch->BondsPerSPList[2*SP+1]) {		// compare to end node of this level
+          Binder = Binder->next;
+          for (int k=0;k<TouchedIndex;k++) {
+            if (Binder->Contains(TouchedList[k]))   // if we added this very endpiece
+              SubSetDimension++;
+          }
+        }
+        // then allocate and fill the list
+        BondsList = (bond **) Malloc(sizeof(bond *)*SubSetDimension, "molecule::SPFragmentGenerator: **BondsList");
+        SubSetDimension = 0;
+        Binder = FragmentSearch->BondsPerSPList[2*SP];
+        while (Binder->next != FragmentSearch->BondsPerSPList[2*SP+1]) {
+          Binder = Binder->next;
+          for (int k=0;k<TouchedIndex;k++) {
+            if (Binder->leftatom->nr == TouchedList[k])   // leftatom is always the close one
+              BondsList[SubSetDimension++] = Binder;
+          }
+        }
+        *out << Verbose(2+verbosity) << "Calling subset generator " << SP << " away from root " << *FragmentSearch->Root << " with sub set dimension " << SubSetDimension << "." << endl;
+        SPFragmentGenerator(out, FragmentSearch, SP, BondsList, SubSetDimension, SubOrder-bits);  
+        Free((void **)&BondsList, "molecule::SPFragmentGenerator: **BondsList");
+      } else {
+        // --2-- otherwise store the complete fragment
+        *out << Verbose(1+verbosity) << "Enough items on stack for a fragment!" << endl;
+        // store fragment as a KeySet
+        *out << Verbose(2) << "Found a new fragment[" << FragmentSearch->FragmentCounter << "], indices are: ";
+        for(KeySet::iterator runner = FragmentSearch->FragmentSet->begin(); runner != FragmentSearch->FragmentSet->end(); runner++) {
+          *out << (*runner)+1 << " "; 
+        }
+        InsertFragmentIntoGraph(out, FragmentSearch);
+        Removal = LookForRemovalCandidate(out, FragmentSearch->FragmentSet, FragmentSearch->ShortestPathList);
+        //Removal = StoreFragmentFromStack(out, FragmentSearch->Root, FragmentSearch->Leaflet, FragmentSearch->FragmentStack, FragmentSearch->ShortestPathList,FragmentSearch->Labels, &FragmentSearch->FragmentCounter, FragmentSearch->configuration);
+      }
+      
+      // --3-- remove all added items in this level from snake stack
+      *out << Verbose(1+verbosity) << "Removing all items that were added on this SP level " << RootDistance << "." << endl;
+      for(int j=0;j<TouchedIndex;j++) {
+        Removal = TouchedList[j];
+        *out << Verbose(2+verbosity) << "Removing item nr. " << Removal+1 << " from snake stack." << endl;
+        FragmentSearch->FragmentSet->erase(Removal);
+        TouchedList[j] = -1;
+      }
+      TouchedIndex = 0; // set Index to 0 for list of atoms added on this level
+    } else {
+      *out << Verbose(2+verbosity) << "More atoms to add for this set (" << bits << ") than space left on stack " << SubOrder << ", skipping this set." << endl;
+    }
+  }
+  Free((void **)&TouchedList, "molecule::SPFragmentGenerator: *TouchedList");  
+  *out << Verbose(1+verbosity) << "End of SPFragmentGenerator " << RootDistance << " away from Root " << *FragmentSearch->Root << " and SubOrder is " << SubOrder << "." << endl;
+};
+
+/** Creates a list of all unique fragments of certain vertex size from a given graph \a Fragment in the context of \a this molecule.
+ * Note that we may use the fact that the atoms are SP-ordered on the atomstack. I.e. when popping always the last, we first get all
+ * with SP of 2, then those with SP of 3, then those with SP of 4 and so on.
+ * \param *out output stream for debugging
+ * \param Order number of vertices
+ * \param *ListOfGraph Graph structure to insert found fragments into
+ * \param Fragment Restricted vertex set to use in context of molecule
+ * \param TEFactor TEFactor to store in graphlist in the end
+ * \param *configuration configuration needed for IsAngstroem
+ * \return number of inserted fragments
+ * \note ShortestPathList in FragmentSearch structure is probably due to NumberOfAtomsSPLevel and SP not needed anymore
+ */
+int molecule::CreateListOfUniqueFragmentsOfOrder(ofstream *out, int Order, Graph *ListOfGraph, KeySet Fragment, double TEFactor, config *configuration) 
+{
+  int SP, UniqueIndex, RootKeyNr, AtomKeyNr;
+  int *NumberOfAtomsSPLevel = (int *) Malloc(sizeof(int)*Order, "molecule::CreateListOfUniqueFragmentsOfOrder: *SPLevelCount");
+  atom *Walker = NULL, *OtherWalker = NULL;
+  bond *Binder = NULL;
+  bond **BondsList = NULL;
+  KeyStack RootStack;
+  KeyStack AtomStack;
+  atom **PredecessorList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::CreateListOfUniqueFragmentsOfOrder: **PredecessorList");
+  KeySet::iterator runner;
+
+  // initialise the fragments structure
+  struct UniqueFragments FragmentSearch;
+  FragmentSearch.BondsPerSPList = (bond **) Malloc(sizeof(bond *)*Order*2, "molecule::CreateListOfUniqueFragmentsOfOrder: ***BondsPerSPList");
+  FragmentSearch.BondsPerSPCount = (int *) Malloc(sizeof(int)*Order, "molecule::CreateListOfUniqueFragmentsOfOrder: *BondsPerSPCount");
+  FragmentSearch.ShortestPathList = (int *) Malloc(sizeof(int)*AtomCount, "molecule::CreateListOfUniqueFragmentsOfOrder: *ShortestPathList");
+  FragmentSearch.Labels = (int *) Malloc(sizeof(int)*AtomCount, "molecule::CreateListOfUniqueFragmentsOfOrder: *Labels");
+  FragmentSearch.FragmentCounter = 0;
+  FragmentSearch.FragmentSet = new KeySet;
+  FragmentSearch.configuration = configuration;
+  FragmentSearch.TEFactor = TEFactor;
+  FragmentSearch.Leaflet = ListOfGraph;      // set to insertion graph
+  for (int i=0;i<AtomCount;i++) {
+    FragmentSearch.Labels[i] = -1;
+    FragmentSearch.ShortestPathList[i] = -1;
+    PredecessorList[i] = NULL;
+  }
+  for (int i=0;i<Order;i++) {
+    FragmentSearch.BondsPerSPList[2*i] = new bond();    // start node
+    FragmentSearch.BondsPerSPList[2*i+1] = new bond();  // end node
+    FragmentSearch.BondsPerSPList[2*i]->next = FragmentSearch.BondsPerSPList[2*i+1];     // intertwine these two 
+    FragmentSearch.BondsPerSPList[2*i+1]->previous = FragmentSearch.BondsPerSPList[2*i];
+    FragmentSearch.BondsPerSPCount[i] = 0;
+  }  
+  
+  *out << endl;
+  *out << Verbose(0) << "Begin of CreateListOfUniqueFragmentsOfOrder with order " << Order << "." << endl;
+
+  RootStack.clear();  
+  // find first root candidates  
+  runner = Fragment.begin();
+  Walker = NULL;
+  while ((Walker == NULL) && (runner != Fragment.end())) { // search for first non-hydrogen atom
+    Walker = FindAtom((*runner));
+    *out << Verbose(4) << "Current Root candidate is " << Walker->Name << "." << endl;
+#ifdef ADDHYDROGEN
+    if (Walker->type->Z == 1) // skip hydrogen
+      Walker = NULL;
+#endif
+    runner++;
+  }
+  if (Walker != NULL)
+    RootStack.push_back(Walker->nr);
+  else
+    *out << Verbose(0) << "ERROR: Could not find an appropriate Root atom!" << endl;
+  
+  UniqueIndex = 0;
+  while (!RootStack.empty()) {
+    // Get Root and prepare
+    RootKeyNr = RootStack.front();
+    RootStack.pop_front();
+    FragmentSearch.Root = FindAtom(RootKeyNr);
+    if (FragmentSearch.Labels[RootKeyNr] == -1)
+      FragmentSearch.Labels[RootKeyNr] = UniqueIndex++;
+    FragmentSearch.ShortestPathList[RootKeyNr] = 0;
+    // prepare the atom stack counters (number of atoms with certain SP on stack)
+    for (int i=0;i<Order;i++)
+      NumberOfAtomsSPLevel[i] = 0;
+    NumberOfAtomsSPLevel[0] = 1;  // for root
+    SP = -1;
+    *out << endl;
+    *out << Verbose(0) << "Starting BFS analysis with current Root: " << *FragmentSearch.Root << "." << endl;
+    // push as first on atom stack and goooo ...
+    AtomStack.clear();  
+    AtomStack.push_back(RootKeyNr);
+    *out << Verbose(0) << "Cleared AtomStack and pushed root as first item onto it." << endl;
+    // do a BFS search to fill the SP lists and label the found vertices
+    while (!AtomStack.empty()) {
+      // pop next atom
+      AtomKeyNr = AtomStack.front();
+      AtomStack.pop_front();
+      if (SP != -1)
+        NumberOfAtomsSPLevel[SP]--;
+      if ((SP == -1) || (NumberOfAtomsSPLevel[SP] == -1)) {
+      ////if (SP < FragmentSearch.ShortestPathList[AtomKeyNr]) { // bfs has reached new SP level, hence allocate for new list
+        SP++;
+        NumberOfAtomsSPLevel[SP]--; // carry over "-1" to next level
+        ////SP = FragmentSearch.ShortestPathList[AtomKeyNr];
+        *out << Verbose(1) << "New SP level reached: " << SP << ", creating new SP list with 0 item(s)";
+        if (SP > 0)
+          *out << ", old level closed with " << FragmentSearch.BondsPerSPCount[SP-1] << " item(s)." << endl;
+        else
+          *out << "." << endl;
+        FragmentSearch.BondsPerSPCount[SP] = 0;
+      } else {
+        *out << Verbose(1) << "Still " << NumberOfAtomsSPLevel[SP]+1 << " on this SP (" << SP << ") level, currently having " << FragmentSearch.BondsPerSPCount[SP] << " item(s)." << endl;
+      }
+      Walker = FindAtom(AtomKeyNr);
+      *out << Verbose(0) << "Current Walker is: " << *Walker << " with label " << FragmentSearch.Labels[AtomKeyNr] << " and SP of " << SP << "." << endl;
+      // check for new sp level
+      // go through all its bonds
+      *out << Verbose(1) << "Going through all bonds of Walker." << endl;
+      for (int i=0;i<NumberOfBondsPerAtom[AtomKeyNr];i++) {
+        Binder = ListOfBondsPerAtom[AtomKeyNr][i];
+        OtherWalker = Binder->GetOtherAtom(Walker);
+        if ((Fragment.find(OtherWalker->nr) != Fragment.end())
+#ifdef ADDHYDROGEN
+         && (OtherWalker->type->Z != 1)
+#endif
+                                                              ) {  // skip hydrogens and restrict to fragment
+          *out << Verbose(2) << "Current partner is " << *OtherWalker << " in bond " << *Binder << "." << endl;
+          // set the label if not set (and push on root stack as well)
+          if (FragmentSearch.Labels[OtherWalker->nr] == -1) {
+            RootStack.push_back(OtherWalker->nr);
+            FragmentSearch.Labels[OtherWalker->nr] = UniqueIndex++;
+            *out << Verbose(3) << "Set label to " << FragmentSearch.Labels[OtherWalker->nr] << "." << endl;
+          } else {
+            *out << Verbose(3) << "Label is already " << FragmentSearch.Labels[OtherWalker->nr] << "." << endl;
+          }
+          if ((OtherWalker != PredecessorList[AtomKeyNr]) && (FragmentSearch.Labels[OtherWalker->nr] > FragmentSearch.Labels[RootKeyNr])) { // only pass through those with label bigger than Root's
+            // set shortest path if not set or longer
+            //if ((FragmentSearch.ShortestPathList[OtherWalker->nr] == -1) || (FragmentSearch.ShortestPathList[OtherWalker->nr] > FragmentSearch.ShortestPathList[AtomKeyNr]))  {
+              FragmentSearch.ShortestPathList[OtherWalker->nr] = SP+1;
+              *out << Verbose(3) << "Set Shortest Path to " << FragmentSearch.ShortestPathList[OtherWalker->nr] << "." << endl;
+            //} else {
+            //  *out << Verbose(3) << "Shortest Path is already " << FragmentSearch.ShortestPathList[OtherWalker->nr] << "." << endl;
+            //}
+            if (FragmentSearch.ShortestPathList[OtherWalker->nr] < Order) { // only pass through those within reach of Order
+              // push for exploration on stack (only if the SP of OtherWalker is longer than of Walker! (otherwise it has been added already!)
+              if (FragmentSearch.ShortestPathList[OtherWalker->nr] > SP) {
+                if (FragmentSearch.ShortestPathList[OtherWalker->nr] < (Order-1)) {
+                  *out << Verbose(3) << "Putting on atom stack for further exploration." << endl;
+                  PredecessorList[OtherWalker->nr] = Walker;    // note down the one further up the exploration tree
+                  AtomStack.push_back(OtherWalker->nr);
+                  NumberOfAtomsSPLevel[FragmentSearch.ShortestPathList[OtherWalker->nr]]++;
+                } else {
+                  *out << Verbose(3) << "Not putting on atom stack, is at end of reach." << 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]);
+                FragmentSearch.BondsPerSPCount[SP]++;
+                *out << Verbose(3) << "Added its bond to SP list, having now " << FragmentSearch.BondsPerSPCount[SP] << " item(s)." << endl;
+              } else {
+                *out << Verbose(3) << "Not putting on atom stack, nor adding bond, as " << *OtherWalker << "'s SP is shorter than Walker's." << endl;
+              }
+            } else {
+              *out << Verbose(3) << "Not continuing, as " << *OtherWalker << " is out of reach of order " << Order << "." << endl;
+            }
+          } else {
+            *out << Verbose(3) << "Not passing on, as label of " << *OtherWalker << " " << FragmentSearch.Labels[OtherWalker->nr] << " is smaller than that of Root " << FragmentSearch.Labels[RootKeyNr] << " or this is my predecessor." << endl;
+          }
+        } else {
+          *out << Verbose(2) << "Is not in the Fragment or skipping hydrogen " << *OtherWalker << "." << endl;
+        }
+      }
+    }
+    // reset predecessor list
+    for(int i=0;i<Order;i++) {
+      Binder = FragmentSearch.BondsPerSPList[2*i];
+      *out << Verbose(1) << "Current SP level is " << i << "." << endl;
+      while (Binder->next != FragmentSearch.BondsPerSPList[2*i+1]) {
+        Binder = Binder->next;
+        PredecessorList[Binder->rightatom->nr] = NULL;  // By construction "OtherAtom" is always Bond::rightatom!
+      } 
+    }
+    *out << endl;
+    *out << Verbose(0) << "Printing all found lists." << endl;
+    // outputting all list for debugging
+    for(int i=0;i<Order;i++) {
+      Binder = FragmentSearch.BondsPerSPList[2*i];
+      *out << Verbose(1) << "Current SP level is " << i << "." << endl;
+      while (Binder->next != FragmentSearch.BondsPerSPList[2*i+1]) {
+        Binder = Binder->next;
+        *out << Verbose(2) << *Binder << endl;
+      } 
+    }
+    
+    // creating fragments with the found edge sets
+    SP = 0;
+    for(int i=0;i<Order;i++) { // sum up all found edges
+      Binder = FragmentSearch.BondsPerSPList[2*i];
+      while (Binder->next != FragmentSearch.BondsPerSPList[2*i+1]) {
+        Binder = Binder->next;
+        SP ++; 
+      }
+    }
+    *out << Verbose(0) << "Total number of edges is " << SP << "." << endl;
+    if (SP >= (Order-1)) {
+      // start with root (push on fragment stack)
+      *out << Verbose(0) << "Starting fragment generation with " << *FragmentSearch.Root << "." << endl;
+      FragmentSearch.FragmentSet->clear();  
+      FragmentSearch.FragmentSet->insert(FragmentSearch.Root->nr);
+      
+      if (FragmentSearch.FragmentSet->size() == (unsigned int) Order) {
+        *out << Verbose(0) << "Enough items on stack already for a fragment!" << endl;
+        // store fragment as a KeySet
+        *out << Verbose(2) << "Found a new fragment[" << FragmentSearch.FragmentCounter << "], indices are: ";
+        for(KeySet::iterator runner = FragmentSearch.FragmentSet->begin(); runner != FragmentSearch.FragmentSet->end(); runner++) {
+          *out << (*runner)+1 << " "; 
+        }
+        *out << endl;
+        InsertFragmentIntoGraph(out, &FragmentSearch);
+        //StoreFragmentFromStack(out, FragmentSearch.Root, FragmentSearch.Leaflet, FragmentSearch.FragmentStack, FragmentSearch.ShortestPathList,FragmentSearch.Labels, &FragmentSearch.FragmentCounter, FragmentSearch.configuration);
+      } else {
+        *out << Verbose(0) << "Preparing subset for this root and calling generator." << endl;
+        // prepare the subset and call the generator
+        BondsList = (bond **) Malloc(sizeof(bond *)*FragmentSearch.BondsPerSPCount[0], "molecule::CreateListOfUniqueFragmentsOfOrder: **BondsList");
+        Binder = FragmentSearch.BondsPerSPList[0];
+        for(int i=0;i<FragmentSearch.BondsPerSPCount[0];i++) {
+          Binder = Binder->next;
+          BondsList[i] = Binder;
+        }
+        SPFragmentGenerator(out, &FragmentSearch, 0, BondsList, FragmentSearch.BondsPerSPCount[0], Order-1);  
+        Free((void **)&BondsList, "molecule::CreateListOfUniqueFragmentsOfOrder: **BondsList");
+      }
+    } else {
+      *out << Verbose(0) << "Not enough total number of edges to build " << Order << "-body fragments." << endl;
+    }
+    
+    // remove root from stack
+    *out << Verbose(0) << "Removing root again from stack." << endl;
+    FragmentSearch.FragmentSet->erase(FragmentSearch.Root->nr);    
+
+    // free'ing the bonds lists
+    *out << Verbose(0) << "Free'ing all found lists. and resetting index lists" << endl;
+    for(int i=0;i<Order;i++) {
+      *out << Verbose(1) << "Current SP level is " << i << ": ";
+      Binder = FragmentSearch.BondsPerSPList[2*i];
+      while (Binder->next != FragmentSearch.BondsPerSPList[2*i+1]) {
+        Binder = Binder->next;
+        FragmentSearch.ShortestPathList[Binder->leftatom->nr] = -1;
+        FragmentSearch.ShortestPathList[Binder->rightatom->nr] = -1;
+      }
+      // delete added bonds
+      cleanup(FragmentSearch.BondsPerSPList[2*i], FragmentSearch.BondsPerSPList[2*i+1]);
+      // also start and end node
+      *out << "cleaned." << endl;
+    }
+  }
+  
+  // free allocated memory
+  Free((void **)&NumberOfAtomsSPLevel, "molecule::CreateListOfUniqueFragmentsOfOrder: *SPLevelCount");
+  Free((void **)&PredecessorList, "molecule::CreateListOfUniqueFragmentsOfOrder: **PredecessorList");
+  for(int i=0;i<Order;i++) { // delete start and end of each list
+    delete(FragmentSearch.BondsPerSPList[2*i]);
+    delete(FragmentSearch.BondsPerSPList[2*i+1]);
+  }
+  Free((void **)&FragmentSearch.BondsPerSPList, "molecule::CreateListOfUniqueFragmentsOfOrder: ***BondsPerSPList");
+  Free((void **)&FragmentSearch.BondsPerSPCount, "molecule::CreateListOfUniqueFragmentsOfOrder: *BondsPerSPCount");
+  Free((void **)&FragmentSearch.ShortestPathList, "molecule::CreateListOfUniqueFragmentsOfOrder: *ShortestPathList");
+  Free((void **)&FragmentSearch.Labels, "molecule::CreateListOfUniqueFragmentsOfOrder: *Labels");
+  delete(FragmentSearch.FragmentSet);
+  
+//  // gather all the leaves together
+//  *out << Verbose(0) << "Copying all fragments into MoleculeList structure." << endl; 
+//  FragmentList = new Graph;
+//  UniqueIndex = 0;
+//  while ((FragmentSearch.Leaflet != NULL) && (UniqueIndex < FragmentSearch.FragmentCounter))  {
+//    FragmentList->insert();
+//    FragmentList->ListOfMolecules[UniqueIndex++] = FragmentSearch.Leaflet->Leaf;
+//    FragmentSearch.Leaflet->Leaf = NULL; // prevent molecule from being removed
+//    TempLeaf = FragmentSearch.Leaflet;
+//    FragmentSearch.Leaflet = FragmentSearch.Leaflet->previous;
+//    delete(TempLeaf);
+//  };
+
+  // return list  
+  *out << Verbose(0) << "End of CreateListOfUniqueFragmentsOfOrder." << endl;
+  return FragmentSearch.FragmentCounter;
+};
+
+/** Corrects the nuclei position if the fragment was created over the cell borders.
+ * Scans all bonds, checks the distance, if greater than typical, we have a candidate for the correction.
+ * We remove the bond whereafter the graph probably separates. Then, we translate the one component periodically
+ * and re-add the bond. Looping on the distance check.
+ * \param *out ofstream for debugging messages
+ */
+void molecule::ScanForPeriodicCorrection(ofstream *out)
+{
+  bond *Binder = NULL;
+  bond *OtherBinder = NULL;
+  atom *Walker = NULL;
+  atom *OtherWalker = NULL;
+  double *matrix = ReturnFullMatrixforSymmetric(cell_size);
+  enum Shading *ColorList = NULL;
+  double tmp;
+  vector TranslationVector;
+  //AtomStackClass *CompStack = NULL;
+  AtomStackClass *AtomStack = new AtomStackClass(AtomCount);
+  bool flag = true;
+
+  *out << Verbose(1) << "Begin of ScanForPeriodicCorrection." << endl;
+
+  ColorList = (enum Shading *) Malloc(sizeof(enum Shading)*AtomCount, "molecule::ScanForPeriodicCorrection: *ColorList");
+  while (flag) {
+    // remove bonds that are beyond bonddistance
+    for(int i=0;i<NDIM;i++)
+      TranslationVector.x[i] = 0.; 
+    // scan all bonds
+    Binder = first;
+    flag = false;
+    while ((!flag) && (Binder->next != last)) {
+      Binder = Binder->next;
+      for (int i=0;i<NDIM;i++) {
+        tmp = fabs(Binder->leftatom->x.x[i] - Binder->rightatom->x.x[i]);
+        //*out << Verbose(3) << "Checking " << i << "th distance of " << *Binder->leftatom << " to " << *Binder->rightatom << ": " << tmp << "." << endl;
+        if (tmp > BondDistance) {
+          OtherBinder = Binder->next; // note down binding partner for later re-insertion
+          unlink(Binder);   // unlink bond
+          *out << Verbose(2) << "Correcting at bond " << *Binder << "." << endl;
+          flag = true;
+          break;
+        }
+      }
+    }
+    if (flag) {
+      // create translation vector from their periodically modified distance
+      for (int i=0;i<NDIM;i++) {
+        tmp = Binder->leftatom->x.x[i] - Binder->rightatom->x.x[i];
+        if (fabs(tmp) > BondDistance)
+          TranslationVector.x[i] = (tmp < 0) ? +1. : -1.;
+      }
+      TranslationVector.MatrixMultiplication(matrix);
+      //*out << "Translation vector is ";
+      //TranslationVector.Output(out);
+      //*out << endl;
+      // apply to all atoms of first component via BFS
+      for (int i=0;i<AtomCount;i++)
+        ColorList[i] = white;
+      AtomStack->Push(Binder->leftatom);
+      while (!AtomStack->IsEmpty()) {
+        Walker = AtomStack->PopFirst();
+        //*out << Verbose (3) << "Current Walker is: " << *Walker << "." << endl;
+        ColorList[Walker->nr] = black;    // mark as explored
+        Walker->x.AddVector(&TranslationVector); // translate
+        for (int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {  // go through all binding partners
+          if (ListOfBondsPerAtom[Walker->nr][i] != Binder) {
+            OtherWalker = ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker);
+            if (ColorList[OtherWalker->nr] == white) {
+              AtomStack->Push(OtherWalker); // push if yet unexplored
+            }
+          }
+        }
+      }
+      // re-add bond    
+      link(Binder, OtherBinder);
+    } else {
+      *out << Verbose(2) << "No corrections for this fragment." << endl;
+    }
+    //delete(CompStack);
+  }
+
+  // free allocated space from ReturnFullMatrixforSymmetric()
+  delete(AtomStack);
+  Free((void **)&ColorList, "molecule::ScanForPeriodicCorrection: *ColorList");
+  Free((void **)&matrix, "molecule::ScanForPeriodicCorrection: *matrix");
+  *out << Verbose(1) << "End of ScanForPeriodicCorrection." << endl;
+};
+
+/** Blows the 6-dimensional \a cell_size array up to a full NDIM by NDIM matrix.
+ * \param *symm 6-dim array of unique symmetric matrix components
+ * \return allocated NDIM*NDIM array with the symmetric matrix
+ */
+double * molecule::ReturnFullMatrixforSymmetric(double *symm)
+{
+  double *matrix = (double *) Malloc(sizeof(double)*NDIM*NDIM, "molecule::ReturnFullMatrixforSymmetric: *matrix");
+  matrix[0] = symm[0];
+  matrix[1] = symm[1];
+  matrix[2] = symm[3];
+  matrix[3] = symm[1];
+  matrix[4] = symm[2];
+  matrix[5] = symm[4];
+  matrix[6] = symm[3];
+  matrix[7] = symm[4];
+  matrix[8] = symm[5];
+  return matrix;
+};
+
+bool KeyCompare::operator() (const KeySet SubgraphA, const KeySet SubgraphB) const
+{
+  //cout << "my check is used." << endl;
+  if (SubgraphA.size() < SubgraphB.size()) {
+    return true;
+  } else {
+    if (SubgraphA.size() > SubgraphB.size()) {
+      return false;
+    } else {
+      KeySet::iterator IteratorA = SubgraphA.begin();
+      KeySet::iterator IteratorB = SubgraphB.begin();
+      while ((IteratorA != SubgraphA.end()) && (IteratorB != SubgraphB.end())) {
+        if ((*IteratorA) <  (*IteratorB))
+          return true;
+        else if ((*IteratorA) > (*IteratorB)) {
+            return false;
+          } // else, go on to next index
+        IteratorA++;
+        IteratorB++;
+      } // end of while loop
+    }// end of check in case of equal sizes 
+  }
+  return false; // if we reach this point, they are equal
+};
+
+//bool operator < (KeySet SubgraphA, KeySet SubgraphB)
+//{
+//  return KeyCompare(SubgraphA, SubgraphB);
+//};
+
+/** Checking whether KeySet is not already present in Graph, if so just adds factor.
+ * \param *out output stream for debugging
+ * \param &set KeySet to insert
+ * \param &graph Graph to insert into
+ * \param *counter pointer to unique fragment count
+ * \param factor energy factor for the fragment
+ */
+inline void InsertFragmentIntoGraph(ofstream *out, struct UniqueFragments *Fragment)
+{
+  GraphTestPair testGraphInsert;
+
+  testGraphInsert = Fragment->Leaflet->insert(GraphPair (*Fragment->FragmentSet,pair<int,double>(Fragment->FragmentCounter,Fragment->TEFactor)));  // store fragment number and current factor
+  if (testGraphInsert.second) {
+    *out << Verbose(2) << "KeySet " << Fragment->FragmentCounter << " successfully inserted." << endl;
+    Fragment->FragmentCounter++;
+  } else {
+    *out << Verbose(2) << "KeySet " << Fragment->FragmentCounter << " failed to insert, present fragment is " << ((*(testGraphInsert.first)).second).first << endl;
+    ((*(testGraphInsert.first)).second).second += Fragment->TEFactor;
+    *out << Verbose(2) << "New factor is " << ((*(testGraphInsert.first)).second).second << "." << endl;
+  }
+};
+//void inline InsertIntoGraph(ofstream *out, KeyStack &stack, Graph &graph, int *counter, double factor)
+//{
+//  // copy stack contents to set and call overloaded function again
+//  KeySet set;
+//  for(KeyStack::iterator runner = stack.begin(); runner != stack.begin(); runner++)
+//    set.insert((*runner));
+//  InsertIntoGraph(out, set, graph, counter, factor);
+//};
+
+/** Inserts each KeySet in \a graph2 into \a graph1.
+ * \param *out output stream for debugging
+ * \param graph1 first (dest) graph
+ * \param graph2 second (source) graph
+ */
+inline void InsertGraphIntoGraph(ofstream *out, Graph &graph1, Graph &graph2, int *counter)
+{
+  GraphTestPair testGraphInsert;
+
+  for(Graph::iterator runner = graph2.begin(); runner != graph2.end(); runner++) {
+    testGraphInsert = graph1.insert(GraphPair ((*runner).first,pair<int,double>((*counter)++,((*runner).second).second)));  // store fragment number and current factor
+    if (testGraphInsert.second) {
+      *out << Verbose(2) << "KeySet " << (*counter)-1 << " successfully inserted." << endl;
+    } else {
+      *out << Verbose(2) << "KeySet " << (*counter)-1 << " failed to insert, present fragment is " << ((*(testGraphInsert.first)).second).first << endl;
+      ((*(testGraphInsert.first)).second).second += (*runner).second.second;
+      *out << Verbose(2) << "New factor is " << (*(testGraphInsert.first)).second.second << "." << endl;
+    }
+  }
+};
+
+
+/** Creates truncated BOSSANOVA expansion up to order \a k.
+ * \param *out output stream for debugging
+ * \param ANOVAOrder ANOVA expansion is truncated above this order
+ * \param *configuration configuration for writing config files for each fragment
+ * \return pointer to MoleculeListClass with all the fragments or NULL if something went wrong.
+ */
+MoleculeListClass * molecule::FragmentBOSSANOVA(ofstream *out, int ANOVAOrder, config *configuration)
+{
+  Graph *FragmentList = NULL, ***FragmentLowerOrdersList = NULL;
+  MoleculeListClass *FragmentMoleculeList = NULL;
+  int Order, NumLevels, NumMolecules, TotalNumMolecules = 0, *NumMoleculesOfOrder = NULL;
+  int counter = 0;
+  
+  *out << 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)
+  // with all needed lower orders that are subtracted, the other dimension is the BondOrder (i.e. from 1 to 5)
+  NumMoleculesOfOrder = (int *) Malloc(sizeof(int)*ANOVAOrder, "molecule::FragmentBOSSANOVA: *NumMoleculesOfOrder");
+  FragmentLowerOrdersList = (Graph ***) Malloc(sizeof(Graph **)*ANOVAOrder, "molecule::FragmentBOSSANOVA: ***FragmentLowerOrdersList");
+
+  // Construct the complete KeySet
+  atom *Walker = start;
+  KeySet CompleteMolecule;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    CompleteMolecule.insert(Walker->nr);
+  } 
+
+  for (int BondOrder=1;BondOrder<=ANOVAOrder;BondOrder++) {
+    // this can easily be seen: if Order is 5, then the number of levels for each lower order is the total sum of the number of levels above, as
+    // each has to be split up. E.g. for the second level we have one from 5th, one from 4th, two from 3th (which in turn is one from 5th, one from 4th),
+    // hence we have overall four 2th order levels for splitting. This also allows for putting all into a single array (FragmentLowerOrdersList[])
+    // with the order along the cells as this: 5433222211111111 for BondOrder 5 needing 16=pow(2,5-1) cells (only we use bit-shifting which is faster)
+    NumLevels = 1 << (BondOrder-1); // (int)pow(2,BondOrder-1);
+    *out << Verbose(0) << "BondOrder is (" << BondOrder << "/" << ANOVAOrder << ") and NumLevels is " << NumLevels << "." << endl;
+  
+    // allocate memory for all lower level orders in this 1D-array of ptrs
+    FragmentLowerOrdersList[BondOrder-1] = (Graph **) Malloc(sizeof(Graph *)*NumLevels, "molecule::FragmentBOSSANOVA: **FragmentLowerOrdersList[]");
+  
+    // create top order where nothing is reduced
+    *out << Verbose(0) << "==============================================================================================================" << endl;
+    *out << Verbose(0) << "Creating list of unique fragments of Bond Order " << BondOrder << " itself." << endl;
+    // Create list of Graphs of current Bond Order (i.e. F_{ij})
+    FragmentLowerOrdersList[BondOrder-1][0] =  new Graph;
+    NumMoleculesOfOrder[BondOrder-1] = CreateListOfUniqueFragmentsOfOrder(out, BondOrder, FragmentLowerOrdersList[BondOrder-1][0], CompleteMolecule, 1., configuration);
+    *out << Verbose(1) << "Number of resulting molecules is: " << NumMoleculesOfOrder[BondOrder-1] << "." << endl;
+    NumMolecules = 0;
+    
+    // create lower order fragments
+    *out << Verbose(0) << "Creating list of unique fragments of lower Bond Order terms to be subtracted." << endl;
+    Order = BondOrder;
+    for (int source=0;source<(NumLevels >> 1);source++) { // 1-terms don't need any more splitting, that's why only half is gone through (shift again)
+
+      // step down to next order at (virtual) boundary of powers of 2 in array
+      while (source >= (1 << (BondOrder-Order))) // (int)pow(2,BondOrder-Order))    
+        Order--;
+      *out << Verbose(0) << "Current Order is: " << Order << "." << endl;
+      for (int SubOrder=Order;SubOrder>1;SubOrder--) {
+        int dest = source + (1 << (BondOrder-SubOrder));
+        *out << Verbose(0) << "--------------------------------------------------------------------------------------------------------------" << endl;
+        *out << Verbose(0) << "Current SubOrder is: " << SubOrder-1 << " with source " << source << " to destination " << dest << "." << endl;
+  
+        // every molecule is split into a list of again (Order - 1) molecules, while counting all molecules
+        //*out << Verbose(1) << "Splitting the " << (*FragmentLowerOrdersList[BondOrder-1][source]).size() << " molecules of the " << source << "th cell in the array." << endl;
+        //NumMolecules = 0;
+        FragmentLowerOrdersList[BondOrder-1][dest] = new Graph;
+        for(Graph::iterator runner = (*FragmentLowerOrdersList[BondOrder-1][source]).begin();runner != (*FragmentLowerOrdersList[BondOrder-1][source]).end(); runner++) {
+          NumMolecules += CreateListOfUniqueFragmentsOfOrder(out,SubOrder-1, FragmentLowerOrdersList[BondOrder-1][dest], (*runner).first, -(*runner).second.second, configuration);
+        }
+        *out << Verbose(1) << "Number of resulting molecules is: " << NumMolecules << "." << endl;
+      }
+    }
+    // now, we have completely filled each cell of FragmentLowerOrdersList[] for the current BondOrder
+    //NumMoleculesOfOrder[BondOrder-1] = NumMolecules;
+    TotalNumMolecules += NumMoleculesOfOrder[BondOrder-1];
+    *out << Verbose(1) << "Number of resulting molecules for Order " << BondOrder << " is: " << NumMoleculesOfOrder[BondOrder-1] << "." << endl;    
+  }
+  *out << Verbose(1) << "Total number of resulting molecules is: " << TotalNumMolecules << "." << endl;
+  // now, FragmentLowerOrdersList is complete, it looks - for BondOrder 5 - as this (number is the ANOVA Order of the terms therein) 
+  // 5433222211111111
+  // 43221111
+  // 3211
+  // 21
+  // 1
+  // Subsequently, we combine same orders into a single list (FragmentByOrderList) and reduce these by order
+
+  *out << Verbose(0) << "Combining the lists of all orders per order and finally into a single one." << endl;
+  FragmentList = new Graph;
+  for (int BondOrder=1;BondOrder<=ANOVAOrder;BondOrder++) {
+    NumLevels = 1 << (BondOrder-1);
+    for(int i=0;i<NumLevels;i++) {
+      InsertGraphIntoGraph(out, *FragmentList, (*FragmentLowerOrdersList[BondOrder-1][i]), &counter);
+      delete(FragmentLowerOrdersList[BondOrder-1][i]);
+    }
+    Free((void **)&FragmentLowerOrdersList[BondOrder-1], "molecule::FragmentBOSSANOVA: **FragmentLowerOrdersList[]");
+  }
+  Free((void **)&FragmentLowerOrdersList, "molecule::FragmentBOSSANOVA: ***FragmentLowerOrdersList");
+  Free((void **)&NumMoleculesOfOrder, "molecule::FragmentBOSSANOVA: *NumMoleculesOfOrder");
+  // allocate memory for the pointer array and transmorph graphs into full molecular fragments
+  FragmentMoleculeList = new MoleculeListClass(TotalNumMolecules, AtomCount);
+  int k=0;
+  for(Graph::iterator runner = FragmentList->begin(); runner != FragmentList->end(); runner++) {
+    KeySet test = (*runner).first;
+    FragmentMoleculeList->ListOfMolecules[k] = StoreFragmentFromKeyset(out, test, configuration);
+    FragmentMoleculeList->TEList[k] = ((*runner).second).second;
+    k++;
+  }
+  
+  *out << Verbose(0) << "End of FragmentBOSSANOVA." << endl;
+  delete(FragmentList); 
+  return FragmentMoleculeList;
+};
+
+/** Fragments a molecule, taking \a BondDegree neighbours into accent.
+ * First of all, we have to split up the molecule into bonds ranging out till \a BondDegree.
+ * These fragments serve in the following as the basis the calculate the bond energy of the bond
+ * they originated from. Thus, they are split up in a left and a right part, each calculated for
+ * the total energy, including the fragment as a whole and then we get: 
+ * E(fragment) - E(left) - E(right) = E(bond)
+ * The splitting up is done via Breadth-First-Search, \sa BreadthFirstSearchAdd().
+ * \param *out output stream for debugging
+ * \param BondOrder up to how many neighbouring bonds a fragment contains
+ * \param *configuration configuration for writing config files for each fragment
+ * \param CutCyclic whether to add cut cyclic bond or to saturate
+ * \return pointer to MoleculeListClass with all the fragments or NULL if something went wrong.
+ */
+MoleculeListClass * molecule::FragmentBottomUp(ofstream *out, int BondOrder, config *configuration, enum CutCyclicBond CutCyclic)
+{
+  int Num;
+  MoleculeListClass *FragmentList =  NULL, **FragmentsList = NULL;
+  bond *Bond = NULL;
+
+  *out << Verbose(0) << "Begin of FragmentBottomUp." << endl; 
+  FragmentsList = (MoleculeListClass **) Malloc(sizeof(MoleculeListClass *)*2, "molecule::FragmentBottomUp: **FragmentsList");
+  *out << Verbose(0) << "Getting Atomic fragments." << endl;
+  FragmentsList[0] = GetAtomicFragments(out, AtomCount, configuration->GetIsAngstroem(), 1., CutCyclic);
+
+  // create the fragments including each one bond of the original molecule and up to \a BondDegree neighbours
+  *out << Verbose(0) << "Getting " << 
+#ifdef ADDHYDROGEN  
+  NoNonBonds 
+#else
+  BondCount
+#endif
+                                        << " Bond fragments." << endl;
+  FragmentList = GetEachBondFragmentOfOrder(out, BondOrder, configuration->GetIsAngstroem(), CutCyclic);
+
+  // check whether there are equal fragments by ReduceToUniqueOnes
+  FragmentList->ReduceToUniqueList(out, &cell_size[0], BondDistance);
+
+	*out << Verbose(0) << "Begin of Separating " << FragmentList->NumberOfMolecules << " Fragments into Bond pieces." << endl;
+	// as we have the list, we have to take each fragment split it relative to its originating
+	// bond into left and right and store these in a new list
+  *out << Verbose(2) << endl << "Allocating MoleculeListClass" << endl; 
+  FragmentsList[1] =  new MoleculeListClass(3*FragmentList->NumberOfMolecules, AtomCount); // for each molecule the whole and its left and right part 
+  *out << Verbose(2) << "Creating TEList." << endl; 
+  // and create TE summation for these bond energy approximations (bond = whole - left - right)
+  for(int i=0;i<FragmentList->NumberOfMolecules;i++) {
+    // make up factors to regain total energy of whole molecule
+    FragmentsList[1]->TEList[3*i] = FragmentList->TEList[i];       // bond energy is 1 * whole 
+    FragmentsList[1]->TEList[3*i+1] = -FragmentList->TEList[i];    // - 1. * left part
+    FragmentsList[1]->TEList[3*i+2] = -FragmentList->TEList[i];    // - 1. * right part
+
+    // shift the pointer on whole molecule to new list in order to avoid that this molecule is deleted on deconstructing FragmentList
+    FragmentsList[1]->ListOfMolecules[3*i] = FragmentList->ListOfMolecules[i]; 
+    *out << Verbose(2) << "shifting whole fragment pointer for fragment " << FragmentList->ListOfMolecules[i] << " -> " <<  FragmentsList[1]->ListOfMolecules[3*i] << "." << endl;
+    // create bond matrix and count bonds
+    *out << Verbose(2) << "Updating bond list for fragment " << i << " [" << FragmentList << "]: " << FragmentList->ListOfMolecules[i] << endl; 
+    // create list of bonds per atom for this fragment (atoms were counted above)
+    FragmentsList[1]->ListOfMolecules[3*i]->CreateListOfBondsPerAtom(out);
+     
+    *out << Verbose(0) << "Getting left & right fragments for fragment " << i << "." << endl;
+    // the bond around which the fragment has been setup is always the first by construction (bond partners are first added atoms)
+    Bond = FragmentsList[1]->ListOfMolecules[3*i]->first->next; // is the bond between atom 0 and another in the middle
+    FragmentsList[1]->ListOfMolecules[3*i]->FragmentMoleculeByBond(out, Bond, &(FragmentsList[1]->ListOfMolecules[3*i+1]), &(FragmentsList[1]->ListOfMolecules[3*i+2]), configuration->GetIsAngstroem(), CutCyclic);
+    if ((FragmentsList[1]->ListOfMolecules[3*i+1] == NULL) || (FragmentsList[1]->ListOfMolecules[3*i+2] == NULL)) {
+      *out << Verbose(2) << "Left and/or Right Fragment is NULL!" << endl;
+    } else {
+      *out << Verbose(3) << "Left Fragment is " <<  FragmentsList[1]->ListOfMolecules[3*i+1] << ": " << endl;
+      FragmentsList[1]->ListOfMolecules[3*i+1]->Output(out);
+      *out << Verbose(3) << "Right Fragment is " <<  FragmentsList[1]->ListOfMolecules[3*i+2] << ": " << endl;
+      FragmentsList[1]->ListOfMolecules[3*i+2]->Output(out);
+      *out << endl;
+    }
+    // remove in old list, so that memory for this molecule is not free'd on final delete of this list
+    FragmentList->ListOfMolecules[i] = NULL;
+  }
+	*out << Verbose(0) << "End of Separating Fragments into Bond pieces." << endl;
+  delete(FragmentList);
+  FragmentList = NULL;
+
+  // combine atomic and bond list
+  FragmentList = new MoleculeListClass(FragmentsList[0]->NumberOfMolecules + FragmentsList[1]->NumberOfMolecules, AtomCount);
+  Num = 0;
+  for(int i=0;i<2;i++) {
+    for(int j=0;j<FragmentsList[i]->NumberOfMolecules;j++) {
+      // transfer molecule
+      FragmentList->ListOfMolecules[Num] = FragmentsList[i]->ListOfMolecules[j];
+      FragmentsList[i]->ListOfMolecules[j] = NULL;
+      // transfer TE factor
+      FragmentList->TEList[Num] = FragmentsList[i]->TEList[j];
+      Num++;
+    }
+    delete(FragmentsList[i]);
+    FragmentsList[i] = NULL;
+  }
+  *out << Verbose(2) << "Memory cleanup and return with filled list." << endl; 
+  Free((void **)&FragmentsList, "molecule::FragmentBottomUp: **FragmentsList");
+
+  // reducing list
+  FragmentList->ReduceToUniqueList(out, &cell_size[0], BondDistance);
+	
+	// write configs for all fragements (are written in FragmentMolecule)
+  // free FragmentList
+  *out << Verbose(0) << "End of FragmentBottomUp." << endl; 
+  return FragmentList;
+};
+
+
+/** Comparision function for GSL heapsort on distances in two molecules.
+ * \param *a
+ * \param *b
+ * \return <0, \a *a less than \a *b, ==0 if equal, >0 \a *a greater than \a *b
+ */
+int CompareDoubles (const void * a, const void * b)
+{
+  if (*(double *)a > *(double *)b)
+    return -1;
+  else if (*(double *)a < *(double *)b)
+    return 1;
+  else
+    return 0;
+};
+
+/** Determines whether two molecules actually contain the same atoms and coordination.
+ * \param *out output stream for debugging
+ * \param *OtherMolecule the molecule to compare this one to
+ * \param threshold upper limit of difference when comparing the coordination.
+ * \return NULL - not equal, otherwise an allocated (molecule::AtomCount) permutation map of the atom numbers (which corresponds to which)
+ */
+int * molecule::IsEqualToWithinThreshold(ofstream *out, molecule *OtherMolecule, double threshold)
+{
+  int flag;
+  double *Distances = NULL, *OtherDistances = NULL;
+  vector CenterOfGravity, OtherCenterOfGravity;
+  size_t *PermMap = NULL, *OtherPermMap = NULL;
+  int *PermutationMap = NULL;
+  atom *Walker = NULL;
+  bool result = true; // status of comparison
+  
+  *out << Verbose(3) << "Begin of IsEqualToWithinThreshold." << endl; 
+  /// first count both their atoms and elements and update lists thereby ...
+  //*out << Verbose(0) << "Counting atoms, updating list" << endl;
+  CountAtoms(out);
+  OtherMolecule->CountAtoms(out);
+  CountElements();
+  OtherMolecule->CountElements();
+
+  /// ... and compare:
+  /// -# AtomCount
+  if (result) {
+    if (AtomCount != OtherMolecule->AtomCount) {
+      *out << Verbose(4) << "AtomCounts don't match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
+      result = false;
+    } else *out << Verbose(4) << "AtomCounts match: " << AtomCount << " == " << OtherMolecule->AtomCount << endl;
+  }
+  /// -# ElementCount
+  if (result) {
+    if (ElementCount != OtherMolecule->ElementCount) {
+      *out << Verbose(4) << "ElementCount don't match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
+      result = false;
+    } else *out << Verbose(4) << "ElementCount match: " << ElementCount << " == " << OtherMolecule->ElementCount << endl;
+  }
+  /// -# ElementsInMolecule
+  if (result) {
+    for (flag=0;flag<MAX_ELEMENTS;flag++) {
+      //*out << Verbose(5) << "Element " <<  flag << ": " << ElementsInMolecule[flag] << " <-> " << OtherMolecule->ElementsInMolecule[flag] << "." << endl;
+      if (ElementsInMolecule[flag] != OtherMolecule->ElementsInMolecule[flag])
+        break;
+    }
+    if (flag < MAX_ELEMENTS) {
+      *out << Verbose(4) << "ElementsInMolecule don't match." << endl;
+      result = false;
+    } else *out << Verbose(4) << "ElementsInMolecule match." << endl;
+  }
+  /// then determine and compare center of gravity for each molecule ...
+  if (result) {
+    *out << Verbose(5) << "Calculating Centers of Gravity" << endl;
+    DetermineCenterOfGravity(CenterOfGravity);
+    OtherMolecule->DetermineCenterOfGravity(OtherCenterOfGravity);
+    *out << Verbose(5) << "Center of Gravity: ";
+    CenterOfGravity.Output(out);
+    *out << endl << Verbose(5) << "Other Center of Gravity: ";
+    OtherCenterOfGravity.Output(out);
+    *out << endl;
+    if (CenterOfGravity.Distance(&OtherCenterOfGravity) > threshold) {
+      *out << Verbose(4) << "Centers of gravity don't match." << endl;
+      result = false;  
+    }
+  }
+  
+  /// ... then make a list with the euclidian distance to this center for each atom of both molecules
+  if (result) {
+    *out << Verbose(5) << "Calculating distances" << endl;
+    Distances = (double *) Malloc(sizeof(double)*AtomCount, "molecule::IsEqualToWithinThreshold: Distances");
+    OtherDistances = (double *) Malloc(sizeof(double)*AtomCount, "molecule::IsEqualToWithinThreshold: OtherDistances");
+    Walker = start;
+    while (Walker->next != end) {
+      Walker = Walker->next;
+    //for (i=0;i<AtomCount;i++) {
+      Distances[Walker->nr] = CenterOfGravity.Distance(&Walker->x);
+    }
+    Walker = OtherMolecule->start;
+    while (Walker->next != OtherMolecule->end) {
+      Walker = Walker->next;
+      OtherDistances[Walker->nr] = OtherCenterOfGravity.Distance(&Walker->x);
+    }
+  
+    /// ... sort each list (using heapsort (o(N log N)) from GSL)
+    *out << Verbose(5) << "Sorting distances" << endl;
+    PermMap = (size_t *) Malloc(sizeof(size_t)*AtomCount, "molecule::IsEqualToWithinThreshold: *PermMap");
+    OtherPermMap = (size_t *) Malloc(sizeof(size_t)*AtomCount, "molecule::IsEqualToWithinThreshold: *OtherPermMap");
+    gsl_heapsort_index (PermMap, Distances, AtomCount, sizeof(double), CompareDoubles);
+    gsl_heapsort_index (OtherPermMap, OtherDistances, AtomCount, sizeof(double), CompareDoubles);
+    PermutationMap = (int *) Malloc(sizeof(int)*AtomCount, "molecule::IsEqualToWithinThreshold: *PermutationMap");
+    *out << Verbose(5) << "Combining Permutation Maps" << endl;
+    for(int i=0;i<AtomCount;i++)
+      PermutationMap[PermMap[i]] = (int) OtherPermMap[i];
+    
+    /// ... and compare them step by step, whether the difference is individiually(!) below \a threshold for all
+    *out << Verbose(4) << "Comparing distances" << endl;
+    flag = 0;
+    for (int i=0;i<AtomCount;i++) {
+      *out << Verbose(5) << "Distances: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " <<  threshold << endl;
+      if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold)
+        flag = 1;
+    }
+    Free((void **)&PermMap, "molecule::IsEqualToWithinThreshold: *PermMap");
+    Free((void **)&OtherPermMap, "molecule::IsEqualToWithinThreshold: *OtherPermMap");
+      
+    /// free memory
+    Free((void **)&Distances, "molecule::IsEqualToWithinThreshold: Distances");
+    Free((void **)&OtherDistances, "molecule::IsEqualToWithinThreshold: OtherDistances");
+    if (flag) { // if not equal
+      Free((void **)&PermutationMap, "molecule::IsEqualToWithinThreshold: *PermutationMap");
+      result = false;
+    }
+  } 
+  /// return pointer to map if all distances were below \a threshold
+  *out << Verbose(3) << "End of IsEqualToWithinThreshold." << endl;
+  if (result) {
+    *out << Verbose(3) << "Result: Equal." << endl;
+    return PermutationMap;
+  } else {
+    *out << Verbose(3) << "Result: Not equal." << endl;
+    return NULL;
+  } 
+};
+
+/** Returns an index map for two father-son-molecules.
+ * The map tells which atom in this molecule corresponds to which one in the other molecul with their fathers.
+ * \param *out output stream for debugging
+ * \param *OtherMolecule corresponding molecule with fathers
+ * \return allocated map of size molecule::AtomCount with map
+ * \todo make this with a good sort O(n), not O(n^2)
+ */
+int * molecule::GetFatherSonAtomicMap(ofstream *out, molecule *OtherMolecule)
+{
+  atom *Walker = NULL, *OtherWalker = NULL;
+  *out << Verbose(3) << "Begin of GetFatherAtomicMap." << endl;
+  int *AtomicMap = (int *) Malloc(sizeof(int)*AtomCount, "molecule::GetAtomicMap: *AtomicMap");  //Calloc
+  for (int i=0;i<AtomCount;i++)
+    AtomicMap[i] = -1;
+  if (OtherMolecule == this) {  // same molecule
+    for (int i=0;i<AtomCount;i++) // no need as -1 means already that there is trivial correspondence
+      AtomicMap[i] = i;
+    *out << Verbose(4) << "Map is trivial." << endl;
+  } else {
+    *out << Verbose(4) << "Map is ";
+    Walker = start;
+    while (Walker->next != end) {
+      Walker = Walker->next;
+      if (Walker->father == NULL) {
+        AtomicMap[Walker->nr] = -2;
+      } else {
+        OtherWalker = OtherMolecule->start;
+        while (OtherWalker->next != OtherMolecule->end) {
+          OtherWalker = OtherWalker->next;
+      //for (int i=0;i<AtomCount;i++) { // search atom
+        //for (int j=0;j<OtherMolecule->AtomCount;j++) {
+          //*out << Verbose(4) << "Comparing father " << Walker->father << " with the other one " << OtherWalker->father << "." << endl;
+          if (Walker->father == OtherWalker)
+            AtomicMap[Walker->nr] = OtherWalker->nr;
+        }
+      }
+      *out << AtomicMap[Walker->nr] << "\t";
+    }
+    *out << endl;
+  }
+  *out << Verbose(3) << "End of GetFatherAtomicMap." << endl;
+  return AtomicMap;
+};
+
Index: molecuilder/src/molecules.hpp
===================================================================
--- molecuilder/src/molecules.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/molecules.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,685 @@
+/** \file molecules.hpp
+ *
+ * Class definitions of atom and molecule, element and periodentafel 
+ */
+
+#ifndef MOLECULES_HPP_
+#define MOLECULES_HPP_
+
+using namespace std;
+
+// GSL headers
+#include <gsl/gsl_multimin.h>
+#include <gsl/gsl_vector.h>
+#include <gsl/gsl_matrix.h>
+#include <gsl/gsl_heapsort.h>
+
+// STL headers
+#include <map>
+#include <set>
+#include <deque>
+
+// system specific headers
+#include <time.h>
+
+
+#include "helpers.hpp"
+
+class atom;
+class AtomStackClass;
+class bond;
+class config;
+class element;
+class molecule;
+class MoleculeListClass;
+class periodentafel;
+class vector;
+class Verbose;
+
+/******************************** Some definitions for easier reading **********************************/
+
+#define KeyStack deque<int>
+#define KeySet set<int>
+#define Graph map<KeySet, pair<int, double>, KeyCompare >
+#define GraphPair pair<KeySet, pair<int, double> >
+#define KeySetTestPair pair<KeySet::iterator, bool>
+#define GraphTestPair pair<Graph::iterator, bool>
+
+struct KeyCompare
+{
+  bool operator() (const KeySet SubgraphA, const KeySet SubgraphB) const;
+};
+//bool operator < (KeySet SubgraphA, KeySet SubgraphB);   //note: this declaration is important, otherwise normal < is used (producing wrong order)
+inline void InsertFragmentIntoGraph(ofstream *out, struct UniqueFragments *Fragment); // Insert a KeySet into a Graph
+inline void InsertGraphIntoGraph(ofstream *out, Graph &graph1, Graph &graph2, int *counter);  // Insert all KeySet's in a Graph into another Graph 
+
+/******************************** Some templates for list management ***********************************/
+
+/** Adds linking of an item to a list.
+ * \param *walker
+ * \return true - adding succeeded, false - error in list
+ */
+template <typename X> void link(X *walker, X *end)
+{
+  X *vorher = end->previous;
+  if (vorher != NULL)
+    vorher->next = walker;
+  end->previous = walker;
+  walker->previous = vorher;
+  walker->next = end;
+};
+
+/** Removes linking of an item in a list.
+ * \param *walker
+ * \return true - removing succeeded, false - given item not found in list
+ */
+template <typename X> void unlink(X *walker)
+{
+  if (walker->next != NULL) 
+    walker->next->previous = walker->previous;
+  if (walker->previous != NULL)
+    walker->previous->next = walker->next;
+};
+
+/** Adds new item before an item \a *end in a list.
+ * \param *pointer   item to be added
+ * \param *end  end of list
+ * \return true - addition succeeded, false - unable to add item to list
+ */
+template <typename X>  bool add(X *pointer, X *end)
+{
+  if (end != NULL) {
+    link(pointer, end);
+  } else {
+    pointer->previous = NULL;
+    pointer->next = NULL; 
+  }
+  return true;
+};
+
+/** Finds item in list
+ * \param *suche  search criteria
+ * \param *start  begin of list
+ * \param *end  end of list
+ * \return X - if found, NULL - if not found
+ */
+template <typename X, typename Y> X * find(Y *suche, X *start, X *end)
+{
+  X *walker = start;
+  while (walker->next != end) { // go through list
+    walker = walker->next; // step onward beforehand
+    if (*walker->sort == *suche) return (walker);
+  }
+  return NULL;
+};
+
+/** Removes an item from the list without check.
+ * \param *walker item to be removed
+ * \return true - removing succeeded, false - given item not found in list
+ */
+template <typename X> void removewithoutcheck(X *walker)
+{
+  if (walker != NULL) {
+    unlink(walker);
+    delete(walker);
+    walker = NULL;
+  }
+};
+
+/** Removes an item from the list, checks if exists.
+ * Checks beforehand if atom is really within molecule list.
+ * \param *pointer   item to be removed
+ * \param *start  begin of list
+ * \param *end  end of list
+ * \return true - removing succeeded, false - given item not found in list
+ */
+template <typename X> bool remove(X *pointer, X *start, X *end)
+{
+  X *walker = find (pointer->sort, start, end);
+/*  while (walker->next != pointer) { // search through list
+    walker = walker->next;
+    if (walker == end) return false;  // item not found in list
+  }*/
+  // atom found, now unlink
+  if (walker != NULL)
+    removewithoutcheck(walker);
+  else
+    return false;
+  return true;
+};
+
+/** Cleans the whole list.
+ * \param *start begin of list
+ * \param *end end of list
+ * \return true - list was cleaned successfully, false - error in list structure
+ */
+template <typename X> bool cleanup(X *start, X *end)
+{
+  X *pointer = start->next;
+  X *walker;
+  while (pointer != end) { // go through list
+    walker = pointer; // mark current
+    pointer = pointer->next; // step onward beforehand
+    // remove walker
+    unlink(walker);
+    delete(walker);
+    walker = NULL;
+  }
+  return true;
+};
+
+/** Returns the first marker in a chain list.
+ * \param *me one arbitrary item in chain list
+ * \return poiner to first marker
+ */
+template <typename X> X *GetFirst(X *me)
+{
+  X *Binder = me;
+  while(Binder->previous != NULL)
+    Binder = Binder->previous;
+  return Binder;
+}; 
+
+/** Returns the last marker in a chain list.
+ * \param *me one arbitrary item in chain list
+ * \return poiner to last marker
+ */
+template <typename X> X *GetLast(X *me)
+{
+  X *Binder = me;
+  while(Binder->next != NULL)
+    Binder = Binder->next;
+  return Binder;
+}; 
+
+/** Frees a two-dimensional array.
+ * \param *ptr pointer to array
+ * \param dim first dim of array
+ */
+template <typename X> void Free2DArray(X **ptr, int dim)
+{
+	int i;
+ 	if (ptr != NULL) {
+ 		for(i=0;i<dim;i++)
+ 			if (ptr[i] != NULL)
+ 				free(ptr[i]);
+ 		free(ptr);
+ 	}
+};
+
+int CompareDoubles (const void * a, const void * b);
+
+/************************************* Class definitions ****************************************/
+
+/** Chemical element.
+ * Class incorporates data for a certain chemical element to be referenced from atom class.
+ */
+class element {
+  public:
+    double mass;    //!< mass in g/mol
+    double CovalentRadius;  //!< covalent radius
+    double VanDerWaalsRadius;  //!< can-der-Waals radius
+    int Z;          //!< atomic number
+    char name[64];  //!< atom name, i.e. "Hydrogren"
+    char symbol[3]; //!< short form of the atom, i.e. "H"
+    char period[8];    //!< period: n quantum number
+    char group[8];    //!< group: l quantum number
+    char block[8];    //!< block: l quantum number
+    element *previous;  //!< previous item in list
+    element *next;  //!< next element in list
+    int *sort;      //!< sorc criteria
+    int No;         //!< number of element set on periodentafel::Output()
+    double Valence;		//!< number of valence electrons for this element
+    int NoValenceOrbitals;  //!< number of valence orbitals, used for determining bond degree in molecule::CreateConnectmatrix()
+    double HBondDistance[NDIM];	//!< distance in Angstrom of this element to hydrogen  (for single, double and triple bonds)
+    double HBondAngle[NDIM];     //!< typical angle for one, two, three bonded hydrogen (in degrees)
+
+  element();
+  ~element();
+
+  //> print element entries to screen
+  bool Output(ofstream *out) const;
+  bool Checkout(ofstream *out, const int No, const int NoOfAtoms) const;
+  
+  private:
+};
+
+/** Periodentafel is a list of all elements sorted by their atomic number.
+ */
+class periodentafel {
+  public:
+    element *start; //!< start of element list
+    element *end;   //!< end of element list
+    char header1[255]; //!< store first header line
+    char header2[255]; //!< store second header line
+  
+  periodentafel();
+  ~periodentafel(); 
+  
+  bool AddElement(element *pointer);
+  bool RemoveElement(element *pointer);
+  bool CleanupPeriodtable();
+  element * FindElement(int Z);
+  element * FindElement(char *shorthand) const;
+  element * AskElement(); 
+  bool Output(ofstream *output) const;
+  bool Checkout(ofstream *output, const int *checkliste) const;
+  bool LoadPeriodentafel();
+  bool StorePeriodentafel() const;
+  
+  private:
+};
+
+// some algebraic matrix stuff
+#define RDET3(a) ((a)[0]*(a)[4]*(a)[8] + (a)[3]*(a)[7]*(a)[2] + (a)[6]*(a)[1]*(a)[5] - (a)[2]*(a)[4]*(a)[6] - (a)[5]*(a)[7]*(a)[0] - (a)[8]*(a)[1]*(a)[3])  //!< hard-coded determinant of a 3x3 matrix
+#define RDET2(a0,a1,a2,a3) ((a0)*(a3)-(a1)*(a2))                      //!< hard-coded determinant of a 2x2 matrix
+
+/** Single vector.
+ * basically, just a x[3] but with helpful functions
+ */
+class vector {   
+  public:
+    double x[NDIM];
+
+  vector();
+  ~vector();
+
+  double Distance(const vector *y) const;
+  double PeriodicDistance(const vector *y, const double *cell_size) const;
+  double ScalarProduct(const vector *y) const;
+  double Projection(const vector *y) const;
+  double Norm() const ;
+  double Angle(vector *y) const;
+
+  void AddVector(const vector *y);
+  void SubtractVector(const vector *y);
+  void CopyVector(const vector *y);
+  void RotateVector(const vector *y, const double alpha);
+  void Zero(); 
+  void Normalize();
+  void Translate(const vector *x);
+  void Mirror(const vector *x);
+  void Scale(double **factor);
+  void Scale(double *factor);
+  void Scale(double factor);
+  void MatrixMultiplication(double *M);
+  void InverseMatrixMultiplication(double *M);
+  void KeepPeriodic(ofstream *out, double *matrix);
+  void LinearCombinationOfVectors(const vector *x1, const vector *x2, const vector *x3, double *factors);
+  
+  bool GetOneNormalVector(const vector *x1);
+  bool MakeNormalVector(const vector *y1);
+  bool MakeNormalVector(const vector *y1, const vector *y2);
+  bool MakeNormalVector(const vector *x1, const vector *x2, const vector *x3);
+  bool SolveSystem(vector *x1, vector *x2, vector *y, double alpha, double beta, double c);
+	bool LSQdistance(vector **vectors, int dim);
+
+  void AskPosition(double *cell_size, bool check);
+  bool Output(ofstream *out) const;
+};
+
+ofstream& operator<<(ofstream& ost, vector& m);
+
+/** Parameter structure for least square minimsation.
+ */
+struct LSQ_params {
+  vector **vectors;
+  int num;
+};
+
+double LSQ(const gsl_vector * x, void * params);
+
+/** Parameter structure for least square minimsation.
+ */
+struct lsq_params {
+  gsl_vector *x;
+  const molecule *mol;
+  element *type;
+};
+
+
+
+/** Single atom.
+ * Class incoporates position, type
+ */
+class atom {
+  public:
+    vector x;    //!< coordinate array of atom, giving position within cell
+    element *type;  //!< pointing to element
+    atom *previous; //!< previous atom in molecule list
+    atom *next;     //!< next atom in molecule list
+    atom *father;   //!< In many-body bond order fragmentations points to originating atom
+    atom *Ancestor; //!< "Father" in Depth-First-Search
+    char *Name;			//!< unique name used during many-body bond-order fragmentation
+    int *sort;      //!< sort criteria
+    int nr;         //!< continuous, unique number
+    int GraphNr;      //!< unique number, given in DepthFirstSearchAnalysis()
+    int *ComponentNr;//!< belongs to this nonseparable components, given in DepthFirstSearchAnalysis() (if more than one, then is SeparationVertex)
+    int LowpointNr; //!< needed in DepthFirstSearchAnalysis() to detect nonseparable components, is the lowest possible number of an atom to reach via tree edges only followed by at most one back edge.
+    bool SeparationVertex; //!< whether this atom separates off subsets of atoms or not, given in DepthFirstSearchAnalysis()
+  
+  atom();
+  ~atom();
+  
+  bool Output(int ElementNo, int AtomNo, ofstream *out) const;
+  bool OutputXYZLine(ofstream *out) const;
+  atom *GetTrueFather();
+  bool Compare(atom &ptr);
+  
+  private:
+};
+
+ostream & operator << (ostream &ost, atom &a);
+
+/* Stack of Atoms.
+ * Is used during DepthFirstSearchAnalysis() to detect nonseparable components.
+ */
+class AtomStackClass {
+  public:
+  AtomStackClass(int dimension);
+  ~AtomStackClass();
+  
+  bool Push(atom *object);
+  atom *PopFirst();
+  atom *PopLast();
+  bool AtomStackClass::RemoveItem(atom *ptr);
+  void ClearStack();
+  bool IsEmpty();
+  bool IsFull();
+	int ItemCount();
+  void Output(ofstream *out) const;
+  void TestImplementation(ofstream *out, atom *test);
+  
+  private:
+    atom **StackList;   //!< the list containing the atom pointers
+    int EntryCount;     //!< number of entries in the stack
+    int CurrentLastEntry;   //!< Current last entry (newest item on stack)
+    int CurrentFirstEntry;   //!< Current first entry (oldest item on stack)
+    int NextFreeField;       //!< Current index of next free field
+};
+
+
+/** Bonds between atoms.
+ * Class incorporates bonds between atoms in a molecule,
+ * used to derive tge fragments in many-body bond order
+ * calculations.
+ */
+class bond {
+  public:
+  	atom *leftatom;		//!< first bond partner
+  	atom *rightatom;	//!< second bond partner
+    bond *previous; //!< previous atom in molecule list
+    bond *next;     //!< next atom in molecule list
+  	int HydrogenBond;	//!< Number of hydrogen atoms in the bond
+  	int BondDegree;		//!< single, double, triple, ... bond
+    int nr;           //!< unique number in a molecule, updated by molecule::CreateAdjacencyList()
+    bool Cyclic;      //!< flag whether bond is part of a cycle or not, given in DepthFirstSearchAnalysis()
+    enum EdgeType Type;//!< whether this is a tree or back edge 
+  	
+  atom * GetOtherAtom(atom *Atom) const;
+  bond * GetFirstBond();
+  bond * GetLastBond();
+  
+  bool MarkUsed(enum Shading color);
+  enum Shading IsUsed();
+  void ResetUsed();
+  bool Contains(const atom *ptr);
+  bool Contains(const int nr);
+  
+  bond();
+  bond(atom *left, atom *right);
+  bond(atom *left, atom *right, int degree);
+  bond(atom *left, atom *right, int degree, int number);
+  ~bond();
+    
+  private: 
+    enum Shading Used;        //!< marker in depth-first search, DepthFirstSearchAnalysis()
+};
+
+ostream & operator << (ostream &ost, bond &b);
+
+class MoleculeLeafClass;
+
+/** The complete molecule.
+ * Class incorporates number of types
+ */
+class molecule {
+  public:
+    double cell_size[6];//!< cell size
+    periodentafel *elemente; //!< periodic table with each element
+    atom *start;        //!< start of atom list
+    atom *end;          //!< end of atom list
+    bond *first;        //!< start of bond list
+    bond *last;         //!< end of bond list
+    bond ***ListOfBondsPerAtom; //!< pointer list for each atom and each bond it has
+    int *NumberOfBondsPerAtom;  //!< Number of Bonds each atom has
+    int AtomCount;					//!< number of atoms, brought up-to-date by CountAtoms()
+    int BondCount;					//!< number of atoms, brought up-to-date by CountBonds()
+    int ElementCount;       //!< how many unique elements are therein
+    int ElementsInMolecule[MAX_ELEMENTS]; //!< list whether element (sorted by atomic number) is alread present or not
+    int NoNonHydrogen;	//!< number of non-hydrogen atoms in molecule
+    int NoNonBonds;     //!< number of non-hydrogen bonds in molecule
+    int NoCyclicBonds;  //!< number of cyclic bonds in molecule, by DepthFirstSearchAnalysis()
+    double BondDistance;  //!< typical bond distance used in CreateAdjacencyList() and furtheron
+  
+  molecule(periodentafel *teil);
+  ~molecule();
+  
+  /// remove atoms from molecule.
+  bool AddAtom(atom *pointer);
+  bool RemoveAtom(atom *pointer);
+  bool CleanupMolecule();
+
+  /// Add/remove atoms to/from molecule.
+  atom * AddCopyAtom(atom *pointer);
+  bool AddXYZFile(string filename);
+  bool AddHydrogenReplacementAtom(ofstream *out, bond *Bond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bond **BondList, int NumBond, bool IsAngstroem);  
+  bond * AddBond(atom *first, atom *second, int degree);
+  bool RemoveBond(bond *pointer);
+  bool RemoveBonds(atom *BondPartner);
+    
+  /// Find atoms.
+  atom * FindAtom(int Nr) const; 
+  atom * AskAtom(char *text);
+
+  /// Count and change present atoms' coordination.
+  void CountAtoms(ofstream *out);
+  void CountElements();
+  void CalculateOrbitals(class config &configuration);
+  void CenterEdge(ofstream *out, vector *max); 
+  void CenterOrigin(ofstream *out, vector *max); 
+  void CenterGravity(ofstream *out, vector *max); 
+  void Translate(const vector *x);
+  void Mirror(const vector *x);
+  void Align(vector *n);
+  void Scale(double **factor);
+  void DetermineCenterOfGravity(vector &CenterOfGravity);
+  void SetBoxDimension(vector *dim);
+  double * ReturnFullMatrixforSymmetric(double *cell_size);
+  void ScanForPeriodicCorrection(ofstream *out);
+
+  bool CheckBounds(const vector *x) const;
+  void GetAlignVector(struct lsq_params * par) const;
+
+  /// Initialising routines in fragmentation  
+  void CreateAdjacencyList(ofstream *out, double bonddistance);
+  void CreateListOfBondsPerAtom(ofstream *out);
+  
+  // Graph analysis
+  MoleculeLeafClass * DepthFirstSearchAnalysis(ofstream *out, bool ReturnStack, int &MinimumRingSize);
+  void CyclicStructureAnalysis(ofstream *out, int &MinimumRingSize);
+  bond * FindNextUnused(atom *vertex);
+  void SetNextComponentNumber(atom *vertex, int nr);
+  void InitComponentNumbers();
+  void OutputComponentNumber(ofstream *out, atom *vertex);
+  void ResetAllBondsToUnused();
+  void ResetAllAtomNumbers();
+  int CountCyclicBonds(ofstream *out);
+  char * GetColor(enum Shading color);
+
+  molecule *CopyMolecule();
+  
+  /// Fragment molecule by two different approaches:
+  void FragmentMolecule(ofstream *out, int BottomUpOrder, int TopDownOrder, enum BondOrderScheme Scheme, config *configuration, enum CutCyclicBond CutCyclic);
+  MoleculeListClass * GetAtomicFragments(ofstream *out, int NumberOfTopAtoms, bool IsAngstroem, double factor, enum CutCyclicBond CutCyclic);
+  void BreadthFirstSearchAdd(ofstream *out, molecule *Mol, atom **&AddedAtomList, bond **&AddedBondList, atom *Root, bond *Bond, int BondOrder, bool IsAngstroem, enum CutCyclicBond CutCyclic);
+  /// -# BottomUp  
+  MoleculeListClass * FragmentBottomUp(ofstream *out, int BondOrder, config *configuration, enum CutCyclicBond CutCyclic);
+  MoleculeListClass * GetEachBondFragmentOfOrder(ofstream *out, int BondOrder, bool IsAngstroem, enum CutCyclicBond CutCyclic);
+  /// -# TopDown
+  void FragmentMoleculeByBond(ofstream *out, bond *Bond, molecule **LeftFragment, molecule **RightFragment, bool IsAngstroem, enum CutCyclicBond CutCyclic);
+  /// -# BOSSANOVA
+	MoleculeListClass * FragmentBOSSANOVA(ofstream *out, int ANOVAOrder, config *configuration);
+	int CreateListOfUniqueFragmentsOfOrder(ofstream *out, int Order, Graph *ListOfGraph, KeySet Fragment, double TEFactor, config *configuration);
+  bool BuildInducedSubgraph(ofstream *out, const molecule *Father);
+  molecule * StoreFragmentFromKeyset(ofstream *&out, KeySet &Leaflet, config *&configuration);
+  void SPFragmentGenerator(ofstream *out, struct UniqueFragments *FragmentSearch, int RootDistance, bond **BondsSet, int SetDimension, int SubOrder);
+  int LookForRemovalCandidate(ofstream *&out, KeySet *&Leaf, int *&ShortestPathList);
+  int GuesstimateFragmentCount(ofstream *out, int order);
+  	  
+  // Recognize doubly appearing molecules in a list of them   
+  int * IsEqualToWithinThreshold(ofstream *out, molecule *OtherMolecule, double threshold);
+  int * GetFatherSonAtomicMap(ofstream *out, molecule *OtherMolecule);
+	
+  // Output routines.
+  bool Output(ofstream *out);
+  bool OutputXYZ(ofstream *out) const;
+  bool Checkout(ofstream *out) const;
+
+  private:
+  int last_atom;      //!< number given to last atom
+};
+
+/** A list of \a molecule classes.
+ */
+class MoleculeListClass {
+  public:
+    molecule **ListOfMolecules;   //!< pointer list of fragment molecules to check for equality
+    int NumberOfMolecules;        //!< Number of entries in \a **FragmentList and of to be returned one.
+    int NumberOfTopAtoms;         //!< Number of atoms in the molecule from which all fragments originate
+    double *TEList;               //!< List of factors when summing over total energies of all fragment
+    
+  MoleculeListClass();
+  MoleculeListClass(int Num, int NumAtoms);
+  ~MoleculeListClass();
+
+  MoleculeListClass * FragmentTopDown(ofstream *out, int BondDegree, double bonddistance, config *configuration, enum CutCyclicBond Saturation);
+
+  /// Reduced list to unique molecules.
+  int * GetMappingToUniqueFragments(ofstream *out, double threshold, double *cell_size, double celldistance);
+  int ReduceFragmentToUniqueOnes(ofstream *out, int *Map);
+  void ReduceToUniqueList(ofstream *out, double *cell_size, double celldistance);
+
+  /// Output configs.
+  bool OutputConfigForListOfFragments(char *prefix, config *configuration, int *SortIndex);
+  void Output(ofstream *out);
+  
+  private:
+};
+
+
+/** A leaf for a tree of \a molecule class
+ * Wraps molecules in a tree structure
+ */
+class MoleculeLeafClass {
+  public:
+    molecule *Leaf;                   //!< molecule of this leaf 
+    //MoleculeLeafClass *UpLeaf;        //!< Leaf one level up
+    //MoleculeLeafClass *DownLeaf;      //!< First leaf one level down
+    MoleculeLeafClass *previous;  //!< Previous leaf on this level
+    MoleculeLeafClass *next;      //!< Next leaf on this level
+
+  //MoleculeLeafClass(MoleculeLeafClass *Up, MoleculeLeafClass *Previous);
+  MoleculeLeafClass(MoleculeLeafClass *PreviousLeaf);
+  ~MoleculeLeafClass();
+
+  bool AddLeaf(molecule *ptr, MoleculeLeafClass *Previous);
+};
+
+/** The config file.
+ * The class contains all parameters that control a dft run also functions to load and save.
+ */
+class config {
+  public:
+    int PsiType;
+    int MaxPsiDouble;
+    int PsiMaxNoUp;
+    int PsiMaxNoDown;
+    int MaxMinStopStep;
+    int InitMaxMinStopStep;
+    int ProcPEGamma;
+    int ProcPEPsi;
+    
+    private:
+    char *mainname;
+    char *defaultpath;
+    char *pseudopotpath;
+    
+    int DoOutVis;
+    int DoOutMes;
+    int DoOutNICS;
+    int DoOutOrbitals;
+    int DoOutCurrent;
+    int DoFullCurrent;
+    int DoPerturbation;
+    int CommonWannier;
+    double SawtoothStart;
+    int VectorPlane;
+    double VectorCut;
+    int UseAddGramSch;
+    int Seed;
+    
+    int MaxOuterStep;
+    double Deltat;
+    int OutVisStep;
+    int OutSrcStep;
+    double TargetTemp;
+    int ScaleTempStep;
+    int MaxPsiStep;
+    double EpsWannier;
+    
+    int MaxMinStep;
+    double RelEpsTotalEnergy;
+    double RelEpsKineticEnergy;
+    int MaxMinGapStopStep;
+    int MaxInitMinStep;
+    double InitRelEpsTotalEnergy;
+    double InitRelEpsKineticEnergy;
+    int InitMaxMinGapStopStep;
+    
+    //double BoxLength[NDIM*NDIM];
+    
+    double ECut;
+    int MaxLevel;
+    int RiemannTensor;
+    int LevRFactor;
+    int RiemannLevel;
+    int Lev0Factor;
+    int RTActualUse;
+    int AddPsis;
+    
+    double RCut;
+    int StructOpt;
+    int IsAngstroem;
+    int RelativeCoord;
+    int MaxTypes;
+
+  
+  int ParseForParameter(int verbose, ifstream *file, const char *name, int sequential, int const xth, int const yth, int type, void *value, int repetition, int critical);
+  
+  public:
+  config();
+  ~config();
+
+  int TestSyntax(ifstream *file, periodentafel *periode, molecule *mol);
+  void Load(ifstream *file, periodentafel *periode, molecule *mol);
+  void LoadOld(ifstream *file, periodentafel *periode, molecule *mol);
+  bool Save(ofstream *file, periodentafel *periode, molecule *mol) const;
+  void Edit(molecule *mol);
+  bool GetIsAngstroem() const;
+  char *GetDefaultPath() const;
+  void config::SetDefaultPath(const char *path);
+};
+
+#endif /*MOLECULES_HPP_*/
+
Index: molecuilder/src/orbitals.db
===================================================================
--- molecuilder/src/orbitals.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/orbitals.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,10 @@
+1	1
+2	0
+3	7
+4	6
+5	5
+6	4
+7	3
+8	2
+9	1
+10	0
Index: molecuilder/src/parser.cpp
===================================================================
--- molecuilder/src/parser.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/parser.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,638 @@
+/** \file parsing.cpp
+ *
+ * Declarations of various class functions for the parsing of value files.
+ *    
+ */
+
+using namespace std;
+
+// ======================================= INCLUDES ==========================================
+
+#include "helpers.hpp" 
+#include "parser.hpp"
+
+// ======================================= FUNCTIONS ==========================================
+
+/** Test if given filename can be opened.
+ * \param filename name of file
+ * \return given file exists
+ */
+#ifdef HAVE_INLINE
+inline
+#endif
+bool FilePresent(const char *filename)
+{
+  ifstream input;
+  
+  input.open(filename, ios::in);
+  if (input == NULL) {
+    cout << endl << "Unable to open " << filename << ", is the directory correct?" << endl;
+    return false;
+  }
+  input.close();
+  return true;
+};
+
+/** Test the given parameters.
+ * \param argc argument count
+ * \param **argv arguments array
+ * \return given inputdir is valid
+ */
+#ifdef HAVE_INLINE
+inline
+#endif
+bool TestParams(int argc, char **argv)
+{
+  ifstream input;
+  stringstream line;
+
+  line << argv[1] << FactorsFile;
+  return FilePresent(line.str().c_str());
+};
+
+// ======================================= CLASS MatrixContainer =============================
+
+/** Constructor of MatrixContainer class.
+ */
+MatrixContainer::MatrixContainer() {
+  Matrix = NULL;
+  Indices = NULL;
+  Header = NULL;
+  MatrixCounter = 0;
+  RowCounter = NULL;
+  ColumnCounter = 0;
+};
+
+/** Destructor of MatrixContainer class.
+ */
+MatrixContainer::~MatrixContainer() {
+  if (Matrix != NULL)
+    for(int i=0;i<MatrixCounter;i++) {
+      if (RowCounter != NULL)
+        for(int j=0;j<=RowCounter[i];j++)
+          Free((void **)&Matrix[i][j], "MatrixContainer::~MatrixContainer: *Matrix[][]");
+      Free((void **)&Matrix[i], "MatrixContainer::~MatrixContainer: **Matrix[]");
+    }
+  if ((RowCounter != NULL) && (Matrix[MatrixCounter] != NULL))
+    for(int j=0;j<=RowCounter[MatrixCounter];j++)
+      Free((void **)&Matrix[MatrixCounter][j], "MatrixContainer::~MatrixContainer: *Matrix[MatrixCounter][]");
+  Free((void **)&Matrix[MatrixCounter], "MatrixContainer::~MatrixContainer: **Matrix[MatrixCounter]");
+  Free((void **)&Matrix, "MatrixContainer::~MatrixContainer: ***Matrix");
+  
+  if (Indices != NULL)
+    for(int i=0;i<=MatrixCounter;i++) {
+      Free((void **)&Indices[i], "MatrixContainer::~MatrixContainer: *Indices[]");
+    }
+  Free((void **)&Indices, "MatrixContainer::~MatrixContainer: **Indices"); 
+  
+  Free((void **)&Header, "MatrixContainer::~MatrixContainer: *Header");
+  Free((void **)&RowCounter, "MatrixContainer::~MatrixContainer: *RowCounter");
+};
+
+/** Parsing a number of matrices.
+ * \param *name directory with files
+ * \param *prefix prefix of each matrix file
+ * \param *suffix suffix of each matrix file
+ * \param skiplines number of inital lines to skip
+ * \param skiplines number of inital columns to skip
+ * \return parsing successful 
+ */
+bool MatrixContainer::ParseMatrix(char *name, char *prefix, char *suffix, int skiplines, int skipcolumns)
+{
+  char filename[1023];
+  ifstream input;
+  char *FragmentNumber = NULL;
+  stringstream line;
+  double tmp;  
+  
+  Header = (char *) Malloc(sizeof(char)*1023, "MatrixContainer::ParseMatrix: *EnergyHeader");
+
+  // count the number of matrices
+  MatrixCounter = -1; // we count one too much
+  line << name << FactorsFile;
+  input.open(line.str().c_str(), ios::in);
+  if (input == NULL) {
+    cout << endl << "Unable to open " << line.str() << ", is the directory correct?" << endl;
+    return false;
+  }
+  while (!input.eof()) {
+    input >> tmp;
+    MatrixCounter++;
+  }
+  input.close();
+  cout << "Determined " << MatrixCounter << " fragments." << endl;
+  
+  cout << "Parsing through each fragment and retrieving " << prefix << suffix << "." << endl;
+  Matrix = (double ***) Malloc(sizeof(double **)*(MatrixCounter+1), "MatrixContainer::ParseMatrix: ***Matrix"); // one more each for the total molecule
+  RowCounter = (int *) Malloc(sizeof(int)*(MatrixCounter+1), "MatrixContainer::ParseMatrix: *RowCounter");
+  for(int i=0;i<=MatrixCounter;i++) {
+    // energy
+    stringstream line;
+    FragmentNumber = FixedDigitNumber(MatrixCounter, i);
+    if (i != MatrixCounter)  
+      line << name << FragmentPrefix << FragmentNumber << "/" << prefix << suffix;
+    else
+      line << name << prefix << suffix;
+    Free((void **)&FragmentNumber, "MatrixContainer::ParseMatrix: *FragmentNumber");
+    input.open(line.str().c_str(), ios::in);
+    //cout << "Opening " << line.str() << " ... "  << input << endl;
+    if (input == NULL) {
+      cerr << endl << "Unable to open " << line.str() << ", is the directory correct?" << endl;
+      return false;
+    }
+    // scan header for number of columns
+    for (int m=0;m<=skiplines;m++)
+      input.getline(Header, 1023);
+    line.str(Header);
+    for(int k=0;k<skipcolumns;k++)
+      line >> Header;
+    //cout << line.str() << endl;
+    ColumnCounter=0;
+    while (!line.eof()) {   
+      strcpy(filename,"@");
+      line >> filename;
+      if (filename[0] != '@')
+        ColumnCounter++;
+    }
+    //cout << line.str() << endl;
+    //cout << "ColumnCounter: " << ColumnCounter << endl;
+    // scan rest for number of rows/lines
+    RowCounter[i]=-1;    // counts one line too much
+    while (!input.eof()) { 
+      input.getline(filename, 1023);
+      //cout << "Comparing: " << strncmp(filename,"MeanForce",9) << endl;
+      RowCounter[i]++; // then line was not last MeanForce
+      if (strncmp(filename,"MeanForce", 9) == 0) {
+        break;
+      }
+    }
+    cout << "RowCounter[" << i << "]: " << RowCounter[i] << endl;
+    Matrix[i] = (double **) Malloc(sizeof(double *)*(RowCounter[i]+1), "MatrixContainer::ParseMatrix: **Matrix[]");
+    input.clear();
+    input.seekg(ios::beg);
+    for (int m=0;m<=skiplines;m++)
+      input.getline(Header, 1023);    // skip header
+    line.str(Header);
+    for(int k=0;k<skipcolumns;k++)  // skip columns in header too
+      line >> filename;
+    strncpy(Header, line.str().c_str(), 1023);  
+    for(int j=0;j<RowCounter[i];j++) {
+      Matrix[i][j] = (double *) Malloc(sizeof(double)*ColumnCounter, "MatrixContainer::ParseMatrix: *Matrix[][]");
+      input.getline(filename, 1023);
+      stringstream line(filename);
+      //cout << "Matrix at level " << j << ":";// << filename << endl;
+      for(int k=0;k<skipcolumns;k++)
+        line >> filename;
+      for(int k=0;(k<ColumnCounter) && (!line.eof());k++) {
+        line >> Matrix[i][j][k];
+        //cout << " " << setprecision(2) << Matrix[i][j][k];;
+      }
+      //cout << endl;
+    }
+    Matrix[i][ RowCounter[i] ] = (double *) Malloc(sizeof(double)*ColumnCounter, "MatrixContainer::ParseMatrix: *Matrix[RowCounter[i]][]");
+    for(int j=0;j<ColumnCounter;j++)
+      Matrix[i][ RowCounter[i] ][j] = 0.;
+    input.close();
+  }
+  return true;
+};
+
+/** Allocates and resets the memory for a number \a MCounter of matrices.
+ * \param *GivenHeader Header line
+ * \param MCounter number of matrices
+ * \param *RCounter number of rows for each matrix
+ * \param CCounter number of columns for all matrices
+ * \return Allocation successful 
+ */
+bool MatrixContainer::AllocateMatrix(char *GivenHeader, int MCounter, int *RCounter, int CCounter)
+{
+  Header = (char *) Malloc(sizeof(char)*1024, "MatrixContainer::ParseMatrix: *EnergyHeader");
+  strncpy(Header, GivenHeader, 1023);
+
+  MatrixCounter = MCounter;
+  ColumnCounter = CCounter;
+  Matrix = (double ***) Malloc(sizeof(double **)*(MatrixCounter+1), "MatrixContainer::ParseMatrix: ***Matrix"); // one more each for the total molecule
+  RowCounter = (int *) Malloc(sizeof(int)*(MatrixCounter+1), "MatrixContainer::ParseMatrix: *RowCounter");
+  for(int i=0;i<=MatrixCounter;i++) {
+    RowCounter[i] = RCounter[i];
+    Matrix[i] = (double **) Malloc(sizeof(double *)*(RowCounter[i]+1), "MatrixContainer::ParseMatrix: **Matrix[]");  
+    for(int j=0;j<=RowCounter[i];j++) {
+      Matrix[i][j] = (double *) Malloc(sizeof(double)*ColumnCounter, "MatrixContainer::ParseMatrix: *Matrix[][]");
+      for(int k=0;k<ColumnCounter;k++)
+        Matrix[i][j][k] = 0.;
+    }
+  }
+  return true;
+};
+
+/** Resets all values in MatrixContainer::Matrix.
+ * \return true if successful
+ */
+bool MatrixContainer::ResetMatrix()
+{
+  for(int i=0;i<=MatrixCounter;i++)
+    for(int j=0;j<=RowCounter[i];j++)
+      for(int k=0;k<ColumnCounter;k++)
+        Matrix[i][j][k] = 0.;
+   return true;
+};
+
+/** Sets all values in the last of MatrixContainer::Matrix to \a value.
+ * \param value reset value
+ * \param skipcolumns skip initial columns
+ * \return true if successful
+ */
+bool MatrixContainer::SetLastMatrix(double value, int skipcolumns)
+{
+  for(int j=0;j<=RowCounter[MatrixCounter];j++)
+    for(int k=skipcolumns;k<ColumnCounter;k++)
+      Matrix[MatrixCounter][j][k] = value;
+   return true;
+};
+
+/** Sets all values in the last of MatrixContainer::Matrix to \a value.
+ * \param **values matrix with each value (must have at least same dimensions!)
+ * \param skipcolumns skip initial columns
+ * \return true if successful
+ */
+bool MatrixContainer::SetLastMatrix(double **values, int skipcolumns)
+{
+  for(int j=0;j<=RowCounter[MatrixCounter];j++)
+    for(int k=skipcolumns;k<ColumnCounter;k++)
+      Matrix[MatrixCounter][j][k] = values[j][k];
+   return true;
+};
+
+/** Sums the energy with each factor and put into last element of \a ***Energies.
+ * \param Matrix MatrixContainer with matrices (LevelCounter by ColumnCounter) with all the energies.
+ * \param KeySet KeySetContainer with bond Order and association mapping of each fragment to an order
+ * \param Order bond order
+ * \return true if summing was successful
+ */
+bool MatrixContainer::SumSubManyBodyTerms(class MatrixContainer &MatrixValues, class KeySetsContainer &KeySet, int Order)
+{
+  // go through each order
+  for (int CurrentFragment=0;CurrentFragment<KeySet.FragmentsPerOrder[Order];CurrentFragment++) {
+    //cout << "Current Fragment is " << CurrentFragment << "/" << KeySet.OrderSet[Order][CurrentFragment] << "." << endl;
+    // then go per order through each suborder and pick together all the terms that contain this fragment
+    for(int SubOrder=0;SubOrder<=Order;SubOrder++) { // go through all suborders up to the desired order
+      for (int j=0;j<KeySet.FragmentsPerOrder[SubOrder];j++) { // go through all possible fragments of size suborder
+        if (KeySet.Contains(KeySet.OrderSet[Order][CurrentFragment], KeySet.OrderSet[SubOrder][j])) {
+          //cout << "Current other fragment is " << j << "/" << KeySet.OrderSet[SubOrder][j] << "." << endl;
+          // if the fragment's indices are all in the current fragment
+          for(int k=0;k<RowCounter[ KeySet.OrderSet[SubOrder][j] ];k++) { // go through all atoms in this fragment
+            int m = MatrixValues.Indices[ KeySet.OrderSet[SubOrder][j] ][k];
+            //cout << "Current index is " << k << "/" << m << "." << endl;
+            if (m != -1) { // if it's not an added hydrogen
+              for (int l=0;l<RowCounter[ KeySet.OrderSet[Order][CurrentFragment] ];l++) { // look for the corresponding index in the current fragment
+                //cout << "Comparing " << m << " with " << Matrix.Indices[ KeySet.OrderSet[Order][CurrentFragment] ][l] << "." << endl;
+                if (m == MatrixValues.Indices[ KeySet.OrderSet[Order][CurrentFragment] ][l]) {
+                  m = l;
+                  break;  
+                }
+              }
+              //cout << "Corresponding index in CurrentFragment is " << m << "." << endl;
+              if (m > RowCounter[ KeySet.OrderSet[Order][CurrentFragment] ]) {
+                cerr << "Current force index " << m << " is greater than " << RowCounter[ KeySet.OrderSet[Order][CurrentFragment] ] << "!" << endl;
+                return false;
+              }
+              if (Order == SubOrder) { // equal order is always copy from Energies
+                for(int l=0;l<ColumnCounter;l++) // then adds/subtract each column 
+                  Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][m][l] += MatrixValues.Matrix[ KeySet.OrderSet[SubOrder][j] ][k][l];
+              } else {
+                for(int l=0;l<ColumnCounter;l++)
+                  Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][m][l] -= Matrix[ KeySet.OrderSet[SubOrder][j] ][k][l];
+              }
+            }
+          //if ((ColumnCounter>1) && (RowCounter >= 1))
+            //cout << "Fragments[ KeySet.OrderSet[" << i << "][" << CurrentFragment << "]=" << KeySet.OrderSet[Order][CurrentFragment] << " ][" << RowCounter[0]-1 << "][" << 1 << "] = " <<  Fragments[ KeySet.OrderSet[Order][CurrentFragment] ][RowCounter[0]-1][1] << endl;
+          }
+        } else {
+          //cout << "Fragment " << KeySet.OrderSet[SubOrder][j] << " is not contained in fragment " << KeySet. KeySet.OrderSet[Order][CurrentFragment] << "." << endl;
+        }
+      }
+    }
+    //cout << "Final Fragments[ KeySet.OrderSet[" << Order << "][" << CurrentFragment << "]=" << KeySet.OrderSet[Order][CurrentFragment] << " ][" << KeySet.AtomCounter[0]-1 << "][" << 1 << "] = " <<  Fragments[ KeySet.OrderSet[Order][CurrentFragment] ][KeySet.AtomCounter[0]-1][1] << endl;
+  }
+  
+  return true;
+};
+
+/** Writes the summed total fragment terms \f$F_{ij}\f$ to file.
+ * \param *name inputdir
+ * \param *prefix prefix before \a EnergySuffix
+ * \return file was written
+ */
+bool MatrixContainer::WriteTotalFragments(const char *name, const char *prefix)
+{
+  ofstream output;
+  char *FragmentNumber = NULL;
+
+  cout << "Writing fragment files." << endl;
+  for(int i=0;i<MatrixCounter;i++) {
+    stringstream line;
+    FragmentNumber = FixedDigitNumber(MatrixCounter, i);
+    line << name << FragmentPrefix << FragmentNumber << "/" << prefix;
+    Free((void **)&FragmentNumber, "*FragmentNumber");
+    output.open(line.str().c_str(), ios::out);
+    if (output == NULL) {
+      cerr << "Unable to open output energy file " << line.str() << "!" << endl;
+      return false;
+    }
+    output << Header << endl;
+    for(int j=0;j<RowCounter[i];j++) {
+      for(int k=0;k<ColumnCounter;k++)
+        output << scientific << Matrix[i][j][k] << "\t";
+      output << endl;
+    }
+    output.close();
+  }
+  return true;
+};
+
+/** Writes the summed total values in the last matrix to file.
+ * \param *name inputdir
+ * \param *prefix prefix
+ * \param *suffix suffix
+ * \return file was written
+ */
+bool MatrixContainer::WriteLastMatrix(const char *name, const char *prefix, const char *suffix)
+{
+  ofstream output;
+  stringstream line;
+
+  cout << "Writing matrix values of " << suffix << "." << endl;
+  line << name << prefix << suffix;
+  output.open(line.str().c_str(), ios::out);
+  if (output == NULL) {
+    cerr << "Unable to open output matrix file " << line.str() << "!" << endl;
+    return false;
+  }
+  output << Header << endl;
+  for(int j=0;j<RowCounter[MatrixCounter];j++) {
+    for(int k=0;k<ColumnCounter;k++)
+      output << scientific << Matrix[MatrixCounter][j][k] << "\t";
+    output << endl;
+  }
+  output.close();
+  return true;
+};
+
+// ======================================= CLASS EnergyMatrix =============================
+
+/** Create a trivial energy index mapping.
+ * This just maps 1 to 1, 2 to 2 and so on for all fragments.
+ * \return creation sucessful
+ */
+bool EnergyMatrix::ParseIndices() 
+{
+  cout << "Parsing energy indices." << endl;
+  Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "EnergyMatrix::ParseIndices: **Indices");
+  for(int i=0;i<=MatrixCounter;i++) {
+    Indices[i] = (int *) Malloc(sizeof(int)*RowCounter[i], "EnergyMatrix::ParseIndices: *Indices[]");
+    for(int j=0;j<RowCounter[i];j++)
+      Indices[i][j] = j;
+  } 
+  return true; 
+};
+
+/** Sums the energy with each factor and put into last element of \a EnergyMatrix::Matrix.
+ * \param Matrix MatrixContainer with matrices (LevelCounter by ColumnCounter) with all the energies.
+ * \param KeySet KeySetContainer with bond Order and association mapping of each fragment to an order
+ * \param Order bond order
+ * \return true if summing was successful
+ */
+bool EnergyMatrix::SumSubEnergy(class EnergyMatrix &Fragments, class KeySetsContainer &KeySet, int Order)
+{
+  // sum energy
+  for(int i=0;i<KeySet.FragmentsPerOrder[Order];i++)
+    for(int j=0;j<RowCounter[ KeySet.OrderSet[Order][i] ];j++)
+      for(int k=0;k<ColumnCounter;k++)
+        Matrix[MatrixCounter][j][k] += Fragments.Matrix[ KeySet.OrderSet[Order][i] ][j][k];
+  return true;
+};
+
+// ======================================= CLASS ForceMatrix =============================
+
+/** Parsing force Indices of each fragment
+ * \param *name directory with \a ForcesFile
+ * \return parsing successful 
+ */
+bool ForceMatrix::ParseIndices(char *name) 
+{
+  ifstream input;
+  char *FragmentNumber = NULL;
+  char filename[1023];
+  stringstream line;
+  
+  cout << "Parsing force indices." << endl;
+  Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "ForceMatrix::ParseIndices: **Indices");
+  line << name << ForcesFile;
+  input.open(line.str().c_str(), ios::in);
+  //cout << "Opening " << line.str() << " ... "  << input << endl;
+  if (input == NULL) {
+    cout << endl << "Unable to open " << line.str() << ", is the directory correct?" << endl;
+    return false;
+  }
+  for (int i=0;(i<MatrixCounter) && (!input.eof());i++) {
+    // get the number of atoms for this fragment
+    stringstream line;
+    input.getline(filename, 1023);
+    line.str(filename);
+    // parse the values
+    Indices[i] = (int *) Malloc(sizeof(int)*RowCounter[i], "ForceMatrix::ParseIndices: *Indices[]");
+    FragmentNumber = FixedDigitNumber(MatrixCounter, i);
+    cout << FragmentPrefix << FragmentNumber << "[" << RowCounter[i] << "]:";
+    Free((void **)&FragmentNumber, "ForceMatrix::ParseIndices: *FragmentNumber");
+    for(int j=0;(j<RowCounter[i]) && (!line.eof());j++) {
+      line >> Indices[i][j];
+      cout << " " << Indices[i][j];
+    }
+    cout << endl;
+  }
+  Indices[MatrixCounter] = (int *) Malloc(sizeof(int)*RowCounter[MatrixCounter], "ForceMatrix::ParseIndices: *Indices[]");
+  for(int j=0;j<RowCounter[MatrixCounter];j++) {
+    Indices[MatrixCounter][j] = j;
+  }
+  input.close();
+  return true;
+};
+
+
+/** Sums the forces and puts into last element of \a ForceMatrix::Matrix.
+ * \param Matrix MatrixContainer with matrices (LevelCounter by ColumnCounter) with all the energies.
+ * \param KeySet KeySetContainer with bond Order and association mapping of each fragment to an order
+ * \param Order bond order
+ * \return true if summing was successful
+ */
+bool ForceMatrix::SumSubForces(class ForceMatrix &Fragments, class KeySetsContainer &KeySet, int Order)
+{
+  // sum forces
+  for(int i=0;i<KeySet.FragmentsPerOrder[Order];i++)
+    for(int l=0;l<RowCounter[ KeySet.OrderSet[Order][i] ];l++) {
+      int j = Indices[ KeySet.OrderSet[Order][i] ][l];
+      if (j > RowCounter[MatrixCounter]) {
+        cerr << "Current force index " << j << " is greater than " << RowCounter[MatrixCounter] << "!" << endl;
+        return false;
+      }
+      if (j != -1)
+        for(int k=2;k<ColumnCounter;k++)
+          Matrix[MatrixCounter][j][k] += Fragments.Matrix[ KeySet.OrderSet[Order][i] ][l][k];
+    }
+  return true;
+};
+
+
+// ======================================= CLASS KeySetsContainer =============================
+
+/** Constructor of KeySetsContainer class.
+ */
+KeySetsContainer::KeySetsContainer() {
+  KeySets = NULL;
+  AtomCounter = NULL;
+  FragmentCounter = 0;
+  Order = 0;
+  FragmentsPerOrder = 0;
+  OrderSet = NULL;
+};
+
+/** Destructor of KeySetsContainer class.
+ */
+KeySetsContainer::~KeySetsContainer() {
+  for(int i=0;i<FragmentCounter;i++)
+    Free((void **)&KeySets[i], "KeySetsContainer::~KeySetsContainer: *KeySets[]");
+  for(int i=0;i<Order;i++)
+    Free((void **)&OrderSet[i], "KeySetsContainer::~KeySetsContainer: *OrderSet[]");
+  Free((void **)&KeySets, "KeySetsContainer::~KeySetsContainer: **KeySets");
+  Free((void **)&OrderSet, "KeySetsContainer::~KeySetsContainer: **OrderSet");
+  Free((void **)&AtomCounter, "KeySetsContainer::~KeySetsContainer: *AtomCounter");
+  Free((void **)&FragmentsPerOrder, "KeySetsContainer::~KeySetsContainer: *FragmentsPerOrder");
+};
+
+/** Parsing KeySets into array.
+ * \param *name directory with keyset file
+ * \param *ACounter number of atoms per fragment
+ * \param FCounter number of fragments
+ * \return parsing succesful
+ */
+bool KeySetsContainer::ParseKeySets(const char *name, const int *ACounter, const int FCounter) {
+  ifstream input;
+  char *FragmentNumber = NULL;
+  stringstream line;
+  char filename[1023];
+  
+  FragmentCounter = FCounter;
+  cout << "Parsing key sets." << endl;
+  KeySets = (int **) Malloc(sizeof(int *)*FragmentCounter, "KeySetsContainer::ParseKeySets: **KeySets");
+  line << name << KeySetsFile;
+  input.open(line.str().c_str(), ios::in);
+  if (input == NULL) {
+    cout << endl << "Unable to open " << line.str() << ", is the directory correct?" << endl;
+    return false;
+  }
+  
+  AtomCounter = (int *) Malloc(sizeof(int)*FragmentCounter, "KeySetsContainer::ParseKeySets: *RowCounter");
+  for(int i=0;(i<FragmentCounter) && (!input.eof());i++) {
+    stringstream line;
+    AtomCounter[i] = ACounter[i];
+    // parse the values
+    KeySets[i] = (int *) Malloc(sizeof(int)*AtomCounter[i], "KeySetsContainer::ParseKeySets: *KeySets[]");
+    FragmentNumber = FixedDigitNumber(FragmentCounter, i);
+    cout << FragmentPrefix << FragmentNumber << "[" << AtomCounter[i] << "]:";
+    Free((void **)&FragmentNumber, "KeySetsContainer::ParseKeySets: *FragmentNumber");
+    input.getline(filename, 1023);
+    line.str(filename);
+    for(int j=0;(j<AtomCounter[i]) && (!line.eof());j++) {
+      line >> KeySets[i][j];
+      cout << " " << KeySets[i][j];
+    }
+    cout << endl;
+  }
+  input.close();
+  return true;
+};
+
+/** Parse many body terms, associating each fragment to a certain bond order.
+ * \return parsing succesful
+ */
+bool KeySetsContainer::ParseManyBodyTerms()
+{
+  int Counter;
+  
+  cout << "Creating Fragment terms." << endl;
+  // scan through all to determine order
+  Order=0;
+  for(int i=0;i<FragmentCounter;i++) {
+    Counter=0;
+    for(int j=0;j<AtomCounter[i];j++)
+      if (KeySets[i][j] != -1)
+        Counter++;
+    if (Counter > Order)
+      Order = Counter;
+  }
+  cout << "Found Order is " << Order << "." << endl;
+  
+  // scan through all to determine fragments per order
+  FragmentsPerOrder = (int *) Malloc(sizeof(int)*Order, "KeySetsContainer::ParseManyBodyTerms: *FragmentsPerOrder");
+  for(int i=0;i<Order;i++)
+    FragmentsPerOrder[i] = 0;
+  for(int i=0;i<FragmentCounter;i++) {
+    Counter=0;
+    for(int j=0;j<AtomCounter[i];j++)
+      if (KeySets[i][j] != -1)
+        Counter++;
+    FragmentsPerOrder[Counter-1]++;
+  }
+  for(int i=0;i<Order;i++)
+    cout << "Found No. of Fragments of Order " << i+1 << " is " << FragmentsPerOrder[i] << "." << endl;
+    
+  // scan through all to gather indices to each order set
+  OrderSet = (int **) Malloc(sizeof(int *)*Order, "KeySetsContainer::ParseManyBodyTerms: **OrderSet");
+  for(int i=0;i<Order;i++)
+    OrderSet[i] = (int *) Malloc(sizeof(int)*FragmentsPerOrder[i], "KeySetsContainer::ParseManyBodyTermsKeySetsContainer::ParseManyBodyTerms: *OrderSet[]");
+  for(int i=0;i<Order;i++)
+    FragmentsPerOrder[i] = 0;
+  for(int i=0;i<FragmentCounter;i++) {
+    Counter=0;
+    for(int j=0;j<AtomCounter[i];j++)
+      if (KeySets[i][j] != -1)
+        Counter++;
+    OrderSet[Counter-1][FragmentsPerOrder[Counter-1]] = i;
+    FragmentsPerOrder[Counter-1]++;
+  }
+  cout << "Printing OrderSet." << endl;
+  for(int i=0;i<Order;i++) {
+    for (int j=0;j<FragmentsPerOrder[i];j++) {
+      cout << " " << OrderSet[i][j];
+    }
+    cout << endl;
+  }
+  cout << endl;
+  
+    
+  return true;
+};
+
+/** Compares each entry in \a *SmallerSet if it is containted in \a *GreaterSet.
+ * \param GreaterSet index to greater set
+ * \param SmallerSet index to smaller set
+ * \return true if all keys of SmallerSet contained in GreaterSet
+ */
+bool KeySetsContainer::Contains(const int GreaterSet, const int SmallerSet)
+{
+  bool result = true;
+  bool intermediate;
+  if ((GreaterSet < 0) || (SmallerSet < 0) || (GreaterSet > FragmentCounter) || (SmallerSet > FragmentCounter)) // index out of bounds
+    return false;
+  for(int i=0;i<AtomCounter[SmallerSet];i++) {
+    intermediate = false;
+    for (int j=0;j<AtomCounter[GreaterSet];j++)
+      intermediate = (intermediate || ((KeySets[SmallerSet][i] == KeySets[GreaterSet][j]) || (KeySets[SmallerSet][i] == -1)));
+    result = result && intermediate;
+  }
+
+  return result;
+};
+
+
+// ======================================= END =============================================
Index: molecuilder/src/parser.hpp
===================================================================
--- molecuilder/src/parser.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/parser.hpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,100 @@
+/** \file parsing.hpp
+ *
+ * Definitions of various class functions for the parsing of value files.
+ *    
+ */
+
+
+#ifndef PARSING_HPP_
+#define PARSING_HPP_
+
+// ======================================= DEFINES ==========================================
+
+#define MYEPSILON 1e-13
+#define FactorsFile "BondFragmentTE-Factors.dat"
+#define ForcesFile "BondFragmentForces-Factors.dat"
+#define KeySetsFile "BondFragmentKeySets.dat"
+#define FragmentPrefix "BondFragment"
+#define EnergySuffix ".energy.all"
+#define ForcesSuffix ".forces.all"
+#define TimeSuffix ".speed"
+#define EnergyFragmentSuffix ".energyfragment.all"
+#define ForceFragmentSuffix ".forcefragment.all"
+#define OrderSuffix ".Order"
+
+// ======================================= FUNCTIONS ==========================================
+
+#ifdef HAVE_INLINE
+inline
+#endif
+bool FilePresent(const char *filename);
+
+#ifdef HAVE_INLINE
+inline
+#endif
+bool TestParams(int argc, char **argv);
+
+// ======================================= CLASS MatrixContainer =============================
+
+class MatrixContainer {
+  public:
+    double ***Matrix;
+    int **Indices;
+    char *Header;
+    int MatrixCounter;
+    int *RowCounter;
+    int ColumnCounter;
+  
+  MatrixContainer();
+  ~MatrixContainer();
+  
+  bool ParseMatrix(char *name, char *prefix, char *suffix, int skiplines, int skipcolumns);
+  bool AllocateMatrix(char *GivenHeader, int MCounter, int *RCounter, int CCounter);
+  bool ResetMatrix();
+  bool SetLastMatrix(double value, int skipcolumns);
+  bool SetLastMatrix(double **values, int skipcolumns);
+  //bool ParseIndices();
+  //bool SumSubValues();
+  bool SumSubManyBodyTerms(class MatrixContainer &Matrix, class KeySetsContainer &KeySet, int Order);
+  bool WriteTotalFragments(const char *name, const char *prefix);
+  bool WriteLastMatrix(const char *name, const char *prefix, const char *suffix);
+}; 
+
+// ======================================= CLASS EnergyMatrix =============================
+
+class EnergyMatrix : public MatrixContainer {
+  public:
+    bool ParseIndices();
+    bool SumSubEnergy(class EnergyMatrix &Fragments, class KeySetsContainer &KeySet, int Order);
+};
+
+// ======================================= CLASS ForceMatrix =============================
+
+class ForceMatrix : public MatrixContainer {
+  public: 
+    bool ParseIndices(char *name);
+    bool SumSubForces(class ForceMatrix &Fragments, class KeySetsContainer &KeySet, int Order);
+};
+
+// ======================================= CLASS KeySetsContainer =============================
+
+class KeySetsContainer {
+  public:
+    int **KeySets;
+    int *AtomCounter;
+    int FragmentCounter;
+    int Order;
+    int *FragmentsPerOrder;
+    int **OrderSet;
+  
+  KeySetsContainer();
+  ~KeySetsContainer();
+   
+  bool ParseKeySets(const char *name, const int *ACounter, const int FCounter);
+  bool ParseManyBodyTerms();
+  bool KeySetsContainer::Contains(const int GreaterSet, const int SmallerSet);
+};
+
+// ======================================= END =============================================
+
+#endif /*PARSING_HPP_*/
Index: molecuilder/src/periodentafel.cpp
===================================================================
--- molecuilder/src/periodentafel.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/periodentafel.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,271 @@
+/** \file periodentafel.cpp
+ * 
+ * Function implementations for the class periodentafel.
+ * 
+ */
+
+#include "molecules.hpp"
+
+/************************************* Functions for class periodentafel ***************************/
+
+/** constructor for class periodentafel
+ * Initialises start and end of list and resets periodentafel::checkliste to false.
+ */
+periodentafel::periodentafel() 
+{ 
+  start = new element; 
+  end = new element; 
+  start->previous = NULL; 
+  start->next = end; 
+  end->previous = start; 
+  end->next = NULL;
+};
+
+/** destructor for class periodentafel
+ * Removes every element and afterwards deletes start and end of list.
+ */
+periodentafel::~periodentafel() 
+{ 
+  CleanupPeriodtable(); 
+  delete(end); 
+  delete(start); 
+}; 
+
+/** Adds element to period table list
+ * \param *pointer element to be added
+ * \return true - succeeded, false - does not occur
+ */
+bool periodentafel::AddElement(element *pointer) 
+{ 
+  pointer->sort = &pointer->Z;
+  if (pointer->Z < 1 && pointer->Z >= MAX_ELEMENTS)
+    cout << Verbose(0) << "Invalid Z number!\n";
+  return add(pointer, end); 
+};
+
+/** Removes element from list.
+ * \param *pointer element to be removed
+ * \return true - succeeded, false - element not found
+ */
+bool periodentafel::RemoveElement(element *pointer) 
+{ 
+  return remove(pointer, start, end); 
+};
+
+/** Removes every element from the period table.
+ * \return true - succeeded, false - does not occur
+ */
+bool periodentafel::CleanupPeriodtable() 
+{ 
+  return cleanup(start,end); 
+};
+
+/** Finds an element by its atomic number.
+ * If element is not yet in list, datas are asked and stored in database.
+ * \param Z atomic number
+ * \return pointer to element
+ */
+element * periodentafel::FindElement(int Z)
+{
+  element *walker = find(&Z, start,end);
+  if (walker == NULL) { // not found: enter and put into db
+    cout << Verbose(0) << "Element not found in database, please enter." << endl;
+    walker = new element;
+    cout << Verbose(0) << "Mass: " << endl;
+    cin >> walker->mass;
+    walker->Z = Z;  
+    cout << Verbose(0) << "Atomic number: " << walker->Z << endl;  
+    cout << Verbose(0) << "Name [max 64 chars]: " << endl;
+    cin >> walker->name;
+    cout << Verbose(0) << "Short form [max 3 chars]: " << endl;
+    cin >> walker->symbol;
+    periodentafel::AddElement(walker);
+  }
+  return(walker);
+};
+
+/** Finds an element by its atomic number.
+ * If element is not yet in list, datas are asked and stored in database.
+ * \param shorthand chemical symbol of the element, e.g. H for hydrogene
+ * \return pointer to element
+ */
+element * periodentafel::FindElement(char *shorthand) const
+{
+  element *walker =  periodentafel::start;
+  while (walker->next != periodentafel::end) {
+    walker = walker->next;
+    if (strncmp(walker->symbol, shorthand, 3) == 0)
+      return(walker);
+  }
+  return (NULL);
+};
+
+/** Asks for element number and returns pointer to element
+ */
+element * periodentafel::AskElement() 
+{
+  element *walker = NULL;
+  int Z;
+  do {
+    cout << Verbose(0) << "Atomic number Z: ";
+    cin >> Z;
+    walker = this->FindElement(Z);  // give type
+  } while (walker == NULL);
+  return walker;
+};
+
+
+/** Prints period table to given stream.
+ * \param output stream
+ */ 
+bool periodentafel::Output(ofstream *output) const
+{
+  bool result = true;
+  element *walker = start;
+  if (output != NULL) {
+    while (walker->next != end) {
+      walker = walker->next;
+      result = result && walker->Output(output);
+    }
+    return result;
+  } else 
+    return false;
+};
+
+/** Prints period table to given stream.
+ * \param *output output stream
+ * \param *checkliste elements table for this molecule
+ */ 
+bool periodentafel::Checkout(ofstream *output, const int *checkliste) const
+{
+  element *walker = start;
+  bool result = true;
+  int No = 1;
+
+  if (output != NULL) {
+    *output << "# Ion type data (PP = PseudoPotential, Z = atomic number)" << endl;
+    *output << "#Ion_TypeNr.\tAmount\tZ\tRGauss\tL_Max(PP)L_Loc(PP)IonMass\t# chemical name, symbol" << endl;
+    while (walker->next != end) {
+      walker = walker->next;
+      if (checkliste[walker->Z]) {
+        walker->No = No;
+        result = result && walker->Checkout(output, No++, checkliste[walker->Z]);      
+      }
+    }
+    return result;
+  } else 
+    return false;
+};
+
+
+/** Loads element list from file.
+ */
+bool periodentafel::LoadPeriodentafel()
+{
+  ifstream infile;
+  double tmp;
+  element *ptr;
+  
+  // fill elements DB
+  infile.open("elements.db");
+  infile.getline(header1, 255);
+  infile.getline(header2, 255); // skip first two header lines
+  while (!infile.eof()) {
+    element *neues = new element;
+    infile >> neues->name;
+    //infile >> ws;
+    infile >> neues->symbol;
+    //infile >> ws;
+    infile >> neues->period;
+    //infile >> ws;
+    infile >> neues->group;
+    //infile >> ws;
+    infile >> neues->block;
+    //infile >> ws;
+    infile >> neues->Z;
+    //infile >> ws;
+    infile >> neues->mass;
+    //infile >> ws;
+    infile >> neues->CovalentRadius;
+    //infile >> ws;
+    infile >> neues->VanDerWaalsRadius;
+    //infile >> ws;
+    periodentafel::AddElement(neues);
+    infile >> ws;
+    neues->Output((ofstream *)&cout);
+  }
+  infile.close();
+  infile.clear();
+
+  // fill valence DB per element
+  infile.open("valence.db");
+  while (!infile.eof()) {
+  	infile >> tmp;
+  	infile >> ws;
+  	infile >> FindElement((int)tmp)->Valence;
+  	infile >> ws;
+  	//cout << Verbose(3) << "Element " << (int)tmp << " has " << find_element((int)tmp)->Valence << " valence electrons." << endl;
+  }
+  infile.close();
+  infile.clear();
+
+  // fill valence DB per element
+  infile.open("orbitals.db");
+  while (!infile.eof()) {
+    infile >> tmp;
+    infile >> ws;
+    infile >> FindElement((int)tmp)->NoValenceOrbitals;
+    infile >> ws;
+    //cout << Verbose(3) << "Element " << (int)tmp << " has " << find_element((int)tmp)->NoValenceOrbitals << " number of singly occupied valence orbitals." << endl;
+  }
+  infile.close();
+  infile.clear();
+  
+  // fill H-BondDistance DB per element
+  infile.open("Hbonddistance.db");
+  while (!infile.eof()) {
+  	infile >> tmp;
+    ptr = FindElement((int)tmp);
+  	infile >> ws;
+    infile >> ptr->HBondDistance[0];
+    infile >> ptr->HBondDistance[1];
+    infile >> ptr->HBondDistance[2];
+  	infile >> ws;
+    //cout << Verbose(3) << "Element " << (int)tmp << " has " << find_element((int)tmp)->HBondDistance[0] << " Angstrom typical distance to hydrogen." << endl;
+  }
+  infile.close();
+  infile.clear();
+  
+  // fill H-BondAngle DB per element
+  infile.open("Hbondangle.db");
+  while (!infile.eof()) {
+    infile >> tmp;
+    ptr = FindElement((int)tmp);
+    infile >> ws;
+    infile >> ptr->HBondAngle[0];
+    infile >> ptr->HBondAngle[1];
+    infile >> ptr->HBondAngle[2];
+    infile >> ws;
+    //cout << Verbose(3) << "Element " << (int)tmp << " has " << FindElement((int)tmp)->HBondAngle[0] << ", " << FindElement((int)tmp)->HBondAngle[1] << ", " << FindElement((int)tmp)->HBondAngle[2] << " degrees bond angle for one, two, three connected hydrogens." << endl;
+  }
+  infile.close();
+  
+  return true;
+};
+
+/** Stores element list to file.
+ */
+bool periodentafel::StorePeriodentafel() const
+{
+  bool result = true;
+  ofstream f("elements.db");
+  f << header1 << endl;
+  f << header2 << endl;
+  element *walker = periodentafel::start;
+  while (walker->next != periodentafel::end) {
+    walker = walker->next;
+    result = result && walker->Output(&f);
+  }
+  f.close();
+  return result;
+};
Index: molecuilder/src/valence.db
===================================================================
--- molecuilder/src/valence.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/valence.db	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,65 @@
+1	0.10000000000000E+01
+2	0.20000000000000E+01
+3	0.10000000000000E+01
+4	0.20000000000000E+01
+5	0.30000000000000E+01
+6	0.40000000000000E+01
+7	0.50000000000000E+01
+8	0.60000000000000E+01
+9	0.70000000000000E+01
+10	0.80000000000000E+01
+11	0.10000000000000E+01
+12	0.40000000000000E+01
+13	.3000000000000000E+01
+14	0.40000000000000E+01
+15	0.50000000000000E+01
+16	0.60000000000000E+01
+17	0.70000000000000E+01
+18	0.80000000000000E+01
+19	0.30000000000000E+01
+20	0.20000000000000E+01
+21	0.30000000000000E+01
+22	0.40000000000000E+01
+23	0.50000000000000E+01
+24	0.60000000000000E+01
+25	0.70000000000000E+01
+26	0.80000000000000E+01
+27	0.90000000000000E+01
+28	0.10000000000000E+02
+29	0.11000000000000E+02
+30	0.12000000000000E+02
+31	3.00000000000000000
+32	0.40000000000000E+01
+33	5.00000000000000000
+34	0.60000000000000E+01
+35	0.70000000000000E+01
+36	0.80000000000000E+01
+37	0.10000000000000E+01
+38	0.20000000000000E+01
+39	0.30000000000000E+01
+40	0.40000000000000E+01
+41	0.50000000000000E+01
+42	0.60000000000000E+01
+43	0.70000000000000E+01
+44	0.80000000000000E+01
+45	0.90000000000000E+01
+46	0.10000000000000E+02
+47	0.11000000000000E+02
+48	0.12000000000000E+02
+49	0.30000000000000E+01
+50	0.40000000000000E+01
+51	0.50000000000000E+01
+52	0.60000000000000E+01
+53	0.70000000000000E+01
+54	0.80000000000000E+01
+55	0.10000000000000E+01
+56	0.20000000000000E+01
+72	0.40000000000000E+01
+73	0.50000000000000E+01
+74	0.60000000000000E+01
+75	0.70000000000000E+01
+76	0.80000000000000E+01
+77	0.90000000000000E+01
+78	0.10000000000000E+02
+79	0.11000000000000E+02
+80	0.12000000000000E+02
Index: molecuilder/src/vector.cpp
===================================================================
--- molecuilder/src/vector.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/vector.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,751 @@
+/** \file vector.cpp
+ * 
+ * Function implementations for the class vector.
+ * 
+ */
+ 
+#include "molecules.hpp"
+ 
+
+/************************************ Functions for class vector ************************************/
+
+/** Constructor of class vector.
+ */
+vector::vector() { x[0] = x[1] = x[2] = 0.; };
+
+/** Desctructor of class vector.
+ */
+vector::~vector() {};
+
+/** Calculates distance between this and another vector.
+ * \param *y array to second vector
+ * \return \f$| x - y |^2\f$
+ */
+double vector::Distance(const vector *y) const
+{
+  double res = 0.;
+  for (int i=0;i<NDIM;i++)
+    res += (x[i]-y->x[i])*(x[i]-y->x[i]);
+  return (res);  
+};
+
+/** Calculates distance between this and another vector in a periodic cell.
+ * \param *y array to second vector
+ * \param *cell_size 6-dimensional array with (xx, xy, yy, xz, yz, zz) entries specifying the periodic cell
+ * \return \f$| x - y |^2\f$
+ */
+double vector::PeriodicDistance(const vector *y, const double *cell_size) const
+{
+  double res = Distance(y), tmp, matrix[NDIM*NDIM];
+  vector Shiftedy, TranslationVector;
+  int N[NDIM];
+  matrix[0] = cell_size[0];
+  matrix[1] = cell_size[1];
+  matrix[2] = cell_size[3];
+  matrix[3] = cell_size[1];
+  matrix[4] = cell_size[2];
+  matrix[5] = cell_size[4];
+  matrix[6] = cell_size[3];
+  matrix[7] = cell_size[4];
+  matrix[8] = cell_size[5];
+  // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
+  for (N[0]=-1;N[0]<=1;N[0]++)
+    for (N[1]=-1;N[1]<=1;N[1]++)
+      for (N[2]=-1;N[2]<=1;N[2]++) {
+        // create the translation vector
+        TranslationVector.Zero();
+        for (int i=0;i<NDIM;i++)
+          TranslationVector.x[i] = (double)N[i];
+        TranslationVector.MatrixMultiplication(matrix);
+        // add onto the original vector to compare with
+        Shiftedy.CopyVector(y);
+        Shiftedy.AddVector(&TranslationVector);
+        // get distance and compare with minimum so far
+        tmp = Distance(&Shiftedy);
+        if (tmp < res) res = tmp;
+      }
+  return (res);  
+};
+
+/** Keeps the vector in a periodic cell, defined by the symmetric \a *matrix.
+ * \param *out ofstream for debugging messages
+ * Tries to translate a vector into each adjacent neighbouring cell.
+ */
+void vector::KeepPeriodic(ofstream *out, double *matrix)
+{
+//  int N[NDIM];
+//  bool flag = false;
+  //vector Shifted, TranslationVector;
+  vector TestVector;
+  *out << Verbose(1) << "Begin of KeepPeriodic." << endl;
+  *out << Verbose(2) << "Vector is: ";
+  Output(out);
+  *out << endl;
+  TestVector.CopyVector(this);
+  TestVector.InverseMatrixMultiplication(matrix);
+  for(int i=0;i<NDIM;i++) { // correct periodically
+    if (TestVector.x[i] < 0) {  // get every coefficient into the interval [0,1)
+      TestVector.x[i] += ceil(TestVector.x[i]);
+    } else {
+      TestVector.x[i] -= floor(TestVector.x[i]);
+    }
+  }
+  TestVector.MatrixMultiplication(matrix);
+  CopyVector(&TestVector);
+  *out << Verbose(2) << "New corrected vector is: ";
+  Output(out);
+  *out << endl;
+  *out << Verbose(1) << "End of KeepPeriodic." << endl;
+};
+
+/** Calculates scalar product between this and another vector.
+ * \param *y array to second vector
+ * \return \f$\langle x, y \rangle\f$
+ */
+double vector::ScalarProduct(const vector *y) const
+{
+  double res = 0.;
+  for (int i=0;i<NDIM;i++)
+    res += x[i]*y->x[i];
+  return (res);  
+};
+
+/** Calculates the projection of a vector onto another \a *y.
+ * \param *y array to second vector
+ * \return \f$\langle x, y \rangle\f$
+ */
+double vector::Projection(const vector *y) const
+{
+  return (ScalarProduct(y)/Norm()/y->Norm());
+};
+
+/** Calculates norm of this vector.
+ * \return \f$|x|\f$
+ */
+double vector::Norm() const
+{
+  double res = 0.;
+  for (int i=0;i<NDIM;i++)
+    res += this->x[i]*this->x[i];
+  return (sqrt(res));  
+};
+
+/** Normalizes this vector.
+ */
+void vector::Normalize()
+{
+  double res = 0.;
+  for (int i=0;i<NDIM;i++)
+    res += this->x[i]*this->x[i];
+  res = 1./sqrt(res);
+  Scale(&res);
+};
+
+/** Zeros all components of this vector.
+ */
+void vector::Zero()
+{
+  for (int i=0;i<NDIM;i++)
+    this->x[i] = 0.;
+};
+
+/** Calculates the angle between this and another vector.
+ * \param *y array to second vector
+ * \return \f$\frac{\langle x, y \rangle}{|x||y|}\f$
+ */
+double vector::Angle(vector *y) const
+{
+  return (this->ScalarProduct(y)/(this->Norm()*y->Norm()));
+};
+
+/** Rotates the vector around the axis given by \a *axis by an angle of \a alpha.
+ * \param *axis rotation axis
+ * \param alpha rotation angle in radian
+ */
+void vector::RotateVector(const vector *axis, const double alpha)
+{
+  vector a,y;
+  // normalise this vector with respect to axis
+  a.CopyVector(this);
+  a.Scale(Projection(axis));
+  SubtractVector(&a);
+  // construct normal vector
+  y.MakeNormalVector(axis,this);
+  y.Scale(Norm());
+  // scale normal vector by sine and this vector by cosine
+  y.Scale(sin(alpha));
+  Scale(cos(alpha));
+  // add scaled normal vector onto this vector
+  AddVector(&y);
+  // add part in axis direction
+  AddVector(&a);
+};
+
+/** Prints a 3dim vector.
+ * prints no end of line.
+ * \param *out output stream
+ */
+bool vector::Output(ofstream *out) const
+{
+  if (out != NULL) {
+    *out << "(";
+    for (int i=0;i<NDIM;i++) {
+      *out << x[i];
+      if (i != 2)
+        *out << ",";
+    }
+    *out << ")";
+    return true;
+  } else
+    return false;
+};
+
+ofstream& operator<<(ofstream& ost,vector& m)
+{
+	m.Output(&ost);
+	return ost;
+};
+
+/** Scales each atom coordinate by an individual \a factor.
+ * \param *factor pointer to scaling factor
+ */
+void vector::Scale(double **factor)
+{
+  for (int i=0;i<NDIM;i++)
+    this->x[i] *= (*factor)[i];
+};
+
+void vector::Scale(double *factor)
+{
+  for (int i=0;i<NDIM;i++)
+    this->x[i] *= *factor;
+};
+
+void vector::Scale(double factor)
+{
+  for (int i=0;i<NDIM;i++)
+    this->x[i] *= factor;
+};
+
+/** Translate atom by given vector. 
+ * \param trans[] translation vector.
+ */
+void vector::Translate(const vector *trans)
+{
+  for (int i=0;i<NDIM;i++)
+    x[i] += trans->x[i];
+}; 
+
+/** Do a matrix multiplication.
+ * \param *matrix NDIM_NDIM array
+ */
+void vector::MatrixMultiplication(double *M)
+{
+  vector C;
+  // do the matrix multiplication
+  C.x[0] = M[0]*x[0]+M[3]*x[1]+M[6]*x[2];
+  C.x[1] = M[1]*x[0]+M[4]*x[1]+M[7]*x[2];
+  C.x[2] = M[2]*x[0]+M[5]*x[1]+M[8]*x[2];
+  // transfer the result into this
+  for (int i=0;i<NDIM;i++)
+    x[i] = C.x[i];
+};
+
+/** Do a matrix multiplication with \a *matrix' inverse.
+ * \param *matrix NDIM_NDIM array
+ */
+void vector::InverseMatrixMultiplication(double *A)
+{
+  vector C;
+  double B[NDIM*NDIM];
+  double detA = RDET3(A);
+  double detAReci;
+
+  // calculate the inverse B
+  if (fabs(detA) > MYEPSILON) {;  // RDET3(A) yields precisely zero if A irregular
+    detAReci = 1./detA;
+    B[0] =  detAReci*RDET2(A[4],A[5],A[7],A[8]);    // A_11
+    B[1] = -detAReci*RDET2(A[1],A[2],A[7],A[8]);    // A_12
+    B[2] =  detAReci*RDET2(A[1],A[2],A[4],A[5]);    // A_13
+    B[3] = -detAReci*RDET2(A[3],A[5],A[6],A[8]);    // A_21
+    B[4] =  detAReci*RDET2(A[0],A[2],A[6],A[8]);    // A_22
+    B[5] = -detAReci*RDET2(A[0],A[2],A[3],A[5]);    // A_23
+    B[6] =  detAReci*RDET2(A[3],A[4],A[6],A[7]);    // A_31
+    B[7] = -detAReci*RDET2(A[0],A[1],A[6],A[7]);    // A_32
+    B[8] =  detAReci*RDET2(A[0],A[1],A[3],A[4]);    // A_33
+  
+    // do the matrix multiplication
+    C.x[0] = B[0]*x[0]+B[3]*x[1]+B[6]*x[2];
+    C.x[1] = B[1]*x[0]+B[4]*x[1]+B[7]*x[2];
+    C.x[2] = B[2]*x[0]+B[5]*x[1]+B[8]*x[2];
+    // transfer the result into this
+    for (int i=0;i<NDIM;i++)
+      x[i] = C.x[i];
+  } else {
+    cerr << "ERROR: inverse of matrix does not exists!" << endl;
+  }
+};
+
+
+/** Creates this vector as the b y *factors' components scaled linear combination of the given three.
+ * this vector = x1*factors[0] + x2* factors[1] + x3*factors[2]
+ * \param *x1 first vector
+ * \param *x2 second vector
+ * \param *x3 third vector
+ * \param *factors three-component vector with the factor for each given vector
+ */
+void vector::LinearCombinationOfVectors(const vector *x1, const vector *x2, const vector *x3, double *factors)
+{
+  for(int i=0;i<NDIM;i++)
+    x[i] = factors[0]*x1->x[i] + factors[1]*x2->x[i] + factors[2]*x3->x[i]; 
+};
+
+/** Mirrors atom against a given plane. 
+ * \param n[] normal vector of mirror plane.
+ */
+void vector::Mirror(const vector *n)
+{
+  double projection;
+  projection = ScalarProduct(n)/((vector *)n)->ScalarProduct(n);    // remove constancy from n (keep as logical one)
+  // withdraw projected vector twice from original one
+  cout << Verbose(1) << "Vector: ";
+  Output((ofstream *)&cout);
+  cout << "\t";
+  for (int i=0;i<NDIM;i++)
+    x[i] -= 2.*projection*n->x[i];
+  cout << "Projected vector: ";
+  Output((ofstream *)&cout);
+  cout << endl;
+}; 
+
+/** Calculates normal vector for three given vectors (being three points in space).
+ * Makes this vector orthonormal to the three given points, making up a place in 3d space.
+ * \param *y1 first vector
+ * \param *y2 second vector
+ * \param *y3 third vector
+ * \return true - success, vectors are linear independent, false - failure due to linear dependency
+ */
+bool vector::MakeNormalVector(const vector *y1, const vector *y2, const vector *y3)
+{
+  vector x1, x2;
+
+  x1.CopyVector(y1);
+  x1.SubtractVector(y2);
+  x2.CopyVector(y3);
+  x2.SubtractVector(y2);
+  if ((x1.Norm()==0) || (x2.Norm()==0)) {
+    cout << Verbose(4) << "Given vectors are linear dependent." << endl;
+    return false;
+  }
+  cout << Verbose(4) << "relative, first plane coordinates:";
+  x1.Output((ofstream *)&cout);
+  cout << endl;
+  cout << Verbose(4) << "second plane coordinates:";
+  x2.Output((ofstream *)&cout);
+  cout << endl;
+
+  this->x[0] = (x1.x[1]*x2.x[2] - x1.x[2]*x2.x[1]);
+  this->x[1] = (x1.x[2]*x2.x[0] - x1.x[0]*x2.x[2]);
+  this->x[2] = (x1.x[0]*x2.x[1] - x1.x[1]*x2.x[0]);
+  Normalize();
+  
+  return true;
+};
+
+
+/** Calculates orthonormal vector to two given vectors.
+ * Makes this vector orthonormal to two given vectors. This is very similar to the other
+ * vector::MakeNormalVector(), only there three points whereas here two difference
+ * vectors are given.
+ * \param *x1 first vector
+ * \param *x2 second vector
+ * \return true - success, vectors are linear independent, false - failure due to linear dependency
+ */
+bool vector::MakeNormalVector(const vector *y1, const vector *y2)
+{
+  vector x1,x2;
+  x1.CopyVector(y1);
+  x2.CopyVector(y2);
+  Zero();
+  if ((x1.Norm()==0) || (x2.Norm()==0)) {
+    cout << Verbose(4) << "Given vectors are linear dependent." << endl;
+    return false;
+  }
+  cout << Verbose(4) << "relative, first plane coordinates:";
+  x1.Output((ofstream *)&cout);
+  cout << endl;
+  cout << Verbose(4) << "second plane coordinates:";
+  x2.Output((ofstream *)&cout);
+  cout << endl;
+
+  this->x[0] = (x1.x[1]*x2.x[2] - x1.x[2]*x2.x[1]);
+  this->x[1] = (x1.x[2]*x2.x[0] - x1.x[0]*x2.x[2]);
+  this->x[2] = (x1.x[0]*x2.x[1] - x1.x[1]*x2.x[0]);
+  Normalize();
+
+  return true;
+};
+
+/** Calculates orthonormal vector to one given vectors.
+ * Just subtracts the projection onto the given vector from this vector.
+ * \param *x1 vector
+ * \return true - success, false - vector is zero
+ */
+bool vector::MakeNormalVector(const vector *y1)
+{
+	bool result = false;
+  vector x1;
+  x1.CopyVector(y1);
+  x1.Scale(x1.Projection(this));
+  SubtractVector(&x1);
+  for (int i=0;i<NDIM;i++)
+	  result = result || (fabs(x[i]) > MYEPSILON);
+
+  return result;
+};
+
+/** Creates this vector as one of the possible orthonormal ones to the given one.
+ * Just scan how many components of given *vector are unequal to zero and
+ * try to get the skp of both to be zero accordingly.  
+ * \param *vector given vector
+ * \return true - success, false - failure (null vector given)
+ */
+bool vector::GetOneNormalVector(const vector *vector)
+{
+  int Components[NDIM]; // contains indices of non-zero components
+  int Last = 0;   // count the number of non-zero entries in vector
+  int j;  // loop variables
+  double norm;
+
+  cout << Verbose(4);
+  vector->Output((ofstream *)&cout);
+  cout << endl;
+  for (j=0;j<NDIM;j++)
+    Components[j] = -1;
+  // find two components != 0
+  for (j=0;j<NDIM;j++)
+    if (fabs(vector->x[j]) > MYEPSILON)
+      Components[Last++] = j;
+  cout << Verbose(4) << Last << " Components != 0: (" << Components[0] << "," << Components[1] << "," << Components[2] << ")" << endl;
+        
+  switch(Last) {
+    case 3:  // threecomponent system
+    case 2:  // two component system
+      norm = sqrt(1./(vector->x[Components[1]]*vector->x[Components[1]]) + 1./(vector->x[Components[0]]*vector->x[Components[0]]));
+      x[Components[2]] = 0.;
+      // in skp both remaining parts shall become zero but with opposite sign and third is zero
+      x[Components[1]] = -1./vector->x[Components[1]] / norm;
+      x[Components[0]] = 1./vector->x[Components[0]] / norm;
+      return true;
+      break;
+    case 1: // one component system
+      // set sole non-zero component to 0, and one of the other zero component pendants to 1
+      x[(Components[0]+2)%NDIM] = 0.;   
+      x[(Components[0]+1)%NDIM] = 1.;   
+      x[Components[0]] = 0.;   
+      return true;
+      break;
+    default:
+      return false;
+  }
+};
+
+/** Creates a new vector as the one with least square distance to a given set of \a vectors.
+ * \param *vectors set of vectors
+ * \param num number of vectors
+ * \return true if success, false if failed due to linear dependency
+ */
+bool vector::LSQdistance(vector **vectors, int num) 
+{
+	int j;
+				
+	for (j=0;j<num;j++) {
+		cout << Verbose(1) << j << "th atom's vector: ";
+		(vectors[j])->Output((ofstream *)&cout);
+		cout << endl;
+	}
+
+  int np = 3;
+	struct LSQ_params par;
+    
+   const gsl_multimin_fminimizer_type *T =
+     gsl_multimin_fminimizer_nmsimplex;
+   gsl_multimin_fminimizer *s = NULL;
+   gsl_vector *ss, *x;
+   gsl_multimin_function minex_func;
+ 
+   size_t iter = 0, i;
+   int status;
+   double size;
+ 
+   /* Initial vertex size vector */
+   ss = gsl_vector_alloc (np);
+   x = gsl_vector_alloc (np);
+ 
+   /* Set all step sizes to 1 */
+   gsl_vector_set_all (ss, 1.0);
+ 
+   /* Starting point */
+   par.vectors = vectors;
+	 par.num = num;
+	
+	 for (i=0;i<NDIM;i++)
+		gsl_vector_set(x, i, (vectors[0]->x[i] - vectors[1]->x[i])/2.); 
+	 
+   /* Initialize method and iterate */
+   minex_func.f = &LSQ;
+   minex_func.n = np;
+   minex_func.params = (void *)&par;
+ 
+   s = gsl_multimin_fminimizer_alloc (T, np);
+   gsl_multimin_fminimizer_set (s, &minex_func, x, ss);
+ 
+   do
+     {
+       iter++;
+       status = gsl_multimin_fminimizer_iterate(s);
+ 
+       if (status)
+         break;
+ 
+       size = gsl_multimin_fminimizer_size (s);
+       status = gsl_multimin_test_size (size, 1e-2);
+ 
+       if (status == GSL_SUCCESS)
+         {
+           printf ("converged to minimum at\n");
+         }
+ 
+       printf ("%5d ", (int)iter);
+       for (i = 0; i < (size_t)np; i++)
+         {
+           printf ("%10.3e ", gsl_vector_get (s->x, i));
+         }
+       printf ("f() = %7.3f size = %.3f\n", s->fval, size);
+     }
+   while (status == GSL_CONTINUE && iter < 100);
+ 
+  for (i=0;i<(size_t)np;i++)
+    this->x[i] = gsl_vector_get(s->x, i);
+   gsl_vector_free(x);
+   gsl_vector_free(ss);
+   gsl_multimin_fminimizer_free (s);
+
+	return true;
+};
+
+/** Adds vector \a *y componentwise.
+ * \param *y vector
+ */
+void vector::AddVector(const vector *y)
+{
+  for (int i=0;i<NDIM;i++)
+    this->x[i] += y->x[i];
+}
+
+/** Adds vector \a *y componentwise.
+ * \param *y vector
+ */
+void vector::SubtractVector(const vector *y)
+{
+  for (int i=0;i<NDIM;i++)
+    this->x[i] -= y->x[i];
+}
+
+/** Copy vector \a *y componentwise.
+ * \param *y vector
+ */
+void vector::CopyVector(const vector *y)
+{
+  for (int i=0;i<NDIM;i++)
+    this->x[i] = y->x[i];
+}
+
+
+/** Asks for position, checks for boundary.
+ * \param cell_size unitary size of cubic cell, coordinates must be within 0...cell_size
+ * \param check whether bounds shall be checked (true) or not (false)
+ */
+void vector::AskPosition(double *cell_size, bool check)
+{
+  char coords[3] = {'x','y','z'};
+  int j = -1;
+  for (int i=0;i<3;i++) {
+    j += i+1;
+    do {
+      cout << Verbose(0) << coords[i] << "[0.." << cell_size[j] << "]: ";
+      cin >> x[i];
+    } while (((x[i] < 0) || (x[i] >= cell_size[j])) && (check));
+  }
+};
+
+/** Solves a vectorial system consisting of two orthogonal statements and a norm statement.
+ * This is linear system of equations to be solved, however of the three given (skp of this vector\
+ * with either of the three hast to be zero) only two are linear independent. The third equation
+ * is that the vector should be of magnitude 1 (orthonormal). This all leads to a case-based solution
+ * where very often it has to be checked whether a certain value is zero or not and thus forked into
+ * another case.
+ * \param *x1 first vector
+ * \param *x2 second vector
+ * \param *y third vector
+ * \param alpha first angle
+ * \param beta second angle
+ * \param c norm of final vector 
+ * \return a vector with \f$\langle x1,x2 \rangle=A\f$, \f$\langle x1,y \rangle = B\f$ and with norm \a c.
+ * \bug this is not yet working properly 
+ */
+bool vector::SolveSystem(vector *x1, vector *x2, vector *y, double alpha, double beta, double c)
+{
+  double D1,D2,D3,E1,E2,F1,F2,F3,p,q=0., A, B1, B2, C;
+  double ang; // angle on testing
+  double sign[3];
+  int i,j,k;
+  A = cos(alpha) * x1->Norm() * c;
+  B1 = cos(beta + M_PI/2.) * y->Norm() * c;
+  B2 = cos(beta) * x2->Norm() * c;
+  C = c * c;
+  cout << Verbose(2) << "A " << A << "\tB " << B1 << "\tC " << C << endl;
+  int flag = 0;
+  if (fabs(x1->x[0]) < MYEPSILON) { // check for zero components for the later flipping and back-flipping
+    if (fabs(x1->x[1]) > MYEPSILON) {
+      flag = 1;    
+    } else if (fabs(x1->x[2]) > MYEPSILON) {
+       flag = 2;
+    } else {
+      return false;
+    }
+  }
+  switch (flag) {
+    default:
+    case 0:
+      break;
+    case 2:
+      flip(&x1->x[0],&x1->x[1]);
+      flip(&x2->x[0],&x2->x[1]);
+      flip(&y->x[0],&y->x[1]);
+      //flip(&x[0],&x[1]);
+      flip(&x1->x[1],&x1->x[2]);
+      flip(&x2->x[1],&x2->x[2]);
+      flip(&y->x[1],&y->x[2]);
+      //flip(&x[1],&x[2]);
+    case 1:
+      flip(&x1->x[0],&x1->x[1]);
+      flip(&x2->x[0],&x2->x[1]);
+      flip(&y->x[0],&y->x[1]);
+      //flip(&x[0],&x[1]);
+      flip(&x1->x[1],&x1->x[2]);
+      flip(&x2->x[1],&x2->x[2]);
+      flip(&y->x[1],&y->x[2]);
+      //flip(&x[1],&x[2]);
+      break;
+  }
+  // now comes the case system
+  D1 = -y->x[0]/x1->x[0]*x1->x[1]+y->x[1];
+  D2 = -y->x[0]/x1->x[0]*x1->x[2]+y->x[2]; 
+  D3 = y->x[0]/x1->x[0]*A-B1;
+  cout << Verbose(2) << "D1 " << D1 << "\tD2 " << D2 << "\tD3 " << D3 << "\n";
+  if (fabs(D1) < MYEPSILON) {
+    cout << Verbose(2) << "D1 == 0!\n"; 
+    if (fabs(D2) > MYEPSILON) {
+      cout << 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];
+      cout << Verbose(3) << "E1 " << E1 << "\tE2 " << E2 << "\n";
+      F1 = E1*E1 + 1.;
+      F2 = -E1*E2;
+      F3 = E1*E1 + D3*D3/(D2*D2) - C;
+      cout << Verbose(3) << "F1 " << F1 << "\tF2 " << F2 << "\tF3 " << F3 << "\n";
+      if (fabs(F1) < MYEPSILON) {
+        cout << Verbose(4) << "F1 == 0!\n"; 
+        cout << Verbose(4) << "Gleichungssystem linear\n";
+        x[1] = F3/(2.*F2); 
+      } else {
+        p = F2/F1;
+        q = p*p - F3/F1;
+        cout << Verbose(4) << "p " << p << "\tq " << q << endl;  
+        if (q < 0) {
+          cout << Verbose(4) << "q < 0" << endl;
+          return false;
+        }
+        x[1] = p + sqrt(q);
+      }
+      x[0] =  A/x1->x[0] - x1->x[1]/x1->x[0]*x[1] + x1->x[2]/x1->x[0]*x[2];
+    } else {
+      cout << Verbose(2) << "Gleichungssystem unterbestimmt\n";
+      return false;
+    }
+  } else {
+    E1 = A/x1->x[0]+x1->x[1]/x1->x[0]*D3/D1;
+    E2 = x1->x[1]/x1->x[0]*D2/D1 - x1->x[2];
+    cout << 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;
+    cout << Verbose(2) << "F1 " << F1 << "\tF2 " << F2 << "\tF3 " << F3 << "\n";
+    if (fabs(F1) < MYEPSILON) {
+      cout << Verbose(3) << "F1 == 0!\n"; 
+      cout << Verbose(3) << "Gleichungssystem linear\n";
+      x[2] = F3/(2.*F2);     
+    } else {
+      p = F2/F1;
+      q = p*p - F3/F1;
+      cout << Verbose(3) << "p " << p << "\tq " << q << endl;  
+      if (q < 0) {
+        cout << Verbose(3) << "q < 0" << endl;
+        return false;
+      }
+      x[2] = p + sqrt(q);
+    }
+    x[1] = (-D2 * x[2] - D3)/D1;
+    x[0] = A/x1->x[0] - x1->x[1]/x1->x[0]*x[1] + x1->x[2]/x1->x[0]*x[2];
+  }
+  switch (flag) { // back-flipping
+    default:
+    case 0:
+      break;
+    case 2:
+      flip(&x1->x[0],&x1->x[1]);
+      flip(&x2->x[0],&x2->x[1]);
+      flip(&y->x[0],&y->x[1]);
+      flip(&x[0],&x[1]);
+      flip(&x1->x[1],&x1->x[2]);
+      flip(&x2->x[1],&x2->x[2]);
+      flip(&y->x[1],&y->x[2]);
+      flip(&x[1],&x[2]);
+    case 1:
+      flip(&x1->x[0],&x1->x[1]);
+      flip(&x2->x[0],&x2->x[1]);
+      flip(&y->x[0],&y->x[1]);
+      //flip(&x[0],&x[1]);
+      flip(&x1->x[1],&x1->x[2]);
+      flip(&x2->x[1],&x2->x[2]);
+      flip(&y->x[1],&y->x[2]);
+      flip(&x[1],&x[2]);
+      break;
+  }
+  // one z component is only determined by its radius (without sign)
+  // thus check eight possible sign flips and determine by checking angle with second vector
+  for (i=0;i<8;i++) {
+    // set sign vector accordingly
+    for (j=2;j>=0;j--) {
+      k = (i & pot(2,j)) << j;
+      cout << Verbose(2) << "k " << k << "\tpot(2,j) " << pot(2,j) << endl;
+      sign[j] = (k == 0) ? 1. : -1.;
+    }
+    cout << Verbose(2) << i << ": sign matrix is " << sign[0] << "\t" << sign[1] << "\t" << sign[2] << "\n";
+    // apply sign matrix 
+    for (j=0;j<NDIM;j++)
+      x[j] *= sign[j];
+    // calculate angle and check
+    ang = x2->Angle (this);
+    cout << Verbose(1) << i << "th angle " << ang << "\tbeta " << cos(beta) << " :\t";
+    if (fabs(ang - cos(beta)) < MYEPSILON) {  
+      break;
+    }
+    // unapply sign matrix (is its own inverse)
+    for (j=0;j<NDIM;j++)
+      x[j] *= sign[j];
+  }
+  return true;
+};
Index: molecuilder/src/verbose.cpp
===================================================================
--- molecuilder/src/verbose.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
+++ molecuilder/src/verbose.cpp	(revision a0bcf15381c41adb281e0a5d9293f02515ba70c0)
@@ -0,0 +1,59 @@
+#include "molecules.hpp"
+
+/** Prints the tabs according to verbosity stored in the temporary constructed class.
+ * \param &ost stream to extend with tabs
+ * \return &ost stream with tabs
+ */
+ostream& Verbose::print (ostream &ost) const
+{
+  for (int i=0;i<Verbosity;i++)
+    ost.put('\t');
+  //cout << "Verbose(.) called." << endl;
+  return ost;
+};
+
+/** Operator for the Verbose(arg) call.
+ * Constructs temporary a Verbose class object, wherein the verbosity is stored.
+ * Then << is called, which calls Verbose's print which adds the tabs and returns the stream.
+ * \param &ost stream to extend
+ * \param &m pointer to created Verbose object
+ * \return &ost
+ */ 
+ostream& operator<<(ostream& ost,const Verbose& m)
+{
+	return m.print(ost);
+};
+
+
+/** Prints the tabs according to verbosity stored in the temporary constructed class.
+ * Note that highest bit is set artificially to give number of bits to print
+ * \param &ost stream to extend with tabs
+ * \return &ost stream with tabs
+ */
+ostream& Binary::print (ostream &ost) const
+{
+	int bits = 1, counter = 1;
+	while ((bits = 1 << counter) < BinaryNumber)
+    counter++;
+  for (int i=0;i<counter-1;i++) {
+  	if ((BinaryNumber & (1 << i)) == 0)
+  		ost.put('0');
+ 		else
+  		ost.put('1');
+  }
+  ost.put('b');
+  //cout << "Binary(.) called." << endl;
+  return ost;
+};
+
+/** Operator for the Binary(arg) call.
+ * Constructs temporary a Verbose class object, wherein the Binary is stored.
+ * Then << is called, which calls Binary's print which adds the tabs and returns the stream.
+ * \param &ost stream to extend
+ * \param &m pointer to created Binary object
+ * \return &ost
+ */ 
+ostream& operator<<(ostream& ost,const Binary& m)
+{
+	return m.print(ost);
+};
