Index: src/Makefile.am
===================================================================
--- src/Makefile.am	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/Makefile.am	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -1,3 +1,3 @@
-SOURCE = atom.cpp bond.cpp boundary.cpp builder.cpp config.cpp element.cpp ellipsoid.cpp helpers.cpp molecules.cpp linkedcell.cpp moleculelist.cpp parser.cpp periodentafel.cpp vector.cpp verbose.cpp
+SOURCE = atom.cpp bond.cpp boundary.cpp builder.cpp config.cpp element.cpp ellipsoid.cpp helpers.cpp linkedcell.cpp moleculelist.cpp molecules.cpp parser.cpp periodentafel.cpp vector.cpp verbose.cpp
 HEADER = boundary.hpp defs.hpp ellipsoid.hpp helpers.hpp linkedcell.hpp molecules.hpp parser.hpp periodentafel.hpp stackclass.hpp vector.hpp
 
@@ -10,3 +10,3 @@
 
 
-#EXTRA_DIST = ${molecuilder_DATA}
+EXTRA_DIST = ${molecuilder_DATA}
Index: src/analyzer.cpp
===================================================================
--- src/analyzer.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/analyzer.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -23,405 +23,539 @@
 int main(int argc, char **argv)
 {
-	periodentafel *periode = NULL; // and a period table of all elements
-	EnergyMatrix Energy;
-	EnergyMatrix Hcorrection;
-	ForceMatrix Force;
-	ForceMatrix Shielding;
-	ForceMatrix ShieldingPAS;
-	EnergyMatrix Time;
-	EnergyMatrix EnergyFragments;
-	EnergyMatrix HcorrectionFragments;
-	ForceMatrix ForceFragments;
-	ForceMatrix ShieldingFragments;
-	ForceMatrix ShieldingPASFragments;
-	KeySetsContainer KeySet;
-	ofstream output;
-	ofstream output2;
-	ofstream output3;
-	ofstream output4;
-	ifstream input;
-	stringstream filename;
-	time_t t = time(NULL);
-	struct tm *ts = localtime(&t);
-	char *datum = asctime(ts);
-	stringstream Orderxrange;
-	stringstream Fragmentxrange;
-	stringstream yrange;
-	char *dir = NULL;
-	bool Hcorrected = true;
-	int counter;
-
-	cout << "ANOVA Analyzer" << endl;
-	cout << "==============" << endl;
-
-	// Get the command line options
-	if (argc < 4) {
-		cout << "Usage: " << argv[0] << " <inputdir> <prefix> <outputdir> [elementsdb]" << 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;
-		cout << "[elementsdb]\tpath to elements database, needed for shieldings." << endl;
-		return 1;
-	} else {
-		dir = (char *) Malloc(sizeof(char)*(strlen(argv[2])+2), "main: *dir");
-		strcpy(dir, "/");
-		strcat(dir, argv[2]);
-	}
-
-	if (argc > 4) {
-		cout << "Loading periodentafel." << endl;
-		periode = new periodentafel;
-		periode->LoadPeriodentafel(argv[4]);
-	}
-
-	// Test the given directory
-	if (!TestParams(argc, argv))
-		return 1;
-
-	// +++++++++++++++++ PARSING +++++++++++++++++++++++++++++++
-
-	// ------------- Parse through all Fragment subdirs --------
-	if (!Energy.ParseFragmentMatrix(argv[1], dir, EnergySuffix,0,0)) return 1;
-	Hcorrected = Hcorrection.ParseFragmentMatrix(argv[1], "", HCORRECTIONSUFFIX,0,0);
-	if (!Force.ParseFragmentMatrix(argv[1], dir, ForcesSuffix,0,0)) return 1;
-	if (!Time.ParseFragmentMatrix(argv[1], dir, TimeSuffix, 10,1)) return 1;
-	if (periode != NULL) { // also look for PAS values
-		if (!Shielding.ParseFragmentMatrix(argv[1], dir, ShieldingSuffix, 1, 0)) return 1;
-		if (!ShieldingPAS.ParseFragmentMatrix(argv[1], dir, ShieldingPASSuffix, 1, 0)) return 1;
-	}
-
-	// ---------- Parse the TE Factors into an array -----------------
-	if (!Energy.ParseIndices()) return 1;
-	if (Hcorrected) Hcorrection.ParseIndices();
-
-	// ---------- Parse the Force indices into an array ---------------
-	if (!Force.ParseIndices(argv[1])) return 1;
-	if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return 1;
-	if (!ForceFragments.ParseIndices(argv[1])) return 1;
-
-	// ---------- Parse the shielding indices into an array ---------------
-	if (periode != NULL) { // also look for PAS values
-		if(!Shielding.ParseIndices(argv[1])) return 1;
-		if(!ShieldingPAS.ParseIndices(argv[1])) return 1;
-		if (!ShieldingFragments.AllocateMatrix(Shielding.Header, Shielding.MatrixCounter, Shielding.RowCounter, Shielding.ColumnCounter)) return 1;
-		if (!ShieldingPASFragments.AllocateMatrix(ShieldingPAS.Header, ShieldingPAS.MatrixCounter, ShieldingPAS.RowCounter, ShieldingPAS.ColumnCounter)) return 1;
-		if(!ShieldingFragments.ParseIndices(argv[1])) return 1;
-		if(!ShieldingPASFragments.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;
-
-	// ---------- Parse fragment files created by 'joiner' into an array -------------
-	if (!EnergyFragments.ParseFragmentMatrix(argv[1], dir, EnergyFragmentSuffix,0,0)) return 1;
-	if (Hcorrected) HcorrectionFragments.ParseFragmentMatrix(argv[1], dir, HcorrectionFragmentSuffix,0,0);
-	if (!ForceFragments.ParseFragmentMatrix(argv[1], dir, ForceFragmentSuffix,0,0)) return 1;
-	if (periode != NULL) { // also look for PAS values
-		if (!ShieldingFragments.ParseFragmentMatrix(argv[1], dir, ShieldingFragmentSuffix, 1, 0)) return 1;
-		if (!ShieldingPASFragments.ParseFragmentMatrix(argv[1], dir, ShieldingPASFragmentSuffix, 1, 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;
-
-	if (periode != NULL) { // also look for PAS values
-		output << endl << "Total Shieldings" << endl << "===============" << endl << Shielding.Header << endl;
-		for(int j=0;j<Shielding.RowCounter[Shielding.MatrixCounter];j++) {
-			for(int k=0;k<Shielding.ColumnCounter;k++)
-				output << scientific << Shielding.Matrix[ Shielding.MatrixCounter ][j][k] << "\t";
-			output << endl;
-		}
-		output << endl;
-
-		output << endl << "Total Shieldings PAS" << endl << "===============" << endl << ShieldingPAS.Header << endl;
-		for(int j=0;j<ShieldingPAS.RowCounter[ShieldingPAS.MatrixCounter];j++) {
-			for(int k=0;k<ShieldingPAS.ColumnCounter;k++)
-				output << scientific << ShieldingPAS.Matrix[ ShieldingPAS.MatrixCounter ][j][k] << "\t";
-			output << endl;
-		}
-		output << endl;
-	}
-
-	output << endl << "Total Times" << endl << "===============" << endl << Time.Header << endl;
-	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();
-	for(int k=0;k<Time.ColumnCounter;k++)
-		Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter] ][k] = Time.Matrix[ Time.MatrixCounter ][Time.RowCounter[Time.MatrixCounter]-1][k];
-
-	// +++++++++++++++ ANALYZING ++++++++++++++++++++++++++++++
-
-	cout << "Analyzing ..." << endl;
-
-	// ======================================= Creating the data files ==============================================================
-
-	// +++++++++++++++++++++++++++++++++++++++ Plotting Simtime vs Bond Order
-	// +++++++++++++++++++++++++++++++++++++++ Plotting Delta Simtime vs Bond Order
-	if (!OpenOutputFile(output, argv[3], "SimTime-Order.dat" )) return false;
-	if (!OpenOutputFile(output2, argv[3], "DeltaSimTime-Order.dat" )) return false;
-	for(int j=Time.RowCounter[Time.MatrixCounter];j--;)
-		for(int k=Time.ColumnCounter;k--;) {
-			Time.Matrix[ Time.MatrixCounter ][j][k] = 0.;
-		}
-	counter = 0;
-	output << "#Order\tFrag.No.\t" << Time.Header << endl;
-	output2 << "#Order\tFrag.No.\t" << Time.Header << endl;
-	for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
-		for(int i=KeySet.FragmentsPerOrder[BondOrder];i--;)
-			for(int j=Time.RowCounter[Time.MatrixCounter];j--;)
-				for(int k=Time.ColumnCounter;k--;) {
-					Time.Matrix[ Time.MatrixCounter ][j][k] += Time.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
-				}
-		counter += KeySet.FragmentsPerOrder[BondOrder];
-		output << BondOrder+1 << "\t" << counter;
-		output2 << BondOrder+1 << "\t" << counter;
-		for(int k=0;k<Time.ColumnCounter;k++) {
-			output << "\t" << scientific << Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter]-1 ][k];
-			if (fabs(Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter] ][k]) > MYEPSILON)
-				output2 << "\t" << scientific << Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter]-1 ][k] / Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter] ][k];
-			else
-				output2 << "\t" << scientific << Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter]-1 ][k];
-		}
-		output << endl;
-		output2 << endl;
-	}
-	output.close();
-	output2.close();
-
-	// +++++++++++++++++++++++++++++++++++++++ Plotting shieldings
-
-	if (periode != NULL) { // also look for PAS values
-		if (!CreateDataDeltaForcesOrderPerAtom(ShieldingPAS, ShieldingPASFragments, KeySet, argv[3], "DeltaShieldingsPAS-Order", "Plot of error between approximated shieldings and full shieldings versus the Bond Order", datum)) return 1;
-		if (!CreateDataForcesOrderPerAtom(ShieldingPASFragments, KeySet, argv[3], "ShieldingsPAS-Order", "Plot of approximated shieldings versus the Bond Order", datum)) return 1;
-		if (!AppendOutputFile(output, argv[3], "ShieldingsPAS-Order.dat" )) return false;
-		output << endl << "# Full" << endl;
-		for(int j=0;j<ShieldingPAS.RowCounter[ShieldingPAS.MatrixCounter];j++) {
-			output << j << "\t";
-			for(int k=0;k<ShieldingPAS.ColumnCounter;k++)
-				output << scientific <<	ShieldingPAS.Matrix[ ShieldingPAS.MatrixCounter ][j][k] << "\t"; //*(((k>1) && (k<6))? 1.e6 : 1.) << "\t";
-			output << endl;
-		}
-	}
-	output.close();
-
-
-	// +++++++++++++++++++++++++++++++++++++++ Plotting deviation in energy to full QM
-	if (!CreateDataDeltaEnergyOrder(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 (!CreateDataEnergyOrder(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 (!CreateDataDeltaForcesOrderPerAtom(Force, ForceFragments, KeySet, argv[3], "DeltaForces-Order", "Plot of error between approximated forces and full forces versus the Bond Order", datum)) return 1;
-
-	// min force
-	if (!CreateDataDeltaForcesOrder(Force, ForceFragments, KeySet, argv[3], "DeltaMinForces-Order", "Plot of min error between approximated forces and full forces versus the Bond Order", datum, CreateMinimumForce)) return 1;
-
-	// mean force
-	if (!CreateDataDeltaForcesOrder(Force, ForceFragments, KeySet, argv[3], "DeltaMeanForces-Order", "Plot of mean error between approximated forces and full forces versus the Bond Order", datum, CreateMeanForce)) return 1;
-
-	// max force
-	if (!CreateDataDeltaForcesOrder(Force, ForceFragments, KeySet, argv[3], "DeltaMaxForces-Order", "Plot of max error between approximated forces and full forces versus the Bond Order", datum, CreateMaximumForce)) return 1;
-
-	// ++++++++++++++++++++++++++++++++++++++Plotting Forces vs. Order
-	if (!CreateDataForcesOrderPerAtom(ForceFragments, KeySet, argv[3], "Forces-Order", "Plot of approximated forces versus the Bond Order", datum)) return 1;
-	if (!AppendOutputFile(output, argv[3], "Forces-Order.dat" )) return false;
-	output << endl << "# Full" << endl;
-	for(int j=0;j<Force.RowCounter[Force.MatrixCounter];j++) {
-		output << j << "\t";
-		for(int k=0;k<Force.ColumnCounter;k++)
-			output << scientific <<	Force.Matrix[ Force.MatrixCounter ][j][k] << "\t";
-		output << endl;
-	}
-	output.close();
-	// min force
-	if (!CreateDataForcesOrder(ForceFragments, KeySet, argv[3], "MinForces-Order", "Plot of min approximated forces versus the Bond Order", datum, CreateMinimumForce)) return 1;
-
-	// mean force
-	if (!CreateDataForcesOrder(ForceFragments, KeySet, argv[3], "MeanForces-Order", "Plot of mean approximated forces versus the Bond Order", datum, CreateMeanForce)) return 1;
-
-	// max force
-	if (!CreateDataForcesOrder(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(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 << "]";
-	yrange.str("[1e-8:1e+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(), yrange.str().c_str(), "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
-	yrange.str("[1e-8:1e+0]");
-	// 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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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", NULL,	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", NULL, 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
-	yrange.str("");
-	yrange << "[" << EnergyFragments.FindMinValue() << ":" << EnergyFragments.FindMaxValue() << "]";
-	if (!CreatePlotOrder(EnergyFragments, KeySet, argv[3], "Energies-Fragment", 5, "below", "y", "", 1, 5, "fragment number", "Energies of each fragment [Ht]", Fragmentxrange.str().c_str(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "1" , "with linespoints", AbsEnergyPlotLine)) return 1;
-
-	// +++++++++++++++++++++++++++++++=Ploting min/mean/max forces for each fragment
-	yrange.str("");
-	yrange << "[" << ForceFragments.FindMinValue() << ":" << ForceFragments.FindMaxValue()<< "]";
-	// 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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "1" , "with boxes fillcolor", BoxesForcePlotLine)) return 1;
-
-	// +++++++++++++++++++++++++++++++=Ploting approximated and true shielding for each atom
-	if (periode != NULL) { // also look for PAS values
-		if(!OpenOutputFile(output, argv[3], "ShieldingsPAS-Order.pyx")) return 1;
-		if(!OpenOutputFile(output2, argv[3], "DeltaShieldingsPAS-Order.pyx")) return 1;
-		CreatePlotHeader(output, "ShieldingsPAS-Order", 1, "top right", NULL, NULL,	1, 5, "nuclei index", "iso chemical shielding value [ppm]");
-		CreatePlotHeader(output2, "DeltaShieldingsPAS-Order", 1, "top right", NULL, NULL,	1, 5, "nuclei index", "iso chemical shielding value [ppm]");
-		double step=0.8/KeySet.Order;
-		output << "set boxwidth " << step << endl;
-		output << "plot [0:" << ShieldingPAS.RowCounter[ShieldingPAS.MatrixCounter]+10 << "]\\" << endl;
-		output2 << "plot [0:" << ShieldingPAS.RowCounter[ShieldingPAS.MatrixCounter]+10 << "]\\" << endl;
-		for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
-			output << "'ShieldingsPAS-Order.dat' index " << BondOrder << " title 'Order " << BondOrder+1 << "' using ($1+" << step*(double)BondOrder << "):7 with boxes, \\" << endl;
-			output2 << "'DeltaShieldingsPAS-Order.dat' index " << BondOrder << " title 'Order " << BondOrder+1 << "' using ($1):7 with linespoints";
-			if (BondOrder-1 != KeySet.Order)
-				output2 << ", \\" << endl;
-		}
-		output << "'ShieldingsPAS-Order.dat' index " << KeySet.Order << " title 'Full' using ($1+" << step*(double)KeySet.Order << "):7 with boxes" << endl;
-		output.close();
-		output2.close();
-	}
-
-	// 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 ++++++++++++++++++++++++++++++++++
-	delete(periode);
-	Free((void **)&dir, "main: *dir");
-	cout << "done." << endl;
-	return 0;
+  periodentafel *periode = NULL; // and a period table of all elements
+  EnergyMatrix Energy;
+  EnergyMatrix EnergyFragments;
+  ForceMatrix Force;
+  ForceMatrix ForceFragments;
+  HessianMatrix Hessian;
+  HessianMatrix HessianFragments;
+  EnergyMatrix Hcorrection;
+  EnergyMatrix HcorrectionFragments;
+  ForceMatrix Shielding;
+  ForceMatrix ShieldingPAS;
+  ForceMatrix Chi;
+  ForceMatrix ChiPAS;
+  EnergyMatrix Time;
+  ForceMatrix ShieldingFragments;
+  ForceMatrix ShieldingPASFragments;
+  ForceMatrix ChiFragments;
+  ForceMatrix ChiPASFragments;
+  KeySetsContainer KeySet;
+  ofstream output;
+  ofstream output2;
+  ofstream output3;
+  ofstream output4;
+  ifstream input;
+  stringstream filename;
+  time_t t = time(NULL);
+  struct tm *ts = localtime(&t);
+  char *datum = asctime(ts);
+  stringstream Orderxrange;
+  stringstream Fragmentxrange;
+  stringstream yrange;
+  char *dir = NULL;
+  bool NoHessian = false;
+  bool NoTime = false;
+  bool NoHCorrection = true;
+  int counter;
+
+  cout << "ANOVA Analyzer" << endl;
+  cout << "==============" << endl;
+
+  // Get the command line options
+  if (argc < 4) {
+    cout << "Usage: " << argv[0] << " <inputdir> <prefix> <outputdir> [elementsdb]" << 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;
+    cout << "[elementsdb]\tpath to elements database, needed for shieldings." << endl;
+    return 1;
+  } else {
+    dir = (char *) Malloc(sizeof(char)*(strlen(argv[2])+2), "main: *dir");
+    strcpy(dir, "/");
+    strcat(dir, argv[2]);
+  }
+
+  if (argc > 4) {
+    cout << "Loading periodentafel." << endl;
+    periode = new periodentafel;
+    periode->LoadPeriodentafel(argv[4]);
+  }
+
+  // Test the given directory
+  if (!TestParams(argc, argv))
+    return 1;
+
+  // +++++++++++++++++ PARSING +++++++++++++++++++++++++++++++
+
+  // ------------- Parse through all Fragment subdirs --------
+  if (!Energy.ParseFragmentMatrix(argv[1], dir, EnergySuffix,0,0)) return 1;
+  if (!Hcorrection.ParseFragmentMatrix(argv[1], "", HCORRECTIONSUFFIX,0,0)) {
+    NoHCorrection = true;
+    cout << "No HCorrection file found, skipping these." << endl;
+  }
+  
+  if (!Force.ParseFragmentMatrix(argv[1], dir, ForcesSuffix,0,0)) return 1;
+  if (!Hessian.ParseFragmentMatrix(argv[1], dir, HessianSuffix,0,0)) {
+    NoHessian = true;
+    cout << "No Hessian file found, skipping these." << endl;
+  }
+  if (!Time.ParseFragmentMatrix(argv[1], dir, TimeSuffix, 10,1)) {
+    NoTime = true;
+    cout << "No speed file found, skipping these." << endl;
+  }
+  if (periode != NULL) { // also look for PAS values
+    if (!Shielding.ParseFragmentMatrix(argv[1], dir, ShieldingSuffix, 1, 0)) return 1;
+    if (!ShieldingPAS.ParseFragmentMatrix(argv[1], dir, ShieldingPASSuffix, 1, 0)) return 1;
+    if (!Chi.ParseFragmentMatrix(argv[1], dir, ChiSuffix, 1, 0)) return 1;
+    if (!ChiPAS.ParseFragmentMatrix(argv[1], dir, ChiPASSuffix, 1, 0)) return 1;
+  }
+
+  // ---------- Parse the TE Factors into an array -----------------
+  if (!Energy.ParseIndices()) return 1;
+  if (!NoHCorrection) Hcorrection.ParseIndices();
+
+  // ---------- Parse the Force indices into an array ---------------
+  if (!Force.ParseIndices(argv[1])) return 1;
+  if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return 1;
+  if (!ForceFragments.InitialiseIndices((class MatrixContainer *)&Force)) return 1;
+
+  // ---------- Parse hessian indices into an array -----------------
+  if (!NoHessian) {
+    if (!Hessian.InitialiseIndices((class MatrixContainer *)&Force)) return 1;
+    if (!HessianFragments.AllocateMatrix(Hessian.Header, Hessian.MatrixCounter, Hessian.RowCounter, Hessian.ColumnCounter)) return 1;
+    if (!HessianFragments.InitialiseIndices((class MatrixContainer *)&Force)) return 1;
+  }
+
+  // ---------- Parse the shielding indices into an array ---------------
+  if (periode != NULL) { // also look for PAS values
+    if(!Shielding.ParseIndices(argv[1])) return 1;
+    if(!ShieldingPAS.ParseIndices(argv[1])) return 1;
+    if (!ShieldingFragments.AllocateMatrix(Shielding.Header, Shielding.MatrixCounter, Shielding.RowCounter, Shielding.ColumnCounter)) return 1;
+    if (!ShieldingPASFragments.AllocateMatrix(ShieldingPAS.Header, ShieldingPAS.MatrixCounter, ShieldingPAS.RowCounter, ShieldingPAS.ColumnCounter)) return 1;
+    if(!ShieldingFragments.ParseIndices(argv[1])) return 1;
+    if(!ShieldingPASFragments.ParseIndices(argv[1])) return 1;
+    if(!Chi.ParseIndices(argv[1])) return 1;
+    if(!ChiPAS.ParseIndices(argv[1])) return 1;
+    if (!ChiFragments.AllocateMatrix(Chi.Header, Chi.MatrixCounter, Chi.RowCounter, Chi.ColumnCounter)) return 1;
+    if (!ChiPASFragments.AllocateMatrix(ChiPAS.Header, ChiPAS.MatrixCounter, ChiPAS.RowCounter, ChiPAS.ColumnCounter)) return 1;
+    if(!ChiFragments.ParseIndices(argv[1])) return 1;
+    if(!ChiPASFragments.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;
+
+  // ---------- Parse fragment files created by 'joiner' into an array -------------
+  if (!EnergyFragments.ParseFragmentMatrix(argv[1], dir, EnergyFragmentSuffix,0,0)) return 1;
+  if (!NoHCorrection) 
+    HcorrectionFragments.ParseFragmentMatrix(argv[1], dir, HcorrectionFragmentSuffix,0,0);
+  if (!ForceFragments.ParseFragmentMatrix(argv[1], dir, ForceFragmentSuffix,0,0)) return 1;
+  if (!NoHessian)
+    if (!HessianFragments.ParseFragmentMatrix(argv[1], dir, HessianFragmentSuffix,0,0)) return 1;
+  if (periode != NULL) { // also look for PAS values
+    if (!ShieldingFragments.ParseFragmentMatrix(argv[1], dir, ShieldingFragmentSuffix, 1, 0)) return 1;
+    if (!ShieldingPASFragments.ParseFragmentMatrix(argv[1], dir, ShieldingPASFragmentSuffix, 1, 0)) return 1;
+    if (!ChiFragments.ParseFragmentMatrix(argv[1], dir, ChiFragmentSuffix, 1, 0)) return 1;
+    if (!ChiPASFragments.ParseFragmentMatrix(argv[1], dir, ChiPASFragmentSuffix, 1, 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[Energy.MatrixCounter] << endl;
+  for(int j=0;j<Energy.RowCounter[Energy.MatrixCounter];j++) {
+    for(int k=0;k<Energy.ColumnCounter[Energy.MatrixCounter];k++)
+      output << scientific << Energy.Matrix[ Energy.MatrixCounter ][j][k] << "\t";
+    output << endl;
+  }
+  output << endl;
+  
+  output << endl << "Total Forces" << endl << "===============" << endl << Force.Header[Force.MatrixCounter] << endl;
+  for(int j=0;j<Force.RowCounter[Force.MatrixCounter];j++) {
+    for(int k=0;k<Force.ColumnCounter[Force.MatrixCounter];k++)
+      output << scientific << Force.Matrix[ Force.MatrixCounter ][j][k] << "\t";
+    output << endl;
+  }
+  output << endl;
+
+  if (!NoHessian) {
+    output << endl << "Total Hessian" << endl << "===============" << endl << Hessian.Header[Hessian.MatrixCounter] << endl;
+    for(int j=0;j<Hessian.RowCounter[Hessian.MatrixCounter];j++) {
+      for(int k=0;k<Hessian.ColumnCounter[Hessian.MatrixCounter];k++)
+        output << scientific << Hessian.Matrix[ Hessian.MatrixCounter ][j][k] << "\t";
+      output << endl;
+    }
+    output << endl;
+  }
+
+  if (periode != NULL) { // also look for PAS values
+    output << endl << "Total Shieldings" << endl << "===============" << endl << Shielding.Header[Hessian.MatrixCounter] << endl;
+    for(int j=0;j<Shielding.RowCounter[Shielding.MatrixCounter];j++) {
+      for(int k=0;k<Shielding.ColumnCounter[Shielding.MatrixCounter];k++)
+        output << scientific << Shielding.Matrix[ Shielding.MatrixCounter ][j][k] << "\t";
+      output << endl;
+    }
+    output << endl;
+  
+    output << endl << "Total Shieldings PAS" << endl << "===============" << endl << ShieldingPAS.Header[ShieldingPAS.MatrixCounter] << endl;
+    for(int j=0;j<ShieldingPAS.RowCounter[ShieldingPAS.MatrixCounter];j++) {
+      for(int k=0;k<ShieldingPAS.ColumnCounter[ShieldingPAS.MatrixCounter];k++)
+        output << scientific << ShieldingPAS.Matrix[ ShieldingPAS.MatrixCounter ][j][k] << "\t";
+      output << endl;
+    }
+    output << endl;
+
+    output << endl << "Total Chis" << endl << "===============" << endl << Chi.Header[Chi.MatrixCounter] << endl;
+    for(int j=0;j<Chi.RowCounter[Chi.MatrixCounter];j++) {
+      for(int k=0;k<Chi.ColumnCounter[Chi.MatrixCounter];k++)
+        output << scientific << Chi.Matrix[ Chi.MatrixCounter ][j][k] << "\t";
+      output << endl;
+    }
+    output << endl;
+  
+    output << endl << "Total Chis PAS" << endl << "===============" << endl << ChiPAS.Header[ChiPAS.MatrixCounter] << endl;
+    for(int j=0;j<ChiPAS.RowCounter[ChiPAS.MatrixCounter];j++) {
+      for(int k=0;k<ChiPAS.ColumnCounter[ChiPAS.MatrixCounter];k++)
+        output << scientific << ChiPAS.Matrix[ ChiPAS.MatrixCounter ][j][k] << "\t";
+      output << endl;
+    }
+    output << endl;
+  }
+  
+  if (!NoTime) {
+    output << endl << "Total Times" << endl << "===============" << endl << Time.Header[Time.MatrixCounter] << endl;
+    for(int j=0;j<Time.RowCounter[Time.MatrixCounter];j++) {
+      for(int k=0;k<Time.ColumnCounter[Time.MatrixCounter];k++) {
+        output << scientific << Time.Matrix[ Time.MatrixCounter ][j][k] << "\t";
+      }
+      output << endl;
+    }
+    output << endl;
+  }
+  output.close();
+  if (!NoTime)
+    for(int k=0;k<Time.ColumnCounter[Time.MatrixCounter];k++)
+      Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter] ][k] = Time.Matrix[ Time.MatrixCounter ][Time.RowCounter[Time.MatrixCounter]-1][k];
+
+  // +++++++++++++++ ANALYZING ++++++++++++++++++++++++++++++
+
+  cout << "Analyzing ..." << endl;
+
+  // ======================================= Creating the data files ==============================================================
+
+  // +++++++++++++++++++++++++++++++++++++++ Plotting Simtime vs Bond Order
+  // +++++++++++++++++++++++++++++++++++++++ Plotting Delta Simtime vs Bond Order
+  if (!NoTime) {
+    if (!OpenOutputFile(output, argv[3], "SimTime-Order.dat" )) return false;
+    if (!OpenOutputFile(output2, argv[3], "DeltaSimTime-Order.dat" )) return false;
+    for(int j=Time.RowCounter[Time.MatrixCounter];j--;)
+      for(int k=Time.ColumnCounter[Time.MatrixCounter];k--;) {
+        Time.Matrix[ Time.MatrixCounter ][j][k] = 0.;
+      }
+    counter = 0;
+    output << "#Order\tFrag.No.\t" << Time.Header[Time.MatrixCounter] << endl;
+    output2 << "#Order\tFrag.No.\t" << Time.Header[Time.MatrixCounter] << endl;
+    for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+      for(int i=KeySet.FragmentsPerOrder[BondOrder];i--;)
+        for(int j=Time.RowCounter[Time.MatrixCounter];j--;)
+          for(int k=Time.ColumnCounter[Time.MatrixCounter];k--;) {
+            Time.Matrix[ Time.MatrixCounter ][j][k] += Time.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+          }
+      counter += KeySet.FragmentsPerOrder[BondOrder];
+      output << BondOrder+1 << "\t" << counter;
+      output2 << BondOrder+1 << "\t" << counter;
+      for(int k=0;k<Time.ColumnCounter[Time.MatrixCounter];k++) {
+        output << "\t" << scientific << Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter]-1 ][k];
+        if (fabs(Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter] ][k]) > MYEPSILON)
+          output2 << "\t" << scientific << Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter]-1 ][k] / Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter] ][k];
+        else
+          output2 << "\t" << scientific << Time.Matrix[ Time.MatrixCounter ][ Time.RowCounter[Time.MatrixCounter]-1 ][k];
+      }
+      output << endl;
+      output2 << endl;
+    }
+    output.close();
+    output2.close();
+  }
+
+  if (!NoHessian) {
+    // +++++++++++++++++++++++++++++++++++++++ Plotting deviation in hessian to full QM
+    if (!CreateDataDeltaHessianOrderPerAtom(Hessian, HessianFragments, KeySet, argv[3], "DeltaHessian_xx-Order", "Plot of error between approximated hessian and full hessian versus the Bond Order", datum)) return 1;
+
+    if (!CreateDataDeltaFrobeniusOrderPerAtom(Hessian, HessianFragments, KeySet, argv[3], "DeltaFrobeniusHessian_xx-Order", "Plot of error between approximated hessian and full hessian in the frobenius norm versus the Bond Order", datum)) return 1;
+
+    // ++++++++++++++++++++++++++++++++++++++Plotting Hessian vs. Order
+    if (!CreateDataHessianOrderPerAtom(HessianFragments, KeySet, argv[3], "Hessian_xx-Order", "Plot of approximated hessian versus the Bond Order", datum)) return 1;
+    if (!AppendOutputFile(output, argv[3], "Hessian_xx-Order.dat" )) return false;
+    output << endl << "# Full" << endl;
+    for(int j=0;j<Hessian.RowCounter[Hessian.MatrixCounter];j++) {
+      output << j << "\t";
+      for(int k=0;k<Hessian.ColumnCounter[Force.MatrixCounter];k++)
+        output << scientific <<  Hessian.Matrix[ Hessian.MatrixCounter ][j][k] << "\t";
+      output << endl;
+    }
+    output.close();
+  }
+
+  // +++++++++++++++++++++++++++++++++++++++ Plotting shieldings
+  if (periode != NULL) { // also look for PAS values
+    if (!CreateDataDeltaForcesOrderPerAtom(ShieldingPAS, ShieldingPASFragments, KeySet, argv[3], "DeltaShieldingsPAS-Order", "Plot of error between approximated shieldings and full shieldings versus the Bond Order", datum)) return 1;
+    if (!CreateDataForcesOrderPerAtom(ShieldingPASFragments, KeySet, argv[3], "ShieldingsPAS-Order", "Plot of approximated shieldings versus the Bond Order", datum)) return 1;
+    if (!AppendOutputFile(output, argv[3], "ShieldingsPAS-Order.dat" )) return false;
+    output << endl << "# Full" << endl;
+    for(int j=0;j<ShieldingPAS.RowCounter[ShieldingPAS.MatrixCounter];j++) {
+      output << j << "\t";
+      for(int k=0;k<ShieldingPAS.ColumnCounter[ShieldingPAS.MatrixCounter];k++)
+        output << scientific <<  ShieldingPAS.Matrix[ ShieldingPAS.MatrixCounter ][j][k] << "\t"; //*(((k>1) && (k<6))? 1.e6 : 1.) << "\t";
+      output << endl;
+    }
+    output.close();
+    if (!CreateDataDeltaForcesOrderPerAtom(ChiPAS, ChiPASFragments, KeySet, argv[3], "DeltaChisPAS-Order", "Plot of error between approximated Chis and full Chis versus the Bond Order", datum)) return 1;
+    if (!CreateDataForcesOrderPerAtom(ChiPASFragments, KeySet, argv[3], "ChisPAS-Order", "Plot of approximated Chis versus the Bond Order", datum)) return 1;
+    if (!AppendOutputFile(output, argv[3], "ChisPAS-Order.dat" )) return false;
+    output << endl << "# Full" << endl;
+    for(int j=0;j<ChiPAS.RowCounter[ChiPAS.MatrixCounter];j++) {
+      output << j << "\t";
+      for(int k=0;k<ChiPAS.ColumnCounter[ChiPAS.MatrixCounter];k++)
+        output << scientific <<  ChiPAS.Matrix[ ChiPAS.MatrixCounter ][j][k] << "\t"; //*(((k>1) && (k<6))? 1.e6 : 1.) << "\t";
+      output << endl;
+    }
+    output.close();
+  }
+
+
+  // +++++++++++++++++++++++++++++++++++++++ Plotting deviation in energy to full QM
+  if (!CreateDataDeltaEnergyOrder(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 (!CreateDataEnergyOrder(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 (!CreateDataDeltaForcesOrderPerAtom(Force, ForceFragments, KeySet, argv[3], "DeltaForces-Order", "Plot of error between approximated forces and full forces versus the Bond Order", datum)) return 1;
+
+  // min force
+  if (!CreateDataDeltaForcesOrder(Force, ForceFragments, KeySet, argv[3], "DeltaMinForces-Order", "Plot of min error between approximated forces and full forces versus the Bond Order", datum, CreateMinimumForce)) return 1;
+
+  // mean force
+  if (!CreateDataDeltaForcesOrder(Force, ForceFragments, KeySet, argv[3], "DeltaMeanForces-Order", "Plot of mean error between approximated forces and full forces versus the Bond Order", datum, CreateMeanForce)) return 1;
+
+  // max force
+  if (!CreateDataDeltaForcesOrder(Force, ForceFragments, KeySet, argv[3], "DeltaMaxForces-Order", "Plot of max error between approximated forces and full forces versus the Bond Order", datum, CreateMaximumForce)) return 1;
+
+  // ++++++++++++++++++++++++++++++++++++++Plotting Forces vs. Order
+  if (!CreateDataForcesOrderPerAtom(ForceFragments, KeySet, argv[3], "Forces-Order", "Plot of approximated forces versus the Bond Order", datum)) return 1;
+  if (!AppendOutputFile(output, argv[3], "Forces-Order.dat" )) return false;
+  output << endl << "# Full" << endl;
+  for(int j=0;j<Force.RowCounter[Force.MatrixCounter];j++) {
+    output << j << "\t";
+    for(int k=0;k<Force.ColumnCounter[Force.MatrixCounter];k++)
+      output << scientific <<  Force.Matrix[ Force.MatrixCounter ][j][k] << "\t";
+    output << endl;
+  }
+  output.close();
+  // min force
+  if (!CreateDataForcesOrder(ForceFragments, KeySet, argv[3], "MinForces-Order", "Plot of min approximated forces versus the Bond Order", datum, CreateMinimumForce)) return 1;
+
+  // mean force
+  if (!CreateDataForcesOrder(ForceFragments, KeySet, argv[3], "MeanForces-Order", "Plot of mean approximated forces versus the Bond Order", datum, CreateMeanForce)) return 1;
+
+  // max force
+  if (!CreateDataForcesOrder(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(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 << "]";
+  yrange.str("[1e-8:1e+1]");
+  
+  if (!NoTime) {
+    // +++++++++++++++++++++++++++++++++++++++ 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(), yrange.str().c_str(), "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
+  yrange.str("[1e-8:1e+0]");
+  // 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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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", NULL,  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", NULL, 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
+  yrange.str("");
+  yrange << "[" << EnergyFragments.FindMinValue() << ":" << EnergyFragments.FindMaxValue() << "]";
+  if (!CreatePlotOrder(EnergyFragments, KeySet, argv[3], "Energies-Fragment", 5, "below", "y", "", 1, 5, "fragment number", "Energies of each fragment [Ht]", Fragmentxrange.str().c_str(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "1" , "with linespoints", AbsEnergyPlotLine)) return 1;
+
+  // +++++++++++++++++++++++++++++++=Ploting min/mean/max forces for each fragment
+  yrange.str("");
+  yrange << "[" << ForceFragments.FindMinValue() << ":" << ForceFragments.FindMaxValue()<< "]";
+  // 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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "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(), yrange.str().c_str(), "1" , "with boxes fillcolor", BoxesForcePlotLine)) return 1;
+
+  // +++++++++++++++++++++++++++++++=Ploting approximated and true shielding for each atom
+  if (periode != NULL) { // also look for PAS values
+    if(!OpenOutputFile(output, argv[3], "ShieldingsPAS-Order.pyx")) return 1;
+    if(!OpenOutputFile(output2, argv[3], "DeltaShieldingsPAS-Order.pyx")) return 1;
+    CreatePlotHeader(output, "ShieldingsPAS-Order", 1, "top right", NULL, NULL,  1, 5, "nuclei index", "iso chemical shielding value [ppm]");
+    CreatePlotHeader(output2, "DeltaShieldingsPAS-Order", 1, "top right", NULL, NULL,  1, 5, "nuclei index", "iso chemical shielding value [ppm]");
+    double step=0.8/KeySet.Order;
+    output << "set boxwidth " << step << endl;
+    output << "plot [0:" << ShieldingPAS.RowCounter[ShieldingPAS.MatrixCounter]+10 << "]\\" << endl;
+    output2 << "plot [0:" << ShieldingPAS.RowCounter[ShieldingPAS.MatrixCounter]+10 << "]\\" << endl;
+    for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+      output << "'ShieldingsPAS-Order.dat' index " << BondOrder << " title 'Order " << BondOrder+1 << "' using ($1+" << step*(double)BondOrder << "):7 with boxes, \\" << endl;
+      output2 << "'DeltaShieldingsPAS-Order.dat' index " << BondOrder << " title 'Order " << BondOrder+1 << "' using ($1):7 with linespoints";
+      if (BondOrder-1 != KeySet.Order)
+        output2 << ", \\" << endl;
+    }
+    output << "'ShieldingsPAS-Order.dat' index " << KeySet.Order << " title 'Full' using ($1+" << step*(double)KeySet.Order << "):7 with boxes" << endl;
+    output2.close();  
+
+    if(!OpenOutputFile(output, argv[3], "ChisPAS-Order.pyx")) return 1;
+    if(!OpenOutputFile(output2, argv[3], "DeltaChisPAS-Order.pyx")) return 1;
+    CreatePlotHeader(output, "ChisPAS-Order", 1, "top right", NULL, NULL,  1, 5, "nuclei index", "iso chemical Chi value [ppm]");
+    CreatePlotHeader(output2, "DeltaChisPAS-Order", 1, "top right", NULL, NULL,  1, 5, "nuclei index", "iso chemical Chi value [ppm]");
+    output << "set boxwidth " << step << endl;
+    output << "plot [0:" << ChiPAS.RowCounter[ChiPAS.MatrixCounter]+10 << "]\\" << endl;
+    output2 << "plot [0:" << ChiPAS.RowCounter[ChiPAS.MatrixCounter]+10 << "]\\" << endl;
+    for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+      output << "'ChisPAS-Order.dat' index " << BondOrder << " title 'Order " << BondOrder+1 << "' using ($1+" << step*(double)BondOrder << "):7 with boxes, \\" << endl;
+      output2 << "'DeltaChisPAS-Order.dat' index " << BondOrder << " title 'Order " << BondOrder+1 << "' using ($1):7 with linespoints";
+      if (BondOrder-1 != KeySet.Order)
+        output2 << ", \\" << endl;
+    }
+    output << "'ChisPAS-Order.dat' index " << KeySet.Order << " title 'Full' using ($1+" << step*(double)KeySet.Order << "):7 with boxes" << endl;
+    output.close();  
+    output2.close();  
+
+    if(!OpenOutputFile(output, argv[3], "ChisPAS-Order.pyx")) return 1;
+    if(!OpenOutputFile(output2, argv[3], "DeltaChisPAS-Order.pyx")) return 1;
+    CreatePlotHeader(output, "ChisPAS-Order", 1, "top right", NULL, NULL,  1, 5, "nuclei index", "iso chemical Chi value [ppm]");
+    CreatePlotHeader(output2, "DeltaChisPAS-Order", 1, "top right", NULL, NULL,  1, 5, "nuclei index", "iso chemical Chi value [ppm]");
+    output << "set boxwidth " << step << endl;
+    output << "plot [0:" << ChiPAS.RowCounter[ChiPAS.MatrixCounter]+10 << "]\\" << endl;
+    output2 << "plot [0:" << ChiPAS.RowCounter[ChiPAS.MatrixCounter]+10 << "]\\" << endl;
+    for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+      output << "'ChisPAS-Order.dat' index " << BondOrder << " title 'Order " << BondOrder+1 << "' using ($1+" << step*(double)BondOrder << "):7 with boxes, \\" << endl;
+      output2 << "'DeltaChisPAS-Order.dat' index " << BondOrder << " title 'Order " << BondOrder+1 << "' using ($1):7 with linespoints";
+      if (BondOrder-1 != KeySet.Order)
+        output2 << ", \\" << endl;
+    }
+    output << "'ChisPAS-Order.dat' index " << KeySet.Order << " title 'Full' using ($1+" << step*(double)KeySet.Order << "):7 with boxes" << endl;
+    output.close();  
+    output2.close();  
+  }
+
+  // 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 ++++++++++++++++++++++++++++++++++
+  delete(periode);
+  Free((void **)&dir, "main: *dir");
+  cout << "done." << endl;
+  return 0;
 };
 
Index: src/atom.cpp
===================================================================
--- src/atom.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/atom.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -13,21 +13,40 @@
 atom::atom()
 {
-	Name = NULL;
-	previous = NULL;
-	next = NULL;
-	father = this;	// generally, father is itself
-	Ancestor = NULL;
-	type = NULL;
-	sort = NULL;
-	FixedIon = 0;
-	nr = -1;
-	GraphNr = -1;
-	ComponentNr = NULL;
-	IsCyclic = false;
-	SeparationVertex = false;
-	LowpointNr = -1;
-	AdaptiveOrder = 0;
-	MaxOrder = false;
+  Name = NULL;
+  previous = NULL;
+  next = NULL;
+  father = this;  // generally, father is itself
+  Ancestor = NULL;
+  type = NULL;
+  sort = NULL;
+  FixedIon = 0;
+  nr = -1;
+  GraphNr = -1;
+  ComponentNr = NULL;
+  IsCyclic = false;
+  SeparationVertex = false;
+  LowpointNr = -1;
+  AdaptiveOrder = 0;
+  MaxOrder = false;
 };
+
+/** Constructor of class atom.
+ *
+ */
+atom::atom(atom *pointer)
+{
+  Name = NULL;
+  previous = NULL;
+  next = NULL;
+  father = this;  // generally, father is itself
+  Ancestor = NULL;
+  type = pointer->type;  // copy element of atom
+  x.CopyVector(&pointer->x); // copy coordination
+  v.CopyVector(&pointer->v); // copy velocity
+  FixedIon = pointer->FixedIon;
+  nr = -1;
+  sort = &nr;
+}
+
 
 /** Destructor of class atom.
@@ -35,6 +54,6 @@
 atom::~atom()
 {
-	Free((void **)&Name, "atom::~atom: *Name");
-	Free((void **)&ComponentNr, "atom::~atom: *ComponentNr");
+  Free((void **)&Name, "atom::~atom: *Name");
+  Free((void **)&ComponentNr, "atom::~atom: *ComponentNr");
 };
 
@@ -45,11 +64,11 @@
 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;
+  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;
 };
 
@@ -62,17 +81,17 @@
 bool atom::Output(int ElementNo, int AtomNo, ofstream *out, const char *comment) 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];
-		*out << "\t" << FixedIon;
-		if (v.Norm() > MYEPSILON)
-			*out << "\t" << scientific << setprecision(6) << v.x[0] << "\t" << v.x[1] << "\t" << v.x[2] << "\t";
-		if (comment != NULL)
-		  *out << " # " << comment << endl;
-		else
-		  *out << " # molecule nr " << nr << endl;
-		return true;
-	} else
-		return false;
+  if (out != NULL) {
+    *out << "Ion_Type" << ElementNo << "_" << AtomNo << "\t"  << fixed << setprecision(9) << showpoint;
+    *out << x.x[0] << "\t" << x.x[1] << "\t" << x.x[2];
+    *out << "\t" << FixedIon;
+    if (v.Norm() > MYEPSILON)
+      *out << "\t" << scientific << setprecision(6) << v.x[0] << "\t" << v.x[1] << "\t" << v.x[2] << "\t";
+    if (comment != NULL)
+      *out << " # " << comment << endl;
+    else
+      *out << " # molecule nr " << nr << endl;
+    return true;
+  } else
+    return false;
 };
 
@@ -82,15 +101,15 @@
 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;
+  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, const atom &a)
 {
-	ost << "[" << a.Name << "|" << &a << "]";
-	return ost;
+  ost << "[" << a.Name << "|" << &a << "]";
+  return ost;
 };
 
@@ -101,13 +120,13 @@
 bool atom::Compare(const atom &ptr)
 {
-	if (nr < ptr.nr)
-		return true;
-	else
-		return false;
+  if (nr < ptr.nr)
+    return true;
+  else
+    return false;
 };
 
 bool operator < (atom &a, atom &b)
 {
-	return a.Compare(b);
+  return a.Compare(b);
 };
 
Index: src/bond.cpp
===================================================================
--- src/bond.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/bond.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -14,14 +14,14 @@
 bond::bond()
 {
-	leftatom = NULL;
-	rightatom = NULL;
-	previous = NULL;
-	next = NULL;
-	nr = -1;
-	HydrogenBond = 0;
-	BondDegree = 0;
-	Used = white;
-	Cyclic = false;
-	Type = Undetermined;
+  leftatom = NULL;
+  rightatom = NULL;
+  previous = NULL;
+  next = NULL;
+  nr = -1;
+  HydrogenBond = 0;
+  BondDegree = 0;
+  Used = white;
+  Cyclic = false;
+  Type = Undetermined;
 };
 
@@ -34,37 +34,37 @@
 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;
+  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;
+  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;
 };
 
@@ -73,17 +73,17 @@
 bond::~bond()
 {
-	// remove this node from the list structure
-	if (previous != NULL) {
-		previous->next = next;
-	}
-	if (next != NULL) {
-		next->previous = previous;
-	}
+  // 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) 
+ostream & operator << (ostream &ost, const bond &b) 
 {
-	ost << "[" << b.leftatom->Name << " <" << b.BondDegree << "(H" << b.HydrogenBond << ")>" << b.rightatom->Name << "]";
-	return ost;
+  ost << "[" << b.leftatom->Name << " <" << b.BondDegree << "(H" << b.HydrogenBond << ")>" << b.rightatom->Name << "]";
+  return ost;
 };
 
@@ -94,9 +94,10 @@
 atom * bond::GetOtherAtom(atom *Atom) const
 {
-	if(leftatom == Atom) 
-		return rightatom;
-	if(rightatom == Atom) 
-		return leftatom;
-	return NULL;
+  if(leftatom == Atom) 
+    return rightatom;
+  if(rightatom == Atom) 
+    return leftatom;
+  cerr << "Bond " << *this << " does not contain atom " << *Atom << "!" << endl;
+  return NULL;
 };
 
@@ -107,5 +108,5 @@
 bond * bond::GetFirstBond()
 {
-	return GetFirst(this);
+  return GetFirst(this);
 };
 
@@ -116,5 +117,5 @@
 bond * bond::GetLastBond()
 {
-	return GetLast(this);
+  return GetLast(this);
 };
 
@@ -124,5 +125,5 @@
 enum Shading bond::IsUsed() 
 {
-	return Used;
+  return Used;
 };
 
@@ -133,5 +134,5 @@
 bool bond::Contains(const atom *ptr)
 {
-	return ((leftatom == ptr) || (rightatom == ptr));
+  return ((leftatom == ptr) || (rightatom == ptr));
 };
 
@@ -142,5 +143,5 @@
 bool bond::Contains(const int number)
 {
-	return ((leftatom->nr == number) || (rightatom->nr == number));
+  return ((leftatom->nr == number) || (rightatom->nr == number));
 };
 
@@ -149,11 +150,11 @@
  */
 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;
-	}
+  if (Used == black) {
+    cerr << "ERROR: Bond " << this << " was already marked black!." << endl;
+    return false;
+  } else {
+    Used = color;
+    return true;
+  }
 };
 
@@ -162,4 +163,4 @@
  */
 void bond::ResetUsed() {
-	Used = white;
+  Used = white;
 };
Index: src/boundary.cpp
===================================================================
--- src/boundary.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/boundary.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -10,5 +10,5 @@
 #define DoSingleStepOutput 0
 #define DoTecplotOutput 1
-#define DoRaster3DOutput 0
+#define DoRaster3DOutput 1
 #define DoVRMLOutput 1
 #define TecplotSuffix ".dat"
@@ -45,5 +45,6 @@
 void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
 {
-  cout << Verbose(6) << "Adding line " << *line << " to " << *this << "." << endl;
+  cout << Verbose(6) << "Adding " << *this << " to line " << *line << "."
+      << endl;
   if (line->endpoints[0] == this)
     {
@@ -131,4 +132,58 @@
 ;
 
+/** Checks whether we have a common endpoint with given \a *line.
+ * \param *line other line to test
+ * \return true - common endpoint present, false - not connected
+ */
+bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
+{
+  if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
+    return true;
+  else
+    return false;
+};
+
+/** Checks whether the adjacent triangles of a baseline are convex or not.
+ * We sum the two angles of each normal vector with a ficticious normnal vector from this baselinbe pointing outwards.
+ * If greater/equal M_PI than we are convex.
+ * \param *out output stream for debugging
+ * \return true - triangles are convex, false - concave or less than two triangles connected
+ */
+bool BoundaryLineSet::CheckConvexityCriterion(ofstream *out)
+{
+  Vector BaseLineNormal;
+  double angle = 0;
+  // get the two triangles
+  if (TrianglesCount != 2) {
+    *out << Verbose(1) << "ERROR: Baseline " << this << " is connect to less than two triangles, Tesselation incomplete!" << endl;
+    return false;
+  }
+  // have a normal vector on the base line pointing outwards
+  BaseLineNormal.Zero();
+  for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++)
+    BaseLineNormal.AddVector(&runner->second->NormalVector);
+  BaseLineNormal.Normalize();
+  // and calculate the sum of the angles with this normal vector and each of the triangle ones'
+  for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++)
+    angle += BaseLineNormal.Angle(&runner->second->NormalVector);
+
+  if ((angle - M_PI) > -MYEPSILON)
+    return true;
+  else
+    return false;
+}
+
+/** Checks whether point is any of the two endpoints this line contains.
+ * \param *point point to test
+ * \return true - point is of the line, false - is not
+ */
+bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
+{
+  for(int i=0;i<2;i++)
+    if (point == endpoints[i])
+      return true;
+  return false;
+};
+
 ostream &
 operator <<(ostream &ost, BoundaryLineSet &a)
@@ -213,6 +268,9 @@
 ;
 
-void
-BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
+/** Calculates the normal vector for this triangle.
+ * Is made unique by comparison with \a OtherVector to point in the other direction.
+ * \param &OtherVector direction vector to make normal vector unique.
+ */
+void BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
 {
   // get normal vector
@@ -223,6 +281,76 @@
   if (NormalVector.Projection(&OtherVector) > 0)
     NormalVector.Scale(-1.);
-}
-;
+};
+
+/** Finds the point on the triangle \a *BTS the line defined by \a *MolCenter and \a *x crosses through.
+ * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
+ * This we test if it's really on the plane and whether it's inside the triangle on the plane or not.
+ * The latter is done as follows: if it's really outside, then for any endpoint of the triangle and it's opposite
+ * base line, the intersection between the line from endpoint to intersection and the base line will have a Vector::NormSquared()
+ * smaller than the first line.
+ * \param *out output stream for debugging
+ * \param *MolCenter offset vector of line
+ * \param *x second endpoint of line, minus \a *MolCenter is directional vector of line
+ * \param *Intersection intersection on plane on return
+ * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
+ */
+bool BoundaryTriangleSet::GetIntersectionInsideTriangle(ofstream *out, Vector *MolCenter, Vector *x, Vector *Intersection)
+{
+  Vector CrossPoint;
+  Vector helper;
+  int i=0;
+
+  if (Intersection->GetIntersectionWithPlane(out, &NormalVector, &endpoints[0]->node->x, MolCenter, x)) {
+    *out << Verbose(1) << "Alas! [Bronstein] failed - at least numerically - the intersection is not on the plane!" << endl;
+    return false;
+  }
+
+  // Calculate cross point between one baseline and the line from the third endpoint to intersection
+  do {
+    CrossPoint.GetIntersectionOfTwoLinesOnPlane(out, &endpoints[i%3]->node->x, &endpoints[(i+1)%3]->node->x, &endpoints[(i+2)%3]->node->x, Intersection);
+    helper.CopyVector(&endpoints[(i+1)%3]->node->x);
+    helper.SubtractVector(&endpoints[i%3]->node->x);
+    i++;
+    if (i>3)
+      break;
+  } while (CrossPoint.NormSquared() < MYEPSILON);
+  if (i>3) {
+    *out << Verbose(1) << "ERROR: Could not find any cross points, something's utterly wrong here!" << endl;
+    exit(255);
+  }
+  CrossPoint.SubtractVector(&endpoints[i%3]->node->x);
+
+  // check whether intersection is inside or not by comparing length of intersection and length of cross point
+  if ((CrossPoint.NormSquared() - helper.NormSquared()) > -MYEPSILON) { // inside
+    return true;
+  } else { // outside!
+    Intersection->Zero();
+    return false;
+  }
+};
+
+/** Checks whether lines is any of the three boundary lines this triangle contains.
+ * \param *line line to test
+ * \return true - line is of the triangle, false - is not
+ */
+bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
+{
+  for(int i=0;i<3;i++)
+    if (line == lines[i])
+      return true;
+  return false;
+};
+
+/** Checks whether point is any of the three endpoints this triangle contains.
+ * \param *point point to test
+ * \return true - point is of the triangle, false - is not
+ */
+bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
+{
+  for(int i=0;i<3;i++)
+    if (point == endpoints[i])
+      return true;
+  return false;
+};
 
 ostream &
@@ -239,15 +367,15 @@
 
 CandidateForTesselation::CandidateForTesselation(
-	atom *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter
+  atom *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter
 ) {
-	point = candidate;
-	BaseLine = line;
-	OptCenter.CopyVector(&OptCandidateCenter);
-	OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
+  point = candidate;
+  BaseLine = line;
+  OptCenter.CopyVector(&OptCandidateCenter);
+  OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
 }
 
 CandidateForTesselation::~CandidateForTesselation() {
-	point = NULL;
-	BaseLine = NULL;
+  point = NULL;
+  BaseLine = NULL;
 }
 
@@ -301,4 +429,6 @@
   LineMap LinesOnBoundary;
   TriangleMap TrianglesOnBoundary;
+  Vector *MolCenter = mol->DetermineCenterOfAll(out);
+  Vector helper;
 
   *out << Verbose(1) << "Finding all boundary points." << endl;
@@ -308,187 +438,152 @@
   double radius, angle;
   // 3a. Go through every axis
-  for (int axis = 0; axis < NDIM; axis++)
-    {
-      AxisVector.Zero();
-      AngleReferenceVector.Zero();
-      AngleReferenceNormalVector.Zero();
-      AxisVector.x[axis] = 1.;
-      AngleReferenceVector.x[(axis + 1) % NDIM] = 1.;
-      AngleReferenceNormalVector.x[(axis + 2) % NDIM] = 1.;
-      //    *out << Verbose(1) << "Axisvector is ";
-      //    AxisVector.Output(out);
-      //    *out << " and AngleReferenceVector is ";
-      //    AngleReferenceVector.Output(out);
-      //    *out << "." << endl;
-      //    *out << " and AngleReferenceNormalVector is ";
-      //    AngleReferenceNormalVector.Output(out);
-      //    *out << "." << endl;
-      // 3b. construct set of all points, transformed into cylindrical system and with left and right neighbours
-      Walker = mol->start;
-      while (Walker->next != mol->end)
+  for (int axis = 0; axis < NDIM; axis++) {
+    AxisVector.Zero();
+    AngleReferenceVector.Zero();
+    AngleReferenceNormalVector.Zero();
+    AxisVector.x[axis] = 1.;
+    AngleReferenceVector.x[(axis + 1) % NDIM] = 1.;
+    AngleReferenceNormalVector.x[(axis + 2) % NDIM] = 1.;
+
+    *out << Verbose(1) << "Axisvector is " << AxisVector << " and AngleReferenceVector is " << AngleReferenceVector << ", and AngleReferenceNormalVector is " << AngleReferenceNormalVector << "." << endl;
+
+    // 3b. construct set of all points, transformed into cylindrical system and with left and right neighbours
+    Walker = mol->start;
+    while (Walker->next != mol->end) {
+      Walker = Walker->next;
+      Vector ProjectedVector;
+      ProjectedVector.CopyVector(&Walker->x);
+      ProjectedVector.SubtractVector(MolCenter);
+      ProjectedVector.ProjectOntoPlane(&AxisVector);
+
+      // correct for negative side
+      radius = ProjectedVector.NormSquared();
+      if (fabs(radius) > MYEPSILON)
+        angle = ProjectedVector.Angle(&AngleReferenceVector);
+      else
+        angle = 0.; // otherwise it's a vector in Axis Direction and unimportant for boundary issues
+
+      //*out << "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << "." << endl;
+      if (ProjectedVector.Projection(&AngleReferenceNormalVector) > 0) {
+        angle = 2. * M_PI - angle;
+      }
+      *out << Verbose(2) << "Inserting " << *Walker << ": (r, alpha) = (" << radius << "," << angle << "): " << ProjectedVector << endl;
+      BoundaryTestPair = BoundaryPoints[axis].insert(BoundariesPair(angle, DistancePair (radius, Walker)));
+      if (!BoundaryTestPair.second) { // same point exists, check first r, then distance of original vectors to center of gravity
+        *out << Verbose(2) << "Encountered two vectors whose projection onto axis " << axis << " is equal: " << endl;
+        *out << Verbose(2) << "Present vector: " << *BoundaryTestPair.first->second.second << endl;
+        *out << Verbose(2) << "New vector: " << *Walker << endl;
+        double tmp = ProjectedVector.NormSquared();
+        if ((tmp - BoundaryTestPair.first->second.first) > MYEPSILON) {
+          BoundaryTestPair.first->second.first = tmp;
+          BoundaryTestPair.first->second.second = Walker;
+          *out << Verbose(2) << "Keeping new vector due to larger projected distance " << tmp << "." << endl;
+        } else if (fabs(tmp - BoundaryTestPair.first->second.first) < MYEPSILON) {
+          helper.CopyVector(&Walker->x);
+          helper.SubtractVector(MolCenter);
+          tmp = helper.NormSquared();
+          helper.CopyVector(&BoundaryTestPair.first->second.second->x);
+          helper.SubtractVector(MolCenter);
+          if (helper.NormSquared() < tmp) {
+            BoundaryTestPair.first->second.second = Walker;
+            *out << Verbose(2) << "Keeping new vector due to larger distance to molecule center " << helper.NormSquared() << "." << endl;
+          } else {
+            *out << Verbose(2) << "Keeping present vector due to larger distance to molecule center " << tmp << "." << endl;
+          }
+        } else {
+          *out << Verbose(2) << "Keeping present vector due to larger projected distance " << tmp << "." << endl;
+        }
+      }
+    }
+    // printing all inserted for debugging
+    //    {
+    //      *out << Verbose(2) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
+    //      int i=0;
+    //      for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
+    //        if (runner != BoundaryPoints[axis].begin())
+    //          *out << ", " << i << ": " << *runner->second.second;
+    //        else
+    //          *out << i << ": " << *runner->second.second;
+    //        i++;
+    //      }
+    //      *out << endl;
+    //    }
+    // 3c. throw out points whose distance is less than the mean of left and right neighbours
+    bool flag = false;
+    *out << Verbose(1) << "Looking for candidates to kick out by convex condition ... " << endl;
+    do { // do as long as we still throw one out per round
+      flag = false;
+      Boundaries::iterator left = BoundaryPoints[axis].end();
+      Boundaries::iterator right = BoundaryPoints[axis].end();
+      for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
+        // set neighbours correctly
+        if (runner == BoundaryPoints[axis].begin()) {
+          left = BoundaryPoints[axis].end();
+        } else {
+          left = runner;
+        }
+        left--;
+        right = runner;
+        right++;
+        if (right == BoundaryPoints[axis].end()) {
+          right = BoundaryPoints[axis].begin();
+        }
+        // check distance
+
+        // construct the vector of each side of the triangle on the projected plane (defined by normal vector AxisVector)
         {
-          Walker = Walker->next;
-          Vector ProjectedVector;
-          ProjectedVector.CopyVector(&Walker->x);
-          ProjectedVector.ProjectOntoPlane(&AxisVector);
-          // correct for negative side
-          //if (Projection(y) < 0)
-          //angle = 2.*M_PI - angle;
-          radius = ProjectedVector.Norm();
-          if (fabs(radius) > MYEPSILON)
-            angle = ProjectedVector.Angle(&AngleReferenceVector);
-          else
-            angle = 0.; // otherwise it's a vector in Axis Direction and unimportant for boundary issues
-
-          //*out << "Checking sign in quadrant : " << ProjectedVector.Projection(&AngleReferenceNormalVector) << "." << endl;
-          if (ProjectedVector.Projection(&AngleReferenceNormalVector) > 0)
-            {
-              angle = 2. * M_PI - angle;
-            }
-          //*out << Verbose(2) << "Inserting " << *Walker << ": (r, alpha) = (" << radius << "," << angle << "): ";
-          //ProjectedVector.Output(out);
-          //*out << endl;
-          BoundaryTestPair = BoundaryPoints[axis].insert(BoundariesPair(angle,
-              DistancePair (radius, Walker)));
-          if (BoundaryTestPair.second)
-            { // successfully inserted
-            }
-          else
-            { // same point exists, check first r, then distance of original vectors to center of gravity
-              *out << Verbose(2)
-                  << "Encountered two vectors whose projection onto axis "
-                  << axis << " is equal: " << endl;
-              *out << Verbose(2) << "Present vector: ";
-              BoundaryTestPair.first->second.second->x.Output(out);
-              *out << endl;
-              *out << Verbose(2) << "New vector: ";
-              Walker->x.Output(out);
-              *out << endl;
-              double tmp = ProjectedVector.Norm();
-              if (tmp > BoundaryTestPair.first->second.first)
-                {
-                  BoundaryTestPair.first->second.first = tmp;
-                  BoundaryTestPair.first->second.second = Walker;
-                  *out << Verbose(2) << "Keeping new vector." << endl;
-                }
-              else if (tmp == BoundaryTestPair.first->second.first)
-                {
-                  if (BoundaryTestPair.first->second.second->x.ScalarProduct(
-                      &BoundaryTestPair.first->second.second->x)
-                      < Walker->x.ScalarProduct(&Walker->x))
-                    { // Norm() does a sqrt, which makes it a lot slower
-                      BoundaryTestPair.first->second.second = Walker;
-                      *out << Verbose(2) << "Keeping new vector." << endl;
-                    }
-                  else
-                    {
-                      *out << Verbose(2) << "Keeping present vector." << endl;
-                    }
-                }
-              else
-                {
-                  *out << Verbose(2) << "Keeping present vector." << endl;
-                }
-            }
+          Vector SideA, SideB, SideC, SideH;
+          SideA.CopyVector(&left->second.second->x);
+          SideA.SubtractVector(MolCenter);
+          SideA.ProjectOntoPlane(&AxisVector);
+          //          *out << "SideA: ";
+          //          SideA.Output(out);
+          //          *out << endl;
+
+          SideB.CopyVector(&right->second.second->x);
+          SideB.SubtractVector(MolCenter);
+          SideB.ProjectOntoPlane(&AxisVector);
+          //          *out << "SideB: ";
+          //          SideB.Output(out);
+          //          *out << endl;
+
+          SideC.CopyVector(&left->second.second->x);
+          SideC.SubtractVector(&right->second.second->x);
+          SideC.ProjectOntoPlane(&AxisVector);
+          //          *out << "SideC: ";
+          //          SideC.Output(out);
+          //          *out << endl;
+
+          SideH.CopyVector(&runner->second.second->x);
+          SideH.SubtractVector(MolCenter);
+          SideH.ProjectOntoPlane(&AxisVector);
+          //          *out << "SideH: ";
+          //          SideH.Output(out);
+          //          *out << endl;
+
+          // calculate each length
+          double a = SideA.Norm();
+          //double b = SideB.Norm();
+          //double c = SideC.Norm();
+          double h = SideH.Norm();
+          // calculate the angles
+          double alpha = SideA.Angle(&SideH);
+          double beta = SideA.Angle(&SideC);
+          double gamma = SideB.Angle(&SideH);
+          double delta = SideC.Angle(&SideH);
+          double MinDistance = a * sin(beta) / (sin(delta)) * (((alpha < M_PI / 2.) || (gamma < M_PI / 2.)) ? 1. : -1.);
+          //*out << Verbose(2) << " I calculated: a = " << a << ", h = " << h << ", beta(" << left->second.second->Name << "," << left->second.second->Name << "-" << right->second.second->Name << ") = " << beta << ", delta(" << left->second.second->Name << "," << runner->second.second->Name << ") = " << delta << ", Min = " << MinDistance << "." << endl;
+          *out << Verbose(1) << "Checking CoG distance of runner " << *runner->second.second << " " << h << " against triangle's side length spanned by (" << *left->second.second << "," << *right->second.second << ") of " << MinDistance << "." << endl;
+          if ((fabs(h / fabs(h) - MinDistance / fabs(MinDistance)) < MYEPSILON) && ((h - MinDistance)) < -MYEPSILON) {
+            // throw out point
+            *out << Verbose(1) << "Throwing out " << *runner->second.second << "." << endl;
+            BoundaryPoints[axis].erase(runner);
+            flag = true;
+          }
         }
-      // printing all inserted for debugging
-      //    {
-      //      *out << Verbose(2) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
-      //      int i=0;
-      //      for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
-      //        if (runner != BoundaryPoints[axis].begin())
-      //          *out << ", " << i << ": " << *runner->second.second;
-      //        else
-      //          *out << i << ": " << *runner->second.second;
-      //        i++;
-      //      }
-      //      *out << endl;
-      //    }
-      // 3c. throw out points whose distance is less than the mean of left and right neighbours
-      bool flag = false;
-      do
-        { // do as long as we still throw one out per round
-          *out << Verbose(1)
-              << "Looking for candidates to kick out by convex condition ... "
-              << endl;
-          flag = false;
-          Boundaries::iterator left = BoundaryPoints[axis].end();
-          Boundaries::iterator right = BoundaryPoints[axis].end();
-          for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner
-              != BoundaryPoints[axis].end(); runner++)
-            {
-              // set neighbours correctly
-              if (runner == BoundaryPoints[axis].begin())
-                {
-                  left = BoundaryPoints[axis].end();
-                }
-              else
-                {
-                  left = runner;
-                }
-              left--;
-              right = runner;
-              right++;
-              if (right == BoundaryPoints[axis].end())
-                {
-                  right = BoundaryPoints[axis].begin();
-                }
-              // check distance
-
-              // construct the vector of each side of the triangle on the projected plane (defined by normal vector AxisVector)
-                {
-                  Vector SideA, SideB, SideC, SideH;
-                  SideA.CopyVector(&left->second.second->x);
-                  SideA.ProjectOntoPlane(&AxisVector);
-                  //          *out << "SideA: ";
-                  //          SideA.Output(out);
-                  //          *out << endl;
-
-                  SideB.CopyVector(&right->second.second->x);
-                  SideB.ProjectOntoPlane(&AxisVector);
-                  //          *out << "SideB: ";
-                  //          SideB.Output(out);
-                  //          *out << endl;
-
-                  SideC.CopyVector(&left->second.second->x);
-                  SideC.SubtractVector(&right->second.second->x);
-                  SideC.ProjectOntoPlane(&AxisVector);
-                  //          *out << "SideC: ";
-                  //          SideC.Output(out);
-                  //          *out << endl;
-
-                  SideH.CopyVector(&runner->second.second->x);
-                  SideH.ProjectOntoPlane(&AxisVector);
-                  //          *out << "SideH: ";
-                  //          SideH.Output(out);
-                  //          *out << endl;
-
-                  // calculate each length
-                  double a = SideA.Norm();
-                  //double b = SideB.Norm();
-                  //double c = SideC.Norm();
-                  double h = SideH.Norm();
-                  // calculate the angles
-                  double alpha = SideA.Angle(&SideH);
-                  double beta = SideA.Angle(&SideC);
-                  double gamma = SideB.Angle(&SideH);
-                  double delta = SideC.Angle(&SideH);
-                  double MinDistance = a * sin(beta) / (sin(delta)) * (((alpha
-                      < M_PI / 2.) || (gamma < M_PI / 2.)) ? 1. : -1.);
-                  //          *out << Verbose(2) << " I calculated: a = " << a << ", h = " << h << ", beta(" << left->second.second->Name << "," << left->second.second->Name << "-" << right->second.second->Name << ") = " << beta << ", delta(" << left->second.second->Name << "," << runner->second.second->Name << ") = " << delta << ", Min = " << MinDistance << "." << endl;
-                  //*out << Verbose(1) << "Checking CoG distance of runner " << *runner->second.second << " " << h << " against triangle's side length spanned by (" << *left->second.second << "," << *right->second.second << ") of " << MinDistance << "." << endl;
-                  if ((fabs(h / fabs(h) - MinDistance / fabs(MinDistance))
-                      < MYEPSILON) && (h < MinDistance))
-                    {
-                      // throw out point
-                      //*out << Verbose(1) << "Throwing out " << *runner->second.second << "." << endl;
-                      BoundaryPoints[axis].erase(runner);
-                      flag = true;
-                    }
-                }
-            }
-        }
-      while (flag);
-    }
+      }
+    } while (flag);
+  }
+  delete(MolCenter);
   return BoundaryPoints;
 }
@@ -619,5 +714,5 @@
       *vrmlfile << "Sphere {" << endl << "  "; // 2 is sphere type
       for (i=0;i<NDIM;i++)
-        *vrmlfile << Walker->x.x[i]+center->x[i] << " ";
+        *vrmlfile << Walker->x.x[i]-center->x[i] << " ";
       *vrmlfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
     }
@@ -628,8 +723,8 @@
       *vrmlfile << "3" << endl << "  "; // 2 is round-ended cylinder type
       for (i=0;i<NDIM;i++)
-        *vrmlfile << Binder->leftatom->x.x[i]+center->x[i] << " ";
+        *vrmlfile << Binder->leftatom->x.x[i]-center->x[i] << " ";
       *vrmlfile << "\t0.03\t";
       for (i=0;i<NDIM;i++)
-        *vrmlfile << Binder->rightatom->x.x[i]+center->x[i] << " ";
+        *vrmlfile << Binder->rightatom->x.x[i]-center->x[i] << " ";
       *vrmlfile << "\t0.03\t0. 0. 1." << endl; // radius 0.05 and blue as colour
     }
@@ -640,5 +735,5 @@
       for (i=0;i<3;i++) { // print each node
         for (int j=0;j<NDIM;j++)  // and for each node all NDIM coordinates
-          *vrmlfile << TriangleRunner->second->endpoints[i]->node->x.x[j]+center->x[j] << " ";
+          *vrmlfile << TriangleRunner->second->endpoints[i]->node->x.x[j]-center->x[j] << " ";
         *vrmlfile << "\t";
       }
@@ -673,5 +768,5 @@
       *rasterfile << "2" << endl << "  ";  // 2 is sphere type
       for (i=0;i<NDIM;i++)
-        *rasterfile << Walker->x.x[i]+center->x[i] << " ";
+        *rasterfile << Walker->x.x[i]-center->x[i] << " ";
       *rasterfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
     }
@@ -682,8 +777,8 @@
       *rasterfile << "3" << endl << "  ";  // 2 is round-ended cylinder type
       for (i=0;i<NDIM;i++)
-        *rasterfile << Binder->leftatom->x.x[i]+center->x[i] << " ";
+        *rasterfile << Binder->leftatom->x.x[i]-center->x[i] << " ";
       *rasterfile << "\t0.03\t";
       for (i=0;i<NDIM;i++)
-        *rasterfile << Binder->rightatom->x.x[i]+center->x[i] << " ";
+        *rasterfile << Binder->rightatom->x.x[i]-center->x[i] << " ";
       *rasterfile << "\t0.03\t0. 0. 1." << endl; // radius 0.05 and blue as colour
     }
@@ -695,5 +790,5 @@
       for (i=0;i<3;i++) {  // print each node
         for (int j=0;j<NDIM;j++)  // and for each node all NDIM coordinates
-          *rasterfile << TriangleRunner->second->endpoints[i]->node->x.x[j]+center->x[j] << " ";
+          *rasterfile << TriangleRunner->second->endpoints[i]->node->x.x[j]-center->x[j] << " ";
         *rasterfile << "\t";
       }
@@ -713,110 +808,82 @@
  * \param N arbitrary number to differentiate various zones in the tecplot format
  */
-void
-write_tecplot_file(ofstream *out, ofstream *tecplot,
-    class Tesselation *TesselStruct, class molecule *mol, int N)
-{
-  if (tecplot != NULL)
-    {
-      *tecplot << "TITLE = \"3D CONVEX SHELL\"" << endl;
-      *tecplot << "VARIABLES = \"X\" \"Y\" \"Z\"" << endl;
-      *tecplot << "ZONE T=\"TRIANGLES" << N << "\", N="
-          << TesselStruct->PointsOnBoundaryCount << ", E="
-          << TesselStruct->TrianglesOnBoundaryCount
-          << ", DATAPACKING=POINT, ZONETYPE=FETRIANGLE" << endl;
-      int *LookupList = new int[mol->AtomCount];
-      for (int i = 0; i < mol->AtomCount; i++)
-        LookupList[i] = -1;
-
-      // print atom coordinates
-      *out << Verbose(2) << "The following triangles were created:";
-      int Counter = 1;
-      atom *Walker = NULL;
-      for (PointMap::iterator target = TesselStruct->PointsOnBoundary.begin(); target
-          != TesselStruct->PointsOnBoundary.end(); target++)
-        {
-          Walker = target->second->node;
-          LookupList[Walker->nr] = Counter++;
-          *tecplot << Walker->x.x[0] << " " << Walker->x.x[1] << " "
-              << Walker->x.x[2] << " " << endl;
-        }
-      *tecplot << endl;
-      // print connectivity
-      for (TriangleMap::iterator runner =
-          TesselStruct->TrianglesOnBoundary.begin(); runner
-          != TesselStruct->TrianglesOnBoundary.end(); runner++)
-        {
-          *out << " " << runner->second->endpoints[0]->node->Name << "<->"
-              << runner->second->endpoints[1]->node->Name << "<->"
-              << runner->second->endpoints[2]->node->Name;
-          *tecplot << LookupList[runner->second->endpoints[0]->node->nr] << " "
-              << LookupList[runner->second->endpoints[1]->node->nr] << " "
-              << LookupList[runner->second->endpoints[2]->node->nr] << endl;
-        }
-      delete[] (LookupList);
-      *out << endl;
-    }
-}
-
-/** Determines the volume of a cluster.
- * Determines first the convex envelope, then tesselates it and calculates its volume.
+void write_tecplot_file(ofstream *out, ofstream *tecplot, class Tesselation *TesselStruct, class molecule *mol, int N)
+{
+  if (tecplot != NULL) {
+    *tecplot << "TITLE = \"3D CONVEX SHELL\"" << endl;
+    *tecplot << "VARIABLES = \"X\" \"Y\" \"Z\"" << endl;
+    *tecplot << "ZONE T=\"TRIANGLES" << N << "\", N=" << TesselStruct->PointsOnBoundaryCount << ", E=" << TesselStruct->TrianglesOnBoundaryCount << ", DATAPACKING=POINT, ZONETYPE=FETRIANGLE" << endl;
+    int *LookupList = new int[mol->AtomCount];
+    for (int i = 0; i < mol->AtomCount; i++)
+      LookupList[i] = -1;
+
+    // print atom coordinates
+    *out << Verbose(2) << "The following triangles were created:";
+    int Counter = 1;
+    atom *Walker = NULL;
+    for (PointMap::iterator target = TesselStruct->PointsOnBoundary.begin(); target != TesselStruct->PointsOnBoundary.end(); target++) {
+      Walker = target->second->node;
+      LookupList[Walker->nr] = Counter++;
+      *tecplot << Walker->x.x[0] << " " << Walker->x.x[1] << " " << Walker->x.x[2] << " " << endl;
+    }
+    *tecplot << endl;
+    // print connectivity
+    for (TriangleMap::iterator runner = TesselStruct->TrianglesOnBoundary.begin(); runner != TesselStruct->TrianglesOnBoundary.end(); runner++) {
+      *out << " " << runner->second->endpoints[0]->node->Name << "<->" << runner->second->endpoints[1]->node->Name << "<->" << runner->second->endpoints[2]->node->Name;
+      *tecplot << LookupList[runner->second->endpoints[0]->node->nr] << " " << LookupList[runner->second->endpoints[1]->node->nr] << " " << LookupList[runner->second->endpoints[2]->node->nr] << endl;
+    }
+    delete[] (LookupList);
+    *out << endl;
+  }
+}
+
+/** Tesselates the convex boundary by finding all boundary points.
  * \param *out output stream for debugging
+ * \param *mol molecule structure with Atom's and Bond's
+ * \param *TesselStruct Tesselation filled with points, lines and triangles on boundary on return
+ * \param *LCList atoms in LinkedCell list
  * \param *filename filename prefix for output of vertex data
- * \param *configuration needed for path to store convex envelope file
- * \param *BoundaryPoints NDIM set of boundary points on the projected plane per axis, on return if desired
- * \param *mol molecule structure representing the cluster
- * \return determined volume of the cluster in cubed config:GetIsAngstroem()
- */
-double
-VolumeOfConvexEnvelope(ofstream *out, const char *filename, config *configuration,
-    Boundaries *BoundaryPtr, molecule *mol)
-{
-  bool IsAngstroem = configuration->GetIsAngstroem();
-  atom *Walker = NULL;
-  struct Tesselation *TesselStruct = new Tesselation;
+ * \return *TesselStruct is filled with convex boundary and tesselation is stored under \a *filename.
+ */
+void Find_convex_border(ofstream *out, molecule* mol, class Tesselation *&TesselStruct, class LinkedCell *LCList, const char *filename)
+{
   bool BoundaryFreeFlag = false;
-  Boundaries *BoundaryPoints = BoundaryPtr;
-  double volume = 0.;
-  double PyramidVolume = 0.;
-  double G, h;
-  Vector x, y;
-  double a, b, c;
-
-  //Find_non_convex_border(out, tecplot, *TesselStruct, mol); // Is now called from command line.
-
-  // 1. calculate center of gravity
-  *out << endl;
-  Vector *CenterOfGravity = mol->DetermineCenterOfGravity(out);
-
-  // 2. translate all points into CoG
-  *out << Verbose(1) << "Translating system to Center of Gravity." << endl;
-  Walker = mol->start;
-  while (Walker->next != mol->end)
-    {
-      Walker = Walker->next;
-      Walker->x.Translate(CenterOfGravity);
-    }
-
-  // 3. Find all points on the boundary
-  if (BoundaryPoints == NULL)
-    {
+  Boundaries *BoundaryPoints = NULL;
+
+  cout << Verbose(1) << "Begin of find_convex_border" << endl;
+
+  if (TesselStruct != NULL) // free if allocated
+    delete(TesselStruct);
+  TesselStruct = new class Tesselation;
+
+  // 1. Find all points on the boundary
+  if (BoundaryPoints == NULL) {
       BoundaryFreeFlag = true;
       BoundaryPoints = GetBoundaryPoints(out, mol);
-    }
-  else
+  } else {
+      *out << Verbose(1) << "Using given boundary points set." << endl;
+  }
+
+// printing all inserted for debugging
+  for (int axis=0; axis < NDIM; axis++)
     {
-      *out << Verbose(1) << "Using given boundary points set." << endl;
-    }
-
-  // 4. fill the boundary point list
+      *out << Verbose(2) << "Printing list of candidates for axis " << axis << " which we have inserted so far." << endl;
+      int i=0;
+      for(Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++) {
+        if (runner != BoundaryPoints[axis].begin())
+          *out << ", " << i << ": " << *runner->second.second;
+        else
+          *out << i << ": " << *runner->second.second;
+        i++;
+      }
+      *out << endl;
+    }
+
+  // 2. fill the boundary point list
   for (int axis = 0; axis < NDIM; axis++)
-    for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner
-        != BoundaryPoints[axis].end(); runner++)
-      {
+    for (Boundaries::iterator runner = BoundaryPoints[axis].begin(); runner != BoundaryPoints[axis].end(); runner++)
         TesselStruct->AddPoint(runner->second.second);
-      }
-
-  *out << Verbose(2) << "I found " << TesselStruct->PointsOnBoundaryCount
-      << " points on the convex boundary." << endl;
+
+  *out << Verbose(2) << "I found " << TesselStruct->PointsOnBoundaryCount << " points on the convex boundary." << endl;
   // now we have the whole set of edge points in the BoundaryList
 
@@ -828,14 +895,63 @@
   //  *out << endl;
 
-  // 5a. guess starting triangle
+  // 3a. guess starting triangle
   TesselStruct->GuessStartingTriangle(out);
 
-  // 5b. go through all lines, that are not yet part of two triangles (only of one so far)
-  TesselStruct->TesselateOnBoundary(out, configuration, mol);
-
-  *out << Verbose(2) << "I created " << TesselStruct->TrianglesOnBoundaryCount
-      << " triangles with " << TesselStruct->LinesOnBoundaryCount
-      << " lines and " << TesselStruct->PointsOnBoundaryCount << " points."
-      << endl;
+  // 3b. go through all lines, that are not yet part of two triangles (only of one so far)
+  TesselStruct->TesselateOnBoundary(out, mol);
+
+  // 3c. check whether all atoms lay inside the boundary, if not, add to boundary points, segment triangle into three with the new point
+  if (!TesselStruct->InsertStraddlingPoints(out, mol))
+    *out << Verbose(1) << "Insertion of straddling points failed!" << endl;
+
+  // 3d. check all baselines whether the peaks of the two adjacent triangles with respect to center of baseline are convex, if not, make the baseline between the two peaks and baseline endpoints become the new peaks
+  if (!TesselStruct->CorrectConcaveBaselines(out))
+    *out << Verbose(1) << "Correction of concave baselines failed!" << endl;
+
+  *out << Verbose(2) << "I created " << TesselStruct->TrianglesOnBoundary.size() << " triangles with " << TesselStruct->LinesOnBoundary.size() << " lines and " << TesselStruct->PointsOnBoundary.size() << " points." << endl;
+
+  // 4. Store triangles in tecplot file
+  if (filename != NULL) {
+    if (DoTecplotOutput) {
+      string OutputName(filename);
+      OutputName.append(TecplotSuffix);
+      ofstream *tecplot = new ofstream(OutputName.c_str());
+      write_tecplot_file(out, tecplot, TesselStruct, mol, 0);
+      tecplot->close();
+      delete(tecplot);
+    }
+    if (DoRaster3DOutput) {
+      string OutputName(filename);
+      OutputName.append(Raster3DSuffix);
+      ofstream *rasterplot = new ofstream(OutputName.c_str());
+      write_raster3d_file(out, rasterplot, TesselStruct, mol);
+      rasterplot->close();
+      delete(rasterplot);
+    }
+  }
+
+  // free reference lists
+  if (BoundaryFreeFlag)
+    delete[] (BoundaryPoints);
+
+  cout << Verbose(1) << "End of find_convex_border" << endl;
+};
+
+
+/** Determines the volume of a cluster.
+ * Determines first the convex envelope, then tesselates it and calculates its volume.
+ * \param *out output stream for debugging
+ * \param *TesselStruct Tesselation filled with points, lines and triangles on boundary on return
+ * \param *configuration needed for path to store convex envelope file
+ * \return determined volume of the cluster in cubed config:GetIsAngstroem()
+ */
+double VolumeOfConvexEnvelope(ofstream *out, class Tesselation *TesselStruct, class config *configuration)
+{
+  bool IsAngstroem = configuration->GetIsAngstroem();
+  double volume = 0.;
+  double PyramidVolume = 0.;
+  double G, h;
+  Vector x, y;
+  double a, b, c;
 
   // 6a. Every triangle forms a pyramid with the center of gravity as its peak, sum up the volumes
@@ -873,27 +989,4 @@
       << endl;
 
-  // 7. translate all points back from CoG
-  *out << Verbose(1) << "Translating system back from Center of Gravity."
-      << endl;
-  CenterOfGravity->Scale(-1);
-  Walker = mol->start;
-  while (Walker->next != mol->end)
-    {
-      Walker = Walker->next;
-      Walker->x.Translate(CenterOfGravity);
-    }
-
-  // 8. Store triangles in tecplot file
-  string OutputName(filename);
-  OutputName.append(TecplotSuffix);
-  ofstream *tecplot = new ofstream(OutputName.c_str());
-  write_tecplot_file(out, tecplot, TesselStruct, mol, 0);
-  tecplot->close();
-  delete(tecplot);
-
-  // free reference lists
-  if (BoundaryFreeFlag)
-    delete[] (BoundaryPoints);
-
   return volume;
 }
@@ -918,12 +1011,13 @@
   bool IsAngstroem = configuration->GetIsAngstroem();
   Boundaries *BoundaryPoints = GetBoundaryPoints(out, mol);
+  class Tesselation *TesselStruct = NULL;
+  LinkedCell LCList(mol, 10.);
+  Find_convex_border(out, mol, TesselStruct, &LCList, NULL);
   double clustervolume;
   if (ClusterVolume == 0)
-    clustervolume = VolumeOfConvexEnvelope(out, NULL, configuration,
-        BoundaryPoints, mol);
+    clustervolume = VolumeOfConvexEnvelope(out, TesselStruct, configuration);
   else
     clustervolume = ClusterVolume;
-  double *GreatestDiameter = GetDiametersOfCluster(out, BoundaryPoints, mol,
-      IsAngstroem);
+  double *GreatestDiameter = GetDiametersOfCluster(out, BoundaryPoints, mol, IsAngstroem);
   Vector BoxLengths;
   int repetition[NDIM] =
@@ -1010,5 +1104,6 @@
       // set new box dimensions
       *out << Verbose(0) << "Translating to box with these boundaries." << endl;
-      mol->CenterInBox((ofstream *) &cout, &BoxLengths);
+      mol->SetBoxDimension(&BoxLengths);
+      mol->CenterInBox((ofstream *) &cout);
     }
   // update Box of atoms by boundary
@@ -1020,4 +1115,116 @@
 }
 ;
+
+
+/** Fills the empty space of the simulation box with water/
+ * \param *out output stream for debugging
+ * \param *List list of molecules already present in box
+ * \param *TesselStruct contains tesselated surface
+ * \param *filler molecule which the box is to be filled with
+ * \param configuration contains box dimensions
+ * \param distance[NDIM] distance between filling molecules in each direction
+ * \param RandAtomDisplacement maximum distance for random displacement per atom
+ * \param RandMolDisplacement maximum distance for random displacement per filler molecule
+ * \param DoRandomRotation true - do random rotiations, false - don't
+ * \return *mol pointer to new molecule with filled atoms
+ */
+molecule * FillBoxWithMolecule(ofstream *out, MoleculeListClass *List, molecule *filler, config &configuration, double distance[NDIM], double RandomAtomDisplacement, double RandomMolDisplacement, bool DoRandomRotation)
+{
+  molecule *Filling = new molecule(filler->elemente);
+  Vector CurrentPosition;
+  int N[NDIM];
+  int n[NDIM];
+  double *M =  filler->ReturnFullMatrixforSymmetric(filler->cell_size);
+  double Rotations[NDIM*NDIM];
+  Vector AtomTranslations;
+  Vector FillerTranslations;
+  Vector FillerDistance;
+  double FillIt = false;
+  atom *Walker = NULL, *Runner = NULL;
+  bond *Binder = NULL;
+
+  // Center filler at origin
+  filler->CenterOrigin(out);
+  filler->Center.Zero();
+
+  // calculate filler grid in [0,1]^3
+  FillerDistance.Init(distance[0], distance[1], distance[2]);
+  FillerDistance.InverseMatrixMultiplication(M);
+  for(int i=0;i<NDIM;i++)
+    N[i] = (int) ceil(1./FillerDistance.x[i]);
+
+  // go over [0,1]^3 filler grid
+  for (n[0] = 0; n[0] < N[0]; n[0]++)
+    for (n[1] = 0; n[1] < N[1]; n[1]++)
+      for (n[2] = 0; n[2] < N[2]; n[2]++) {
+        // calculate position of current grid vector in untransformed box
+        CurrentPosition.Init(n[0], n[1], n[2]);
+        CurrentPosition.MatrixMultiplication(M);
+        // Check whether point is in- or outside
+        FillIt = true;
+        for (MoleculeList::iterator ListRunner = List->ListOfMolecules.begin(); ListRunner != List->ListOfMolecules.end(); ListRunner++) {
+          //FillIt = FillIt && (!(*ListRunner)->TesselStruct->IsInside(&CurrentPosition));
+        }
+
+        if (FillIt) {
+          // fill in Filler
+          *out << Verbose(2) << "Space at " << CurrentPosition << " is unoccupied by any molecule, filling in." << endl;
+
+          // create molecule random translation vector ...
+          for (int i=0;i<NDIM;i++)
+            FillerTranslations.x[i] = RandomMolDisplacement*(rand()/(RAND_MAX/2.) - 1.);
+
+          // go through all atoms
+          Walker = filler->start;
+          while (Walker != filler->end) {
+            Walker = Walker->next;
+            // copy atom ...
+            *Runner = new atom(Walker);
+
+            // create atomic random translation vector ...
+            for (int i=0;i<NDIM;i++)
+              AtomTranslations.x[i] = RandomAtomDisplacement*(rand()/(RAND_MAX/2.) - 1.);
+
+            // ... and rotation matrix
+            if (DoRandomRotation) {
+              double phi[NDIM];
+              for (int i=0;i<NDIM;i++) {
+                phi[i] = rand()/(RAND_MAX/(2.*M_PI));
+              }
+
+              Rotations[0] =   cos(phi[0])            *cos(phi[2]) + (sin(phi[0])*sin(phi[1])*sin(phi[2]));
+              Rotations[3] =   sin(phi[0])            *cos(phi[2]) - (cos(phi[0])*sin(phi[1])*sin(phi[2]));
+              Rotations[6] =               cos(phi[1])*sin(phi[2])                                     ;
+              Rotations[1] = - sin(phi[0])*cos(phi[1])                                                ;
+              Rotations[4] =   cos(phi[0])*cos(phi[1])                                                ;
+              Rotations[7] =               sin(phi[1])                                                ;
+              Rotations[3] = - cos(phi[0])            *sin(phi[2]) + (sin(phi[0])*sin(phi[1])*cos(phi[2]));
+              Rotations[5] = - sin(phi[0])            *sin(phi[2]) - (cos(phi[0])*sin(phi[1])*cos(phi[2]));
+              Rotations[8] =               cos(phi[1])*cos(phi[2])                                     ;
+            }
+
+            // ... and put at new position
+            if (DoRandomRotation)
+              Runner->x.MatrixMultiplication(Rotations);
+            Runner->x.AddVector(&AtomTranslations);
+            Runner->x.AddVector(&FillerTranslations);
+            Runner->x.AddVector(&CurrentPosition);
+            // insert into Filling
+            Filling->AddAtom(Runner);
+          }
+
+          // go through all bonds and add as well
+          Binder = filler->first;
+          while(Binder != filler->last) {
+            Binder = Binder->next;
+          }
+        } else {
+          // leave empty
+          *out << Verbose(2) << "Space at " << CurrentPosition << " is occupied." << endl;
+        }
+      }
+  return Filling;
+};
+
 
 // =========================================================== class TESSELATION ===========================================
@@ -1133,5 +1340,5 @@
                   << A->second->node->Name << ","
                   << baseline->second.first->second->node->Name << ","
-                  << baseline->second.second->second->node->Name << " leave "
+                  << baseline->second.second->second->node->Name << " leaves "
                   << checker->second->node->Name << " outside the convex hull."
                   << endl;
@@ -1218,7 +1425,7 @@
  * -# if the lines contains to only one triangle
  * -# We search all points in the boundary
- *    -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors
  *    -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
  *       baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
+ *    -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
  *    -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
  * \param *out output stream for debugging
@@ -1226,7 +1433,5 @@
  * \param *mol the cluster as a molecule structure
  */
-void
-Tesselation::TesselateOnBoundary(ofstream *out, config *configuration,
-    molecule *mol)
+void Tesselation::TesselateOnBoundary(ofstream *out, molecule *mol)
 {
   bool flag;
@@ -1234,221 +1439,389 @@
   class BoundaryPointSet *peak = NULL;
   double SmallestAngle, TempAngle;
-  Vector NormalVector, VirtualNormalVector, CenterVector, TempVector,
-      PropagationVector;
+  Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *MolCenter = NULL;
   LineMap::iterator LineChecker[2];
-  do
-    {
-      flag = false;
-      for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline
-          != LinesOnBoundary.end(); baseline++)
-        if (baseline->second->TrianglesCount == 1)
-          {
-            *out << Verbose(2) << "Current baseline is between "
-                << *(baseline->second) << "." << endl;
-            // 5a. go through each boundary point if not _both_ edges between either endpoint of the current line and this point exist (and belong to 2 triangles)
-            SmallestAngle = M_PI;
-            BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
-            // get peak point with respect to this base line's only triangle
-            for (int i = 0; i < 3; i++)
-              if ((BTS->endpoints[i] != baseline->second->endpoints[0])
-                  && (BTS->endpoints[i] != baseline->second->endpoints[1]))
-                peak = BTS->endpoints[i];
-            *out << Verbose(3) << " and has peak " << *peak << "." << endl;
-            // normal vector of triangle
-            BTS->GetNormalVector(NormalVector);
-            *out << Verbose(4) << "NormalVector of base triangle is ";
-            NormalVector.Output(out);
-            *out << endl;
-            // offset to center of triangle
-            CenterVector.Zero();
-            for (int i = 0; i < 3; i++)
-              CenterVector.AddVector(&BTS->endpoints[i]->node->x);
-            CenterVector.Scale(1. / 3.);
-            *out << Verbose(4) << "CenterVector of base triangle is ";
-            CenterVector.Output(out);
-            *out << endl;
-            // vector in propagation direction (out of triangle)
-            // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
+
+  MolCenter = mol->DetermineCenterOfAll(out);
+  // create a first tesselation with the given BoundaryPoints
+  do {
+    flag = false;
+    for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
+      if (baseline->second->TrianglesCount == 1) {
+        // 5a. go through each boundary point if not _both_ edges between either endpoint of the current line and this point exist (and belong to 2 triangles)
+        SmallestAngle = M_PI;
+
+        // get peak point with respect to this base line's only triangle
+        BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
+        *out << Verbose(2) << "Current baseline is between " << *(baseline->second) << "." << endl;
+        for (int i = 0; i < 3; i++)
+          if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
+            peak = BTS->endpoints[i];
+        *out << Verbose(3) << " and has peak " << *peak << "." << endl;
+
+        // prepare some auxiliary vectors
+        Vector BaseLineCenter, BaseLine;
+        BaseLineCenter.CopyVector(&baseline->second->endpoints[0]->node->x);
+        BaseLineCenter.AddVector(&baseline->second->endpoints[1]->node->x);
+        BaseLineCenter.Scale(1. / 2.); // points now to center of base line
+        BaseLine.CopyVector(&baseline->second->endpoints[0]->node->x);
+        BaseLine.SubtractVector(&baseline->second->endpoints[1]->node->x);
+
+        // offset to center of triangle
+        CenterVector.Zero();
+        for (int i = 0; i < 3; i++)
+          CenterVector.AddVector(&BTS->endpoints[i]->node->x);
+        CenterVector.Scale(1. / 3.);
+        *out << Verbose(4) << "CenterVector of base triangle is " << CenterVector << endl;
+
+        // normal vector of triangle
+        NormalVector.CopyVector(MolCenter);
+        NormalVector.SubtractVector(&CenterVector);
+        BTS->GetNormalVector(NormalVector);
+        NormalVector.CopyVector(&BTS->NormalVector);
+        *out << Verbose(4) << "NormalVector of base triangle is " << NormalVector << endl;
+
+        // vector in propagation direction (out of triangle)
+        // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
+        PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
+        TempVector.CopyVector(&CenterVector);
+        TempVector.SubtractVector(&baseline->second->endpoints[0]->node->x); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
+        //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
+        if (PropagationVector.Projection(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
+          PropagationVector.Scale(-1.);
+        *out << Verbose(4) << "PropagationVector of base triangle is " << PropagationVector << endl;
+        winner = PointsOnBoundary.end();
+
+        // loop over all points and calculate angle between normal vector of new and present triangle
+        for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
+          if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
+            *out << Verbose(3) << "Target point is " << *(target->second) << ":" << endl;
+
+            // first check direction, so that triangles don't intersect
+            VirtualNormalVector.CopyVector(&target->second->node->x);
+            VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
+            VirtualNormalVector.ProjectOntoPlane(&NormalVector);
+            TempAngle = VirtualNormalVector.Angle(&PropagationVector);
+            *out << Verbose(4) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
+            if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
+              *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
+              continue;
+            } else
+              *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
+
+            // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
+            LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
+            LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
+            if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->TrianglesCount == 2))) {
+              *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->TrianglesCount << " triangles." << endl;
+              continue;
+            }
+            if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->TrianglesCount == 2))) {
+              *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->TrianglesCount << " triangles." << endl;
+              continue;
+            }
+
+            // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
+            if ((((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (GetCommonEndpoint(LineChecker[0]->second, LineChecker[1]->second) == peak)))) {
+              *out << Verbose(4) << "Current target is peak!" << endl;
+              continue;
+            }
+
+            // check for linear dependence
             TempVector.CopyVector(&baseline->second->endpoints[0]->node->x);
-            TempVector.SubtractVector(&baseline->second->endpoints[1]->node->x);
-            PropagationVector.MakeNormalVector(&TempVector, &NormalVector);
-            TempVector.CopyVector(&CenterVector);
-            TempVector.SubtractVector(&baseline->second->endpoints[0]->node->x); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
-            //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
-            if (PropagationVector.Projection(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
-              PropagationVector.Scale(-1.);
-            *out << Verbose(4) << "PropagationVector of base triangle is ";
-            PropagationVector.Output(out);
-            *out << endl;
-            winner = PointsOnBoundary.end();
-            for (PointMap::iterator target = PointsOnBoundary.begin(); target
-                != PointsOnBoundary.end(); target++)
-              if ((target->second != baseline->second->endpoints[0])
-                  && (target->second != baseline->second->endpoints[1]))
-                { // don't take the same endpoints
-                  *out << Verbose(3) << "Target point is " << *(target->second)
-                      << ":";
-                  bool continueflag = true;
-
-                  VirtualNormalVector.CopyVector(
-                      &baseline->second->endpoints[0]->node->x);
-                  VirtualNormalVector.AddVector(
-                      &baseline->second->endpoints[0]->node->x);
-                  VirtualNormalVector.Scale(-1. / 2.); // points now to center of base line
-                  VirtualNormalVector.AddVector(&target->second->node->x); // points from center of base line to target
-                  TempAngle = VirtualNormalVector.Angle(&PropagationVector);
-                  continueflag = continueflag && (TempAngle < (M_PI/2.)); // no bends bigger than Pi/2 (90 degrees)
-                  if (!continueflag)
-                    {
-                      *out << Verbose(4)
-                          << "Angle between propagation direction and base line to "
-                          << *(target->second) << " is " << TempAngle
-                          << ", bad direction!" << endl;
-                      continue;
-                    }
-                  else
-                    *out << Verbose(4)
-                        << "Angle between propagation direction and base line to "
-                        << *(target->second) << " is " << TempAngle
-                        << ", good direction!" << endl;
-                  LineChecker[0] = baseline->second->endpoints[0]->lines.find(
-                      target->first);
-                  LineChecker[1] = baseline->second->endpoints[1]->lines.find(
-                      target->first);
-                  //            if (LineChecker[0] != baseline->second->endpoints[0]->lines.end())
-                  //              *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->TrianglesCount << " triangles." << endl;
-                  //            else
-                  //              *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has no line to " << *(target->second) << " as endpoint." << endl;
-                  //            if (LineChecker[1] != baseline->second->endpoints[1]->lines.end())
-                  //              *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->TrianglesCount << " triangles." << endl;
-                  //            else
-                  //              *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has no line to " << *(target->second) << " as endpoint." << endl;
-                  // check first endpoint (if any connecting line goes to target or at least not more than 1)
-                  continueflag = continueflag && (((LineChecker[0]
-                      == baseline->second->endpoints[0]->lines.end())
-                      || (LineChecker[0]->second->TrianglesCount == 1)));
-                  if (!continueflag)
-                    {
-                      *out << Verbose(4) << *(baseline->second->endpoints[0])
-                          << " has line " << *(LineChecker[0]->second)
-                          << " to " << *(target->second)
-                          << " as endpoint with "
-                          << LineChecker[0]->second->TrianglesCount
-                          << " triangles." << endl;
-                      continue;
-                    }
-                  // check second endpoint (if any connecting line goes to target or at least not more than 1)
-                  continueflag = continueflag && (((LineChecker[1]
-                      == baseline->second->endpoints[1]->lines.end())
-                      || (LineChecker[1]->second->TrianglesCount == 1)));
-                  if (!continueflag)
-                    {
-                      *out << Verbose(4) << *(baseline->second->endpoints[1])
-                          << " has line " << *(LineChecker[1]->second)
-                          << " to " << *(target->second)
-                          << " as endpoint with "
-                          << LineChecker[1]->second->TrianglesCount
-                          << " triangles." << endl;
-                      continue;
-                    }
-                  // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
-                  continueflag = continueflag && (!(((LineChecker[0]
-                      != baseline->second->endpoints[0]->lines.end())
-                      && (LineChecker[1]
-                          != baseline->second->endpoints[1]->lines.end())
-                      && (GetCommonEndpoint(LineChecker[0]->second,
-                          LineChecker[1]->second) == peak))));
-                  if (!continueflag)
-                    {
-                      *out << Verbose(4) << "Current target is peak!" << endl;
-                      continue;
-                    }
-                  // in case NOT both were found
-                  if (continueflag)
-                    { // create virtually this triangle, get its normal vector, calculate angle
-                      flag = true;
-                      VirtualNormalVector.MakeNormalVector(
-                          &baseline->second->endpoints[0]->node->x,
-                          &baseline->second->endpoints[1]->node->x,
-                          &target->second->node->x);
-                      // make it always point inward
-                      if (baseline->second->endpoints[0]->node->x.Projection(
-                          &VirtualNormalVector) > 0)
-                        VirtualNormalVector.Scale(-1.);
-                      // calculate angle
-                      TempAngle = NormalVector.Angle(&VirtualNormalVector);
-                      *out << Verbose(4) << "NormalVector is ";
-                      VirtualNormalVector.Output(out);
-                      *out << " and the angle is " << TempAngle << "." << endl;
-                      if (SmallestAngle > TempAngle)
-                        { // set to new possible winner
-                          SmallestAngle = TempAngle;
-                          winner = target;
-                        }
-                    }
-                }
-            // 5b. The point of the above whose triangle has the greatest angle with the triangle the current line belongs to (it only belongs to one, remember!): New triangle
-            if (winner != PointsOnBoundary.end())
-              {
-                *out << Verbose(2) << "Winning target point is "
-                    << *(winner->second) << " with angle " << SmallestAngle
-                    << "." << endl;
-                // create the lins of not yet present
-                BLS[0] = baseline->second;
-                // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
-                LineChecker[0] = baseline->second->endpoints[0]->lines.find(
-                    winner->first);
-                LineChecker[1] = baseline->second->endpoints[1]->lines.find(
-                    winner->first);
-                if (LineChecker[0]
-                    == baseline->second->endpoints[0]->lines.end())
-                  { // create
-                    BPS[0] = baseline->second->endpoints[0];
-                    BPS[1] = winner->second;
-                    BLS[1] = new class BoundaryLineSet(BPS,
-                        LinesOnBoundaryCount);
-                    LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount,
-                        BLS[1]));
-                    LinesOnBoundaryCount++;
-                  }
-                else
-                  BLS[1] = LineChecker[0]->second;
-                if (LineChecker[1]
-                    == baseline->second->endpoints[1]->lines.end())
-                  { // create
-                    BPS[0] = baseline->second->endpoints[1];
-                    BPS[1] = winner->second;
-                    BLS[2] = new class BoundaryLineSet(BPS,
-                        LinesOnBoundaryCount);
-                    LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount,
-                        BLS[2]));
-                    LinesOnBoundaryCount++;
-                  }
-                else
-                  BLS[2] = LineChecker[1]->second;
-                BTS = new class BoundaryTriangleSet(BLS,
-                    TrianglesOnBoundaryCount);
-                TrianglesOnBoundary.insert(TrianglePair(
-                    TrianglesOnBoundaryCount, BTS));
-                TrianglesOnBoundaryCount++;
-              }
-            else
-              {
-                *out << Verbose(1)
-                    << "I could not determine a winner for this baseline "
-                    << *(baseline->second) << "." << endl;
-              }
-
-            // 5d. If the set of lines is not yet empty, go to 5. and continue
+            TempVector.SubtractVector(&target->second->node->x);
+            helper.CopyVector(&baseline->second->endpoints[1]->node->x);
+            helper.SubtractVector(&target->second->node->x);
+            helper.ProjectOntoPlane(&TempVector);
+            if (fabs(helper.NormSquared()) < MYEPSILON) {
+              *out << Verbose(4) << "Chosen set of vectors is linear dependent." << endl;
+              continue;
+            }
+
+            // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
+            flag = true;
+            VirtualNormalVector.MakeNormalVector(&baseline->second->endpoints[0]->node->x, &baseline->second->endpoints[1]->node->x, &target->second->node->x);
+            TempVector.CopyVector(&baseline->second->endpoints[0]->node->x);
+            TempVector.AddVector(&baseline->second->endpoints[1]->node->x);
+            TempVector.AddVector(&target->second->node->x);
+            TempVector.Scale(1./3.);
+            TempVector.SubtractVector(MolCenter);
+            // make it always point outward
+            if (VirtualNormalVector.Projection(&TempVector) < 0)
+              VirtualNormalVector.Scale(-1.);
+            // calculate angle
+            TempAngle = NormalVector.Angle(&VirtualNormalVector);
+            *out << Verbose(4) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
+            if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
+              SmallestAngle = TempAngle;
+              winner = target;
+              *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
+            } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
+              // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
+              helper.CopyVector(&target->second->node->x);
+              helper.SubtractVector(&BaseLineCenter);
+              helper.ProjectOntoPlane(&BaseLine);
+              // ...the one with the smaller angle is the better candidate
+              TempVector.CopyVector(&target->second->node->x);
+              TempVector.SubtractVector(&BaseLineCenter);
+              TempVector.ProjectOntoPlane(&VirtualNormalVector);
+              TempAngle = TempVector.Angle(&helper);
+              TempVector.CopyVector(&winner->second->node->x);
+              TempVector.SubtractVector(&BaseLineCenter);
+              TempVector.ProjectOntoPlane(&VirtualNormalVector);
+              if (TempAngle < TempVector.Angle(&helper)) {
+                TempAngle = NormalVector.Angle(&VirtualNormalVector);
+                SmallestAngle = TempAngle;
+                winner = target;
+                *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
+              } else
+                *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
+            } else
+              *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
           }
+        } // end of loop over all boundary points
+
+        // 5b. The point of the above whose triangle has the greatest angle with the triangle the current line belongs to (it only belongs to one, remember!): New triangle
+        if (winner != PointsOnBoundary.end()) {
+          *out << Verbose(2) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
+          // create the lins of not yet present
+          BLS[0] = baseline->second;
+          // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
+          LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
+          LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
+          if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
+            BPS[0] = baseline->second->endpoints[0];
+            BPS[1] = winner->second;
+            BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
+            LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
+            LinesOnBoundaryCount++;
+          } else
+            BLS[1] = LineChecker[0]->second;
+          if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
+            BPS[0] = baseline->second->endpoints[1];
+            BPS[1] = winner->second;
+            BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
+            LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
+            LinesOnBoundaryCount++;
+          } else
+            BLS[2] = LineChecker[1]->second;
+          BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
+          TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
+          TrianglesOnBoundaryCount++;
+        } else {
+          *out << Verbose(1) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
+        }
+
+        // 5d. If the set of lines is not yet empty, go to 5. and continue
+      } else
+        *out << Verbose(2) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->TrianglesCount << "." << endl;
+  } while (flag);
+
+  // exit
+  delete(MolCenter);
+};
+
+/** Inserts all atoms outside of the tesselated surface into it by adding new triangles.
+ * \param *out output stream for debugging
+ * \param *mol molecule structure with atoms
+ * \return true - all straddling points insert, false - something went wrong
+ */
+bool Tesselation::InsertStraddlingPoints(ofstream *out, molecule *mol)
+{
+  Vector Intersection;
+  atom *Walker = mol->start;
+  Vector *MolCenter = mol->DetermineCenterOfAll(out);
+  while (Walker->next != mol->end) {  // we only have to go once through all points, as boundary can become only bigger
+    // get the next triangle
+    BTS = FindClosestTriangleToPoint(out, &Walker->x);
+    if (BTS == NULL) {
+      *out << Verbose(1) << "ERROR: No triangle closest to " << Walker << " was found." << endl;
+      return false;
+    }
+    // get the intersection point
+    if (BTS->GetIntersectionInsideTriangle(out, MolCenter, &Walker->x, &Intersection)) {
+      // we have the intersection, check whether in- or outside of boundary
+      if ((MolCenter->DistanceSquared(&Walker->x) - MolCenter->DistanceSquared(&Intersection)) < -MYEPSILON) {
+        // inside, next!
+        *out << Verbose(4) << Walker << " is inside wrt triangle " << BTS << "." << endl;
+      } else {
+        // outside!
+        *out << Verbose(3) << Walker << " is outside wrt triangle " << BTS << "." << endl;
+        class BoundaryLineSet *OldLines[3], *NewLines[3];
+        class BoundaryPointSet *OldPoints[3], *NewPoint;
+        // store the three old lines and old points
+        for (int i=0;i<3;i++) {
+          OldLines[i] = BTS->lines[i];
+          OldPoints[i] = BTS->endpoints[i];
+        }
+        // add Walker to boundary points
+        AddPoint(Walker);
+        if (BPS[0] == NULL)
+          NewPoint = BPS[0];
         else
-          *out << Verbose(2) << "Baseline candidate " << *(baseline->second)
-              << " has a triangle count of "
-              << baseline->second->TrianglesCount << "." << endl;
-    }
-  while (flag);
-
-}
-;
+          continue;
+        // remove triangle
+        TrianglesOnBoundary.erase(BTS->Nr);
+        // create three new boundary lines
+        for (int i=0;i<3;i++) {
+          BPS[0] = NewPoint;
+          BPS[1] = OldPoints[i];
+          NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
+          LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
+          LinesOnBoundaryCount++;
+        }
+        // create three new triangle with new point
+        for (int i=0;i<3;i++) { // find all baselines
+          BLS[0] = OldLines[i];
+          int n = 1;
+          for (int j=0;j<3;j++) {
+            if (NewLines[j]->IsConnectedTo(BLS[0])) {
+              if (n>2) {
+                *out << Verbose(1) << "ERROR: " << BLS[0] << " connects to all of the new lines?!" << endl;
+                return false;
+              } else
+                BLS[n++] = NewLines[j];
+            }
+          }
+          // create the triangle
+          BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
+          TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
+          TrianglesOnBoundaryCount++;
+        }
+      }
+    } else { // something is wrong with FindClosestTriangleToPoint!
+      *out << Verbose(1) << "ERROR: The closest triangle did not produce an intersection!" << endl;
+      return false;
+    }
+  }
+
+  // exit
+  delete(MolCenter);
+  return true;
+};
+
+/** Goes over all baselines and checks whether adjacent triangles and convex to each other.
+ * \param *out output stream for debugging
+ * \return true - all baselines were corrected, false - there are still concave pieces
+ */
+bool Tesselation::CorrectConcaveBaselines(ofstream *out)
+{
+  class BoundaryTriangleSet *triangle[2];
+  class BoundaryLineSet *OldLines[4], *NewLine;
+  class BoundaryPointSet *OldPoints[2];
+  Vector BaseLineNormal;
+  class BoundaryLineSet *Base = NULL;
+  int OldTriangles[2], OldBaseLine;
+  int i;
+  for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++) {
+    Base = baseline->second;
+
+    // check convexity
+    if (Base->CheckConvexityCriterion(out)) { // triangles are convex
+      *out << Verbose(3) << Base << " has two convex triangles." << endl;
+    } else { // not convex!
+      // get the two triangles
+      i=0;
+      for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
+        triangle[i++] = runner->second;
+      // gather four endpoints and four lines
+      for (int j=0;j<4;j++)
+        OldLines[j] = NULL;
+      for (int j=0;j<2;j++)
+        OldPoints[j] = NULL;
+      i=0;
+      for (int m=0;m<2;m++) { // go over both triangles
+        for (int j=0;j<3;j++) { // all of their endpoints and baselines
+          if (triangle[m]->lines[j] != Base) // pick not the central baseline
+            OldLines[i++] = triangle[m]->lines[j];
+          if (!Base->ContainsBoundaryPoint(triangle[m]->endpoints[j])) // and neither of its endpoints
+            OldPoints[m] = triangle[m]->endpoints[j];
+        }
+      }
+      if (i<4) {
+        *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
+        return false;
+      }
+      for (int j=0;j<4;j++)
+        if (OldLines[j] == NULL) {
+          *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
+          return false;
+        }
+      for (int j=0;j<2;j++)
+        if (OldPoints[j] == NULL) {
+          *out << Verbose(1) << "ERROR: We have not gathered enough endpoints!" << endl;
+          return false;
+        }
+
+      // remove triangles
+      for (int j=0;j<2;j++) {
+        OldTriangles[j] = triangle[j]->Nr;
+        TrianglesOnBoundary.erase(OldTriangles[j]);
+        triangle[j] = NULL;
+      }
+
+      // remove baseline
+      OldBaseLine = Base->Nr;
+      LinesOnBoundary.erase(OldBaseLine);
+      Base = NULL;
+
+      // construct new baseline (with same number as old one)
+      BPS[0] = OldPoints[0];
+      BPS[1] = OldPoints[1];
+      NewLine = new class BoundaryLineSet(BPS, OldBaseLine);
+      LinesOnBoundary.insert(LinePair(OldBaseLine, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
+
+      // construct new triangles with flipped baseline
+      i=-1;
+      if (BLS[0]->IsConnectedTo(OldLines[2]))
+        i=2;
+      if (BLS[0]->IsConnectedTo(OldLines[2]))
+        i=3;
+      if (i!=-1) {
+        BLS[0] = OldLines[0];
+        BLS[1] = OldLines[i];
+        BLS[2] = NewLine;
+        BTS = new class BoundaryTriangleSet(BLS, OldTriangles[0]);
+        TrianglesOnBoundary.insert(TrianglePair(OldTriangles[0], BTS));
+
+        BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
+        BLS[1] = OldLines[1];
+        BLS[2] = NewLine;
+        BTS = new class BoundaryTriangleSet(BLS, OldTriangles[1]);
+        TrianglesOnBoundary.insert(TrianglePair(OldTriangles[1], BTS));
+      } else {
+        *out << Verbose(1) << "The four old lines do not connect, something's utterly wrong here!" << endl;
+        return false;
+      }
+    }
+  }
+  return true;
+};
+
+
+/** States whether point is in- or outside of a tesselated surface.
+ * \param *pointer point to be checked
+ * \return true - is inside, false - is outside
+ */
+bool Tesselation::IsInside(Vector *pointer)
+{
+
+  // hier kommt dann Saskias Routine hin...
+
+  return true;
+};
+
+/** Finds the closest triangle to a given point.
+ * \param *out output stream for debugging
+ * \param *x second endpoint of line
+ * \return pointer triangle that is closest, NULL if none was found
+ */
+class BoundaryTriangleSet * Tesselation::FindClosestTriangleToPoint(ofstream *out, Vector *x)
+{
+  class BoundaryTriangleSet *triangle = NULL;
+
+  // hier kommt dann Saskias Routine hin...
+
+  return triangle;
+};
 
 /** Adds an atom to the tesselation::PointsOnBoundary list.
@@ -1463,4 +1836,8 @@
   if (InsertUnique.second) // if new point was not present before, increase counter
     PointsOnBoundaryCount++;
+  else {
+    delete(BPS[0]);
+    BPS[0] = NULL;
+  }
 }
 ;
@@ -1904,6 +2281,6 @@
   Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
   Vector SphereCenter;
-  Vector NewSphereCenter;	 // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
-  Vector OtherNewSphereCenter;	 // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
+  Vector NewSphereCenter;   // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
+  Vector OtherNewSphereCenter;   // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
   Vector NewNormalVector;   // normal vector of the Candidate's triangle
   Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
@@ -1985,5 +2362,5 @@
 
                   if ((NewNormalVector.MakeNormalVector(&(BaseLine->endpoints[0]->node->x), &(BaseLine->endpoints[1]->node->x), &(Candidate->x)))
-                	&& (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
+                  && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
                   ) {
                     helper.CopyVector(&NewNormalVector);
@@ -2072,6 +2449,6 @@
   //cout << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
   if (candidates->size() > 1) {
-	  candidates->unique();
-	  candidates->sort(sortCandidates);
+    candidates->unique();
+    candidates->sort(sortCandidates);
   }
 
@@ -2080,8 +2457,8 @@
 
 struct Intersection {
-	Vector x1;
-	Vector x2;
-	Vector x3;
-	Vector x4;
+  Vector x1;
+  Vector x2;
+  Vector x3;
+  Vector x4;
 };
 
@@ -2093,27 +2470,27 @@
  */
 double MinIntersectDistance(const gsl_vector * x, void *params) {
-	double retval = 0;
-	struct Intersection *I = (struct Intersection *)params;
-	Vector intersection;
-	Vector SideA,SideB,HeightA, HeightB;
-	for (int i=0;i<NDIM;i++)
-		intersection.x[i] = gsl_vector_get(x, i);
-
-	SideA.CopyVector(&(I->x1));
-	SideA.SubtractVector(&I->x2);
-	HeightA.CopyVector(&intersection);
-	HeightA.SubtractVector(&I->x1);
-	HeightA.ProjectOntoPlane(&SideA);
-
-	SideB.CopyVector(&I->x3);
-	SideB.SubtractVector(&I->x4);
-	HeightB.CopyVector(&intersection);
-	HeightB.SubtractVector(&I->x3);
-	HeightB.ProjectOntoPlane(&SideB);
-
-	retval = HeightA.ScalarProduct(&HeightA) + HeightB.ScalarProduct(&HeightB);
-	//cout << Verbose(2) << "MinIntersectDistance called, result: " << retval << endl;
-
-	return retval;
+  double retval = 0;
+  struct Intersection *I = (struct Intersection *)params;
+  Vector intersection;
+  Vector SideA,SideB,HeightA, HeightB;
+  for (int i=0;i<NDIM;i++)
+    intersection.x[i] = gsl_vector_get(x, i);
+
+  SideA.CopyVector(&(I->x1));
+  SideA.SubtractVector(&I->x2);
+  HeightA.CopyVector(&intersection);
+  HeightA.SubtractVector(&I->x1);
+  HeightA.ProjectOntoPlane(&SideA);
+
+  SideB.CopyVector(&I->x3);
+  SideB.SubtractVector(&I->x4);
+  HeightB.CopyVector(&intersection);
+  HeightB.SubtractVector(&I->x3);
+  HeightB.ProjectOntoPlane(&SideB);
+
+  retval = HeightA.ScalarProduct(&HeightA) + HeightB.ScalarProduct(&HeightB);
+  //cout << Verbose(2) << "MinIntersectDistance called, result: " << retval << endl;
+
+  return retval;
 };
 
@@ -2132,11 +2509,11 @@
  */
 bool existsIntersection(Vector point1, Vector point2, Vector point3, Vector point4) {
-	bool result;
-
-	struct Intersection par;
-		par.x1.CopyVector(&point1);
-		par.x2.CopyVector(&point2);
-		par.x3.CopyVector(&point3);
-		par.x4.CopyVector(&point4);
+  bool result;
+
+  struct Intersection par;
+    par.x1.CopyVector(&point1);
+    par.x2.CopyVector(&point2);
+    par.x3.CopyVector(&point3);
+    par.x4.CopyVector(&point4);
 
     const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
@@ -2179,47 +2556,47 @@
 
         if (status == GSL_SUCCESS) {
-        	cout << Verbose(2) << "converged to minimum" <<  endl;
+          cout << Verbose(2) << "converged to minimum" <<  endl;
         }
     } while (status == GSL_CONTINUE && iter < 100);
 
     // check whether intersection is in between or not
-	Vector intersection, SideA, SideB, HeightA, HeightB;
-	double t1, t2;
-	for (int i = 0; i < NDIM; i++) {
-		intersection.x[i] = gsl_vector_get(s->x, i);
-	}
-
-	SideA.CopyVector(&par.x2);
-	SideA.SubtractVector(&par.x1);
-	HeightA.CopyVector(&intersection);
-	HeightA.SubtractVector(&par.x1);
-
-	t1 = HeightA.Projection(&SideA)/SideA.ScalarProduct(&SideA);
-
-	SideB.CopyVector(&par.x4);
-	SideB.SubtractVector(&par.x3);
-	HeightB.CopyVector(&intersection);
-	HeightB.SubtractVector(&par.x3);
-
-	t2 = HeightB.Projection(&SideB)/SideB.ScalarProduct(&SideB);
-
-	cout << Verbose(2) << "Intersection " << intersection << " is at "
-		<< t1 << " for (" << point1 << "," << point2 << ") and at "
-		<< t2 << " for (" << point3 << "," << point4 << "): ";
-
-	if (((t1 >= 0) && (t1 <= 1)) && ((t2 >= 0) && (t2 <= 1))) {
-		cout << "true intersection." << endl;
-		result = true;
-	} else {
-		cout << "intersection out of region of interest." << endl;
-		result = false;
-	}
-
-	// free minimizer stuff
+  Vector intersection, SideA, SideB, HeightA, HeightB;
+  double t1, t2;
+  for (int i = 0; i < NDIM; i++) {
+    intersection.x[i] = gsl_vector_get(s->x, i);
+  }
+
+  SideA.CopyVector(&par.x2);
+  SideA.SubtractVector(&par.x1);
+  HeightA.CopyVector(&intersection);
+  HeightA.SubtractVector(&par.x1);
+
+  t1 = HeightA.Projection(&SideA)/SideA.ScalarProduct(&SideA);
+
+  SideB.CopyVector(&par.x4);
+  SideB.SubtractVector(&par.x3);
+  HeightB.CopyVector(&intersection);
+  HeightB.SubtractVector(&par.x3);
+
+  t2 = HeightB.Projection(&SideB)/SideB.ScalarProduct(&SideB);
+
+  cout << Verbose(2) << "Intersection " << intersection << " is at "
+    << t1 << " for (" << point1 << "," << point2 << ") and at "
+    << t2 << " for (" << point3 << "," << point4 << "): ";
+
+  if (((t1 >= 0) && (t1 <= 1)) && ((t2 >= 0) && (t2 <= 1))) {
+    cout << "true intersection." << endl;
+    result = true;
+  } else {
+    cout << "intersection out of region of interest." << endl;
+    result = false;
+  }
+
+  // free minimizer stuff
     gsl_vector_free(x);
     gsl_vector_free(ss);
     gsl_multimin_fminimizer_free(s);
 
-	return result;
+  return result;
 }
 
@@ -2241,5 +2618,5 @@
   int N[NDIM], Nlower[NDIM], Nupper[NDIM];
 
-  if (LC->SetIndexToAtom(*a)) {  // get cell for the starting atom
+  if (LC->SetIndexToAtom(a)) {  // get cell for the starting atom
     for(int i=0;i<NDIM;i++) // store indices of this cell
       N[i] = LC->n[i];
@@ -2603,5 +2980,5 @@
   cout << Verbose(1) << "Third Points are ";
   for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
-	  cout << " " << *(*it)->point;
+    cout << " " << *(*it)->point;
   }
   cout << endl;
@@ -2609,18 +2986,18 @@
   BoundaryLineSet *BaseRay = &Line;
   for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
-	  cout << Verbose(1) << " Third point candidate is " << *(*it)->point
-		<< " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
-	  cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
-
-	  // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
-	  atom *AtomCandidates[3];
-	  AtomCandidates[0] = (*it)->point;
-	  AtomCandidates[1] = BaseRay->endpoints[0]->node;
-	  AtomCandidates[2] = BaseRay->endpoints[1]->node;
-	  int existentTrianglesCount = CheckPresenceOfTriangle(out, AtomCandidates);
-
-	  BTS = NULL;
-	  // If there is no triangle, add it regularly.
-	  if (existentTrianglesCount == 0) {
+    cout << Verbose(1) << " Third point candidate is " << *(*it)->point
+    << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
+    cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
+
+    // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
+    atom *AtomCandidates[3];
+    AtomCandidates[0] = (*it)->point;
+    AtomCandidates[1] = BaseRay->endpoints[0]->node;
+    AtomCandidates[2] = BaseRay->endpoints[1]->node;
+    int existentTrianglesCount = CheckPresenceOfTriangle(out, AtomCandidates);
+
+    BTS = NULL;
+    // If there is no triangle, add it regularly.
+    if (existentTrianglesCount == 0) {
       AddTrianglePoint((*it)->point, 0);
       AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
@@ -2640,5 +3017,5 @@
         << " for this triangle ... " << endl;
       //cout << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
-	  } else if (existentTrianglesCount == 1) { // If there is a planar region within the structure, we need this triangle a second time.
+    } else if (existentTrianglesCount == 1) { // If there is a planar region within the structure, we need this triangle a second time.
         AddTrianglePoint((*it)->point, 0);
         AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
@@ -2679,5 +3056,5 @@
     }
 
-	  if ((result) && (existentTrianglesCount < 2) && (DoSingleStepOutput && (TrianglesOnBoundaryCount % 1 == 0))) { // if we have a new triangle and want to output each new triangle configuration
+    if ((result) && (existentTrianglesCount < 2) && (DoSingleStepOutput && (TrianglesOnBoundaryCount % 1 == 0))) { // if we have a new triangle and want to output each new triangle configuration
       sprintf(NumberName, "-%04d-%s_%s_%s", TriangleFilesWritten, BTS->endpoints[0]->node->Name, BTS->endpoints[1]->node->Name, BTS->endpoints[2]->node->Name);
       if (DoTecplotOutput) {
@@ -2711,5 +3088,5 @@
         (*it)->OptCenter.AddVector(&helper);
         Vector *center = mol->DetermineCenterOfAll(out);
-        (*it)->OptCenter.AddVector(center);
+        (*it)->OptCenter.SubtractVector(center);
         delete(center);
         // and add to file plus translucency object
@@ -2726,8 +3103,8 @@
       if (DoTecplotOutput || DoRaster3DOutput)
         TriangleFilesWritten++;
-	  }
+    }
 
     // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
-	  BaseRay = BLS[0];
+    BaseRay = BLS[0];
   }
 
@@ -2760,30 +3137,30 @@
 
   // create normal in-plane vector to cope with acos() non-uniqueness on [0,2pi] (note that is pointing in the "right" direction already, hence ">0" test!)
-	helper.CopyVector(&(candidate1->BaseLine->endpoints[0]->node->x));
-	helper.SubtractVector(&(candidate1->point->x));
-	OrthogonalVector.CopyVector(&helper);
-	helper.VectorProduct(&BaseLineVector);
-	OrthogonalVector.SubtractVector(&helper);
-	OrthogonalVector.Normalize();
+  helper.CopyVector(&(candidate1->BaseLine->endpoints[0]->node->x));
+  helper.SubtractVector(&(candidate1->point->x));
+  OrthogonalVector.CopyVector(&helper);
+  helper.VectorProduct(&BaseLineVector);
+  OrthogonalVector.SubtractVector(&helper);
+  OrthogonalVector.Normalize();
 
   // calculate both angles and correct with in-plane vector
-	helper.CopyVector(&(candidate1->point->x));
-	helper.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
-	double phi = BaseLineVector.Angle(&helper);
+  helper.CopyVector(&(candidate1->point->x));
+  helper.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
+  double phi = BaseLineVector.Angle(&helper);
   if (OrthogonalVector.ScalarProduct(&helper) > 0) {
     phi = 2.*M_PI - phi;
   }
   helper.CopyVector(&(candidate2->point->x));
-	helper.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
-	double psi = BaseLineVector.Angle(&helper);
+  helper.SubtractVector(&(candidate1->BaseLine->endpoints[0]->node->x));
+  double psi = BaseLineVector.Angle(&helper);
   if (OrthogonalVector.ScalarProduct(&helper) > 0) {
-		psi = 2.*M_PI - psi;
-	}
-
-	cout << Verbose(2) << *candidate1->point << " has angle " << phi << endl;
-	cout << Verbose(2) << *candidate2->point << " has angle " << psi << endl;
-
-	// return comparison
-	return phi < psi;
+    psi = 2.*M_PI - psi;
+  }
+
+  cout << Verbose(2) << *candidate1->point << " has angle " << phi << endl;
+  cout << Verbose(2) << *candidate2->point << " has angle " << psi << endl;
+
+  // return comparison
+  return phi < psi;
 }
 
@@ -3090,4 +3467,5 @@
  * \param *mol molecule structure with Atom's and Bond's
  * \param *Tess Tesselation filled with points, lines and triangles on boundary on return
+ * \param *LCList atoms in LinkedCell list
  * \param *filename filename prefix for output of vertex data
  * \para RADIUS radius of the virtual sphere
@@ -3137,5 +3515,5 @@
     }
   }
-  if (1) { //failflag) {
+  if (filename != 0) {
     *out << Verbose(1) << "Writing final tecplot file\n";
     if (DoTecplotOutput) {
Index: src/boundary.hpp
===================================================================
--- src/boundary.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/boundary.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -54,4 +54,7 @@
 
     void AddTriangle(class BoundaryTriangleSet *triangle);
+    bool IsConnectedTo(class BoundaryLineSet *line);
+    bool ContainsBoundaryPoint(class BoundaryPointSet *point);
+    bool CheckConvexityCriterion(ofstream *out);
 
     class BoundaryPointSet *endpoints[2];
@@ -68,4 +71,7 @@
 
     void GetNormalVector(Vector &NormalVector);
+    bool GetIntersectionInsideTriangle(ofstream *out, Vector *MolCenter, Vector *x, Vector *Intersection);
+    bool ContainsBoundaryLine(class BoundaryLineSet *line);
+    bool ContainsBoundaryPoint(class BoundaryPointSet *point);
 
     class BoundaryPointSet *endpoints[3];
@@ -78,10 +84,10 @@
 class CandidateForTesselation {
   public :
-	CandidateForTesselation(atom* candidate, BoundaryLineSet* currentBaseLine, Vector OptCandidateCenter, Vector OtherOptCandidateCenter);
-	~CandidateForTesselation();
-	atom *point;
-	BoundaryLineSet *BaseLine;
-	Vector OptCenter;
-	Vector OtherOptCenter;
+  CandidateForTesselation(atom* candidate, BoundaryLineSet* currentBaseLine, Vector OptCandidateCenter, Vector OtherOptCandidateCenter);
+  ~CandidateForTesselation();
+  atom *point;
+  BoundaryLineSet *BaseLine;
+  Vector OptCenter;
+  Vector OtherOptCenter;
 };
 
@@ -93,5 +99,5 @@
     ~Tesselation();
 
-    void TesselateOnBoundary(ofstream *out, config *configuration, molecule *mol);
+    void TesselateOnBoundary(ofstream *out, molecule *mol);
     void GuessStartingTriangle(ofstream *out);
     void AddPoint(atom * Walker);
@@ -104,4 +110,8 @@
     int CheckPresenceOfTriangle(ofstream *out, atom *Candidates[3]);
     void Find_next_suitable_point_via_Angle_of_Sphere(atom* a, atom* b, atom* c, atom* Candidate, atom* Parent, int RecursionLevel, Vector *Chord, Vector *direction1, Vector *OldNormal, Vector ReferencePoint, atom*& Opt_Candidate, double *Storage, const double RADIUS, molecule* mol);
+    class BoundaryTriangleSet * FindClosestTriangleToPoint(ofstream *out, Vector *x);
+    bool IsInside(Vector *pointer);
+    bool InsertStraddlingPoints(ofstream *out, molecule *mol);
+    bool CorrectConcaveBaselines(ofstream *out);
     list<atom*> *getClosestConnectedAtoms(atom* Atom, atom* AtomToCheck);
     list<BoundaryTriangleSet*> *FindTriangles(atom* TrianglePoints[3]);
@@ -126,7 +136,9 @@
 
 
-double VolumeOfConvexEnvelope(ofstream *out, const char *filename, config *configuration, Boundaries *BoundaryPoints, molecule *mol);
+double VolumeOfConvexEnvelope(ofstream *out, class Tesselation *TesselStruct, class config *configuration);
 double * GetDiametersOfCluster(ofstream *out, Boundaries *BoundaryPtr, molecule *mol, bool IsAngstroem);
 void PrepareClustersinWater(ofstream *out, config *configuration, molecule *mol, double ClusterVolume, double celldensity);
+molecule * FillBoxWithMolecule(ofstream *out, MoleculeListClass *List, molecule *filler, config &configuration, double distance[NDIM], double RandAtomDisplacement, double RandMolDisplacement, bool DoRandomRotation);
+void Find_convex_border(ofstream *out, molecule* mol, class Tesselation *&TesselStruct, class LinkedCell *LCList, const char *filename);
 void Find_non_convex_border(ofstream *out, molecule* mol, class Tesselation *T, class LinkedCell *LC, const char *tempbasename, const double RADIUS);
 void Find_next_suitable_point(class BoundaryTriangleSet *BaseTriangle, class BoundaryLineSet *BaseLine, atom*& OptCandidate, Vector *OptCandidateCenter, double *ShortestAngle, const double RADIUS, LinkedCell *LC);
Index: src/builder.cpp
===================================================================
--- src/builder.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/builder.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -15,33 +15,33 @@
  * \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.
+ *  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.
+ *  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
+ *  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
+ *  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
+ *  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.
+ *  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.
+ *  For the special configuration file format, see the documentation of pcp.
  *
  */
@@ -54,5 +54,4 @@
 #include "helpers.hpp"
 #include "molecules.hpp"
-
 /********************************************* Subsubmenu routine ************************************/
 
@@ -63,36 +62,36 @@
 static 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) {
+  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) {
     default:
       cout << Verbose(0) << "Not a valid choice." << endl;
       break;
-			case 'a': // absolute coordinates of atom
+      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->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;
@@ -106,9 +105,9 @@
           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->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;
@@ -122,6 +121,6 @@
           }
         } while (!(valid = mol->CheckBounds((const Vector *)&first->x)));
-        first->type = periode->AskElement();	// give type
-        mol->AddAtom(first);	// add to molecule
+        first->type = periode->AskElement();  // give type
+        mol->AddAtom(first);  // add to molecule
         break;
 
@@ -224,9 +223,9 @@
           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->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]);
@@ -248,12 +247,12 @@
 
           first->x.Output((ofstream *)&cout);
-          first->type = periode->AskElement();	// give type
-          mol->AddAtom(first);	// add to molecule
+          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;
-	};
+        break;
+  };
 };
 
@@ -263,54 +262,54 @@
 static void CenterAtoms(molecule *mol)
 {
-	Vector x, y, helper;
-	char choice;	// menu choice char
-
-	cout << Verbose(0) << "===========CENTER ATOMS=========================" << endl;
-	cout << Verbose(0) << " a - on origin" << endl;
-	cout << Verbose(0) << " b - on center of gravity" << endl;
-	cout << Verbose(0) << " c - within box with additional boundary" << endl;
-	cout << Verbose(0) << " d - within given simulation box" << endl;
-	cout << Verbose(0) << "all else - go back" << endl;
-	cout << Verbose(0) << "===============================================" << endl;
-	cout << Verbose(0) << "INPUT: ";
-	cin >> choice;
-
-	switch (choice) {
-		default:
-			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<NDIM;i++) {
-				cout << Verbose(0) << "Enter axis " << i << " boundary: ";
-				cin >> y.x[i];
-			}
-			mol->CenterEdge((ofstream *)&cout, &x);	// make every coordinate positive
-			mol->Translate(&y); // translate by boundary
-			helper.CopyVector(&y);
-			helper.Scale(2.);
-			helper.AddVector(&x);
-			mol->SetBoxDimension(&helper);	// update Box of atoms by boundary
-			break;
-		case 'd':
-			cout << Verbose(1) << "Centering atoms in config file within given simulation box." << endl;
-			for (int i=0;i<NDIM;i++) {
-				cout << Verbose(0) << "Enter axis " << i << " boundary: ";
-				cin >> x.x[i];
-			}
-			// center
-			mol->CenterInBox((ofstream *)&cout, &x);
-			// update Box of atoms by boundary
-			mol->SetBoxDimension(&x);
-			break;
-	}
+  Vector x, y, helper;
+  char choice;  // menu choice char
+
+  cout << Verbose(0) << "===========CENTER ATOMS=========================" << endl;
+  cout << Verbose(0) << " a - on origin" << endl;
+  cout << Verbose(0) << " b - on center of gravity" << endl;
+  cout << Verbose(0) << " c - within box with additional boundary" << endl;
+  cout << Verbose(0) << " d - within given simulation box" << endl;
+  cout << Verbose(0) << "all else - go back" << endl;
+  cout << Verbose(0) << "===============================================" << endl;
+  cout << Verbose(0) << "INPUT: ";
+  cin >> choice;
+
+  switch (choice) {
+    default:
+      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);
+      break;
+    case 'b':
+      cout << Verbose(0) << "Centering atoms in config file on center of gravity." << endl;
+      mol->CenterPeriodic((ofstream *)&cout);
+      break;
+    case 'c':
+      cout << Verbose(0) << "Centering atoms in config file within given additional boundary." << endl;
+      for (int i=0;i<NDIM;i++) {
+        cout << Verbose(0) << "Enter axis " << i << " boundary: ";
+        cin >> y.x[i];
+      }
+      mol->CenterEdge((ofstream *)&cout, &x);  // make every coordinate positive
+      mol->Center.AddVector(&y); // translate by boundary
+      helper.CopyVector(&y);
+      helper.Scale(2.);
+      helper.AddVector(&x);
+      mol->SetBoxDimension(&helper);  // update Box of atoms by boundary
+      break;
+    case 'd':
+      cout << Verbose(1) << "Centering atoms in config file within given simulation box." << endl;
+      for (int i=0;i<NDIM;i++) {
+        cout << Verbose(0) << "Enter axis " << i << " boundary: ";
+        cin >> x.x[i];
+      }
+      // update Box of atoms by boundary
+      mol->SetBoxDimension(&x);
+      // center
+      mol->CenterInBox((ofstream *)&cout);
+      break;
+  }
 };
 
@@ -321,65 +320,65 @@
 static 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=NDIM;i--;) {
-				x.x[i] = gsl_vector_get(param.x,i);
-				n.x[i] = gsl_vector_get(param.x,i+NDIM);
-			}
-			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);
+  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=NDIM;i--;) {
+        x.x[i] = gsl_vector_get(param.x,i);
+        n.x[i] = gsl_vector_get(param.x,i+NDIM);
+      }
+      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);
 };
 
@@ -389,44 +388,44 @@
 static 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);
+  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);
 };
 
@@ -436,54 +435,60 @@
 static 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.DistanceSquared((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';
+  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;
+      second = first->next;
+      while(second != mol->end) {
+        first = second;
+        second = first->next;
+        if (first->x.DistanceSquared((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) << "Lower boundary: ";
+      cin >> tmp1;
+      cout << Verbose(0) << "Upper boundary: ";
+      cin >> tmp2;
+      first = mol->start;
+      second = first->next;
+      while(second != mol->end) {
+        first = second;
+        second = first->next;
+        if ((first->x.x[axis] < tmp1) || (first->x.x[axis] > tmp2)) {// out of boundary ...
+          //cout << "Atom " << *first << " with " << first->x.x[axis] << " on axis " << axis << " is out of bounds [" << tmp1 << "," << tmp2 << "]." << endl;
+          mol->RemoveAtom(first);
+        }
+      }
+      break;
+  };
+  //mol->Output((ofstream *)&cout);
+  choice = 'r';
 };
 
@@ -494,107 +499,114 @@
 static void MeasureAtoms(periodentafel *periode, molecule *mol, config *configuration)
 {
-	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) << " d - calculate principal axis of the system" << endl;
-	cout << Verbose(0) << " e - calculate volume of the convex envelope" << endl;
-	cout << Verbose(0) << " f - calculate temperature from current velocity" << endl;
-	cout << Verbose(0) << " g - output all temperatures per step from velocities" << 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=MAX_ELEMENTS;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=MAX_ELEMENTS;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=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;
-		case 'd':
-			cout << Verbose(0) << "Evaluating prinicipal axis." << endl;
-			cout << Verbose(0) << "Shall we rotate? [0/1]: ";
-			cin >> Z;
-			if ((Z >=0) && (Z <=1))
-				mol->PrincipalAxisSystem((ofstream *)&cout, (bool)Z);
-			else
-				mol->PrincipalAxisSystem((ofstream *)&cout, false);
-			break;
-		case 'e':
-			cout << Verbose(0) << "Evaluating volume of the convex envelope.";
-			VolumeOfConvexEnvelope((ofstream *)&cout, NULL, configuration, NULL, mol);
-			break;
-		case 'f':
-			mol->OutputTemperatureFromTrajectories((ofstream *)&cout, mol->MDSteps-1, mol->MDSteps, (ofstream *)&cout);
-			break;
-		case 'g':
-			{
-				char filename[255];
-				cout << "Please enter filename: " << endl;
-				cin >> filename;
-				cout << Verbose(1) << "Storing temperatures in " << filename << "." << endl;
-				ofstream *output = new ofstream(filename, ios::trunc);
-				if (!mol->OutputTemperatureFromTrajectories((ofstream *)&cout, 0, mol->MDSteps, output))
-					cout << Verbose(2) << "File could not be written." << endl;
-				else
-					cout << Verbose(2) << "File stored." << endl;
-				output->close();
-				delete(output);
-			}
-			break;
-	}
+  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) << " d - calculate principal axis of the system" << endl;
+  cout << Verbose(0) << " e - calculate volume of the convex envelope" << endl;
+  cout << Verbose(0) << " f - calculate temperature from current velocity" << endl;
+  cout << Verbose(0) << " g - output all temperatures per step from velocities" << 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=MAX_ELEMENTS;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=MAX_ELEMENTS;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=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;
+    case 'd':
+      cout << Verbose(0) << "Evaluating prinicipal axis." << endl;
+      cout << Verbose(0) << "Shall we rotate? [0/1]: ";
+      cin >> Z;
+      if ((Z >=0) && (Z <=1))
+        mol->PrincipalAxisSystem((ofstream *)&cout, (bool)Z);
+      else
+        mol->PrincipalAxisSystem((ofstream *)&cout, false);
+      break;
+    case 'e':
+      {
+        cout << Verbose(0) << "Evaluating volume of the convex envelope.";
+        LinkedCell LCList(mol, 10.);
+        class Tesselation *TesselStruct = NULL;
+        Find_convex_border((ofstream *)&cout, mol, TesselStruct, &LCList, NULL);
+        double clustervolume = VolumeOfConvexEnvelope((ofstream *)&cout, TesselStruct, configuration);
+        cout << Verbose(0) << "The tesselated surface area is " << clustervolume << "." << endl;
+        delete(TesselStruct);
+      }
+      break;
+    case 'f':
+      mol->OutputTemperatureFromTrajectories((ofstream *)&cout, mol->MDSteps-1, mol->MDSteps, (ofstream *)&cout);
+      break;
+    case 'g':
+      {
+        char filename[255];
+        cout << "Please enter filename: " << endl;
+        cin >> filename;
+        cout << Verbose(1) << "Storing temperatures in " << filename << "." << endl;
+        ofstream *output = new ofstream(filename, ios::trunc);
+        if (!mol->OutputTemperatureFromTrajectories((ofstream *)&cout, 0, mol->MDSteps, output))
+          cout << Verbose(2) << "File could not be written." << endl;
+        else
+          cout << Verbose(2) << "File stored." << endl;
+        output->close();
+        delete(output);
+      }
+      break;
+  }
 };
 
@@ -605,17 +617,17 @@
 static void FragmentAtoms(molecule *mol, config *configuration)
 {
-	int Order1;
-	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;
-	if (mol->first->next != mol->last) {	// there are bonds
-		start = clock();
-		mol->FragmentMolecule((ofstream *)&cout, Order1, configuration);
-		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;
+  int Order1;
+  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;
+  if (mol->first->next != mol->last) {  // there are bonds
+    start = clock();
+    mol->FragmentMolecule((ofstream *)&cout, Order1, configuration);
+    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;
 };
 
@@ -644,5 +656,5 @@
   cout << Verbose(0) << "all else - go back" << endl;
   cout << Verbose(0) << "===============================================" << endl;
-  if (molecules->NumberOfActiveMolecules() > 0)
+  if (molecules->NumberOfActiveMolecules() > 1)
     cout << Verbose(0) << "WARNING: There is more than one molecule active! Atoms will be added to each." << endl;
   cout << Verbose(0) << "INPUT: ";
@@ -655,5 +667,6 @@
 
     case 'a': // add atom
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -663,5 +676,6 @@
 
     case 'b': // scale a bond
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -685,5 +699,6 @@
 
     case 'c': // unit scaling of the metric
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -701,5 +716,6 @@
 
     case 'l': // measure distances or angles
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -709,5 +725,6 @@
 
     case 'r': // remove atom
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -717,5 +734,6 @@
 
     case 'u': // change an atom's element
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         int Z;
         mol = *ListRunner;
@@ -761,5 +779,5 @@
   cout << Verbose(0) << "all else - go back" << endl;
   cout << Verbose(0) << "===============================================" << endl;
-  if (molecules->NumberOfActiveMolecules() > 0)
+  if (molecules->NumberOfActiveMolecules() > 1)
     cout << Verbose(0) << "WARNING: There is more than one molecule active! Atoms will be added to each." << endl;
   cout << Verbose(0) << "INPUT: ";
@@ -772,5 +790,6 @@
 
     case 'd': // duplicate the periodic cell along a given axis, given times
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) 
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -830,5 +849,6 @@
 
     case 'g': // center the atoms
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -838,5 +858,6 @@
 
     case 'i': // align all atoms
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -846,5 +867,6 @@
 
     case 'm': // mirror atoms along a given axis
-      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
@@ -854,24 +876,27 @@
 
     case 'o': // create the connection matrix
-      {
-        double bonddistance;
-        clock_t start,end;
-        cout << Verbose(0) << "What's the maximum bond distance: ";
-        cin >> bonddistance;
-        start = clock();
-        mol->CreateAdjacencyList((ofstream *)&cout, bonddistance, configuration->GetIsAngstroem());
-        mol->CreateListOfBondsPerAtom((ofstream *)&cout);
-        end = clock();
-        cout << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
-      }
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
+          mol = *ListRunner;
+          double bonddistance;
+          clock_t start,end;
+          cout << Verbose(0) << "What's the maximum bond distance: ";
+          cin >> bonddistance;
+          start = clock();
+          mol->CreateAdjacencyList((ofstream *)&cout, bonddistance, configuration->GetIsAngstroem());
+          mol->CreateListOfBondsPerAtom((ofstream *)&cout);
+          end = clock();
+          cout << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+        }
       break;
 
     case 't': // translate all atoms
-     for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+      for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if ((*ListRunner)->ActiveFlag) {
         mol = *ListRunner;
         cout << Verbose(0) << "Current molecule is: " << mol->IndexNr << "\t" << mol->name << endl;
         cout << Verbose(0) << "Enter translation vector." << endl;
         x.AskPosition(mol->cell_size,0);
-        mol->Translate((const Vector *)&x);
+        mol->Center.AddVector((const Vector *)&x);
      }
      break;
@@ -895,15 +920,14 @@
 {
   char choice;  // menu choice char
-  Vector Center;
+  Vector center;
   int nr, count;
   molecule *mol = NULL;
-  char filename[MAXSTRINGSIZE];
-
-  cout << Verbose(0) << "==========Edit MOLECULES=====================" << endl;
+
+  cout << Verbose(0) << "==========EDIT MOLECULES=====================" << endl;
   cout << Verbose(0) << "c - create new molecule" << endl;
   cout << Verbose(0) << "l - load molecule from xyz file" << endl;
   cout << Verbose(0) << "n - change molecule's name" << endl;
   cout << Verbose(0) << "N - give molecules filename" << endl;
-  cout << Verbose(0) << "p - parse xyz file into molecule" << endl;
+  cout << Verbose(0) << "p - parse atoms in xyz file into molecule" << endl;
   cout << Verbose(0) << "r - remove a molecule" << endl;
   cout << Verbose(0) << "all else - go back" << endl;
@@ -921,58 +945,70 @@
       break;
 
-    case 'l': // laod from XYZ file
-      cout << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
-      mol = new molecule(periode);
-      do {
-        cout << Verbose(0) << "Enter file name: ";
+    case 'l': // load from XYZ file
+      {
+        char filename[MAXSTRINGSIZE];
+        cout << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
+        mol = new molecule(periode);
+        do {
+          cout << Verbose(0) << "Enter file name: ";
+          cin >> filename;
+        } while (!mol->AddXYZFile(filename));
+        mol->SetNameFromFilename(filename);
+        // center at set box dimensions
+        mol->CenterEdge((ofstream *)&cout, &center);
+        mol->cell_size[0] = center.x[0];
+        mol->cell_size[1] = 0;
+        mol->cell_size[2] = center.x[1];
+        mol->cell_size[3] = 0;
+        mol->cell_size[4] = 0;
+        mol->cell_size[5] = center.x[2];
+        molecules->insert(mol);
+      }
+      break;
+
+    case 'n':
+      {
+        char filename[MAXSTRINGSIZE];
+        do {
+          cout << Verbose(0) << "Enter index of molecule: ";
+          cin >> nr;
+          mol = molecules->ReturnIndex(nr);
+        } while (mol == NULL);
+        cout << Verbose(0) << "Enter name: ";
         cin >> filename;
-      } while (!mol->AddXYZFile(filename));
-      mol->SetNameFromFilename(filename);
-      // center at set box dimensions
-      mol->CenterEdge((ofstream *)&cout, &Center);
-      mol->cell_size[0] = Center.x[0];
-      mol->cell_size[1] = 0;
-      mol->cell_size[2] = Center.x[1];
-      mol->cell_size[3] = 0;
-      mol->cell_size[4] = 0;
-      mol->cell_size[5] = Center.x[2];
-      molecules->insert(mol);
-      break;
-
-    case 'n':
-      do {
-        cout << Verbose(0) << "Enter index of molecule: ";
-        cin >> nr;
-        mol = molecules->ReturnIndex(nr);
-      } while (mol != NULL);
-      cout << Verbose(0) << "Enter name: ";
-      cin >> filename;
-      strcpy(mol->name, filename);
+        strcpy(mol->name, filename);
+      }
       break;
 
     case 'N':
-      do {
-        cout << Verbose(0) << "Enter index of molecule: ";
-        cin >> nr;
-        mol = molecules->ReturnIndex(nr);
-      } while (mol != NULL);
-      cout << Verbose(0) << "Enter name: ";
-      cin >> filename;
-      mol->SetNameFromFilename(filename);
+      {
+        char filename[MAXSTRINGSIZE];
+        do {
+          cout << Verbose(0) << "Enter index of molecule: ";
+          cin >> nr;
+          mol = molecules->ReturnIndex(nr);
+        } while (mol == NULL);
+        cout << Verbose(0) << "Enter name: ";
+        cin >> filename;
+        mol->SetNameFromFilename(filename);
+      }
       break;
 
     case 'p': // parse XYZ file
-      mol = NULL;
-      do {
-        cout << Verbose(0) << "Enter index of molecule: ";
-        cin >> nr;
-        mol = molecules->ReturnIndex(nr);
-      } while (mol == NULL);
-      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));
-      mol->SetNameFromFilename(filename);
+      {
+        char filename[MAXSTRINGSIZE];
+        mol = NULL;
+        do {
+          cout << Verbose(0) << "Enter index of molecule: ";
+          cin >> nr;
+          mol = molecules->ReturnIndex(nr);
+        } while (mol == NULL);
+        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));
+        mol->SetNameFromFilename(filename);
+      }
       break;
 
@@ -981,11 +1017,10 @@
       cin >> nr;
       count = 1;
-      MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin();
-      for(; ((ListRunner != molecules->ListOfMolecules.end()) && (count < nr)); ListRunner++);
-      mol = *ListRunner;
-      if (count == nr) {
-        molecules->ListOfMolecules.erase(ListRunner);
-        delete(mol);
-      }
+      for( MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+        if (nr == (*ListRunner)->IndexNr) {
+          mol = *ListRunner;
+          molecules->ListOfMolecules.erase(ListRunner);
+          delete(mol);
+        }
       break;
   }
@@ -1002,4 +1037,5 @@
 
   cout << Verbose(0) << "===========MERGE MOLECULES=====================" << endl;
+  cout << Verbose(0) << "a - simple add of one molecule to another" << endl;
   cout << Verbose(0) << "e - embedding merge of two molecules" << endl;
   cout << Verbose(0) << "m - multi-merge of all molecules" << endl;
@@ -1016,14 +1052,73 @@
       break;
 
+    case 'a':
+      {
+        int src, dest;
+        molecule *srcmol = NULL, *destmol = NULL;
+        {
+          do {
+            cout << Verbose(0) << "Enter index of destination molecule: ";
+            cin >> dest;
+            destmol = molecules->ReturnIndex(dest);
+          } while ((destmol == NULL) && (dest != -1));
+          do {
+            cout << Verbose(0) << "Enter index of source molecule to add from: ";
+            cin >> src;
+            srcmol = molecules->ReturnIndex(src);
+          } while ((srcmol == NULL) && (src != -1));
+          if ((src != -1) && (dest != -1))
+            molecules->SimpleAdd(srcmol, destmol);
+        }
+      }
+      break;
+
     case 'e':
+      cout << Verbose(0) << "Not implemented yet." << endl;
       break;
 
     case 'm':
+      {
+        int nr;
+        molecule *mol = NULL;
+        do {
+          cout << Verbose(0) << "Enter index of molecule to merge into: ";
+          cin >> nr;
+          mol = molecules->ReturnIndex(nr);
+        } while ((mol == NULL) && (nr != -1));
+        if (nr != -1) {
+          int N = molecules->ListOfMolecules.size()-1;
+          int *src = new int(N);
+          for(MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+            if ((*ListRunner)->IndexNr != nr)
+              src[N++] = (*ListRunner)->IndexNr;        
+          molecules->SimpleMultiMerge(mol, src, N);
+          delete[](src);
+        }
+      }
       break;
 
     case 's':
+      cout << Verbose(0) << "Not implemented yet." << endl;
       break;
 
     case 't':
+      {
+        int src, dest;
+        molecule *srcmol = NULL, *destmol = NULL;
+        {
+          do {
+            cout << Verbose(0) << "Enter index of destination molecule: ";
+            cin >> dest;
+            destmol = molecules->ReturnIndex(dest);
+          } while ((destmol == NULL) && (dest != -1));
+          do {
+            cout << Verbose(0) << "Enter index of source molecule to merge into: ";
+            cin >> src;
+            srcmol = molecules->ReturnIndex(src);
+          } while ((srcmol == NULL) && (src != -1));
+          if ((src != -1) && (dest != -1))
+            molecules->SimpleMerge(srcmol, destmol);
+        }
+      }
       break;
   }
@@ -1038,6 +1133,6 @@
 static void testroutine(MoleculeListClass *molecules)
 {
-	// the current test routine checks the functionality of the KeySet&Graph concept:
-	// We want to have a multiindex (the KeySet) describing a unique subgraph
+  // the current test routine checks the functionality of the KeySet&Graph concept:
+  // We want to have a multiindex (the KeySet) describing a unique subgraph
   int i, comp, counter=0;
 
@@ -1052,63 +1147,63 @@
   atom *Walker = mol->start;
 
-	// 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++;
-	}
-	delete(mol);
+  // 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++;
+  }
+  delete(mol);
 };
 
@@ -1121,79 +1216,88 @@
 static void SaveConfig(char *ConfigFileName, config *configuration, periodentafel *periode, MoleculeListClass *molecules)
 {
-	char filename[MAXSTRINGSIZE];
-	ofstream output;
-	molecule *mol = new molecule(periode);
-
-	// merge all molecules in MoleculeListClass into this molecule
-	int N = molecules->ListOfMolecules.size();
-	int *src = new int(N);
-	N=0;
-	for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
-	  src[N++] = (*ListRunner)->IndexNr;
-	molecules->SimpleMultiAdd(mol, src, N);
-
-	cout << Verbose(0) << "Storing configuration ... " << endl;
-	// get correct valence orbitals
-	mol->CalculateOrbitals(*configuration);
-	configuration->InitMaxMinStopStep = configuration->MaxMinStopStep = configuration->MaxPsiDouble;
-	strcpy(filename, ConfigFileName);
-	if (ConfigFileName != NULL) { // test the file name
-		output.open(ConfigFileName, ios::trunc);
-	} else if (strlen(configuration->configname) != 0) {
-		strcpy(filename, configuration->configname);
-		output.open(configuration->configname, ios::trunc);
-		} else {
-			strcpy(filename, DEFAULTCONFIG);
-			output.open(DEFAULTCONFIG, ios::trunc);
-		}
-	output.close();
-	output.clear();
-	cout << Verbose(0) << "Saving of config file ";
-	if (configuration->Save(filename, periode, mol))
-		cout << "successful." << endl;
-	else
-		cout << "failed." << endl;
-
-	// and save to xyz file
-	if (ConfigFileName != NULL) {
-		strcpy(filename, ConfigFileName);
-		strcat(filename, ".xyz");
-		output.open(filename, ios::trunc);
-	}
-	if (output == NULL) {
-		strcpy(filename,"main_pcp_linux");
-		strcat(filename, ".xyz");
-		output.open(filename, ios::trunc);
-	}
-	cout << Verbose(0) << "Saving of XYZ file ";
-	if (mol->MDSteps <= 1) {
-		if (mol->OutputXYZ(&output))
-			cout << "successful." << endl;
-		else
-			cout << "failed." << endl;
-	} else {
-		if (mol->OutputTrajectoriesXYZ(&output))
-			cout << "successful." << endl;
-		else
-			cout << "failed." << endl;
-	}
-	output.close();
-	output.clear();
-
-	// and save as MPQC configuration
-	if (ConfigFileName != NULL)
-		strcpy(filename, ConfigFileName);
-	if (output == NULL)
-		strcpy(filename,"main_pcp_linux");
-	cout << Verbose(0) << "Saving as mpqc input ";
-	if (configuration->SaveMPQC(filename, mol))
-		cout << "done." << endl;
-	else
-		cout << "failed." << endl;
-
-	if (!strcmp(configuration->configpath, configuration->GetDefaultPath())) {
-		cerr << "WARNING: config is found under different path then stated in config file::defaultpath!" << endl;
-	}
-	delete(mol);
+  char filename[MAXSTRINGSIZE];
+  ofstream output;
+  molecule *mol = new molecule(periode);
+
+  // translate each to its center and merge all molecules in MoleculeListClass into this molecule
+  int N = molecules->ListOfMolecules.size();
+  int *src = new int(N);
+  N=0;
+  for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+    src[N++] = (*ListRunner)->IndexNr;
+    (*ListRunner)->Translate(&(*ListRunner)->Center);
+  }
+  molecules->SimpleMultiAdd(mol, src, N);
+  delete[](src);
+  // ... and translate back
+  for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
+    (*ListRunner)->Center.Scale(-1.);
+    (*ListRunner)->Translate(&(*ListRunner)->Center);
+    (*ListRunner)->Center.Scale(-1.);
+  }
+
+  cout << Verbose(0) << "Storing configuration ... " << endl;
+  // get correct valence orbitals
+  mol->CalculateOrbitals(*configuration);
+  configuration->InitMaxMinStopStep = configuration->MaxMinStopStep = configuration->MaxPsiDouble;
+  if (ConfigFileName != NULL) { // test the file name
+    strcpy(filename, ConfigFileName);
+    output.open(filename, ios::trunc);
+  } else if (strlen(configuration->configname) != 0) {
+    strcpy(filename, configuration->configname);
+    output.open(configuration->configname, ios::trunc);
+    } else {
+      strcpy(filename, DEFAULTCONFIG);
+      output.open(DEFAULTCONFIG, ios::trunc);
+    }
+  output.close();
+  output.clear();
+  cout << Verbose(0) << "Saving of config file ";
+  if (configuration->Save(filename, periode, mol))
+    cout << "successful." << endl;
+  else
+    cout << "failed." << endl;
+
+  // and save to xyz file
+  if (ConfigFileName != NULL) {
+    strcpy(filename, ConfigFileName);
+    strcat(filename, ".xyz");
+    output.open(filename, ios::trunc);
+  }
+  if (output == NULL) {
+    strcpy(filename,"main_pcp_linux");
+    strcat(filename, ".xyz");
+    output.open(filename, ios::trunc);
+  }
+  cout << Verbose(0) << "Saving of XYZ file ";
+  if (mol->MDSteps <= 1) {
+    if (mol->OutputXYZ(&output))
+      cout << "successful." << endl;
+    else
+      cout << "failed." << endl;
+  } else {
+    if (mol->OutputTrajectoriesXYZ(&output))
+      cout << "successful." << endl;
+    else
+      cout << "failed." << endl;
+  }
+  output.close();
+  output.clear();
+
+  // and save as MPQC configuration
+  if (ConfigFileName != NULL)
+    strcpy(filename, ConfigFileName);
+  if (output == NULL)
+    strcpy(filename,"main_pcp_linux");
+  cout << Verbose(0) << "Saving as mpqc input ";
+  if (configuration->SaveMPQC(filename, mol))
+    cout << "done." << endl;
+  else
+    cout << "failed." << endl;
+
+  if (!strcmp(configuration->configpath, configuration->GetDefaultPath())) {
+    cerr << "WARNING: config is found under different path then stated in config file::defaultpath!" << endl;
+  }
+  delete(mol);
 };
 
@@ -1210,567 +1314,621 @@
 static int ParseCommandLineOptions(int argc, char **argv, MoleculeListClass *&molecules, periodentafel *&periode, config& configuration, char *&ConfigFileName)
 {
-	Vector x,y,z,n;	// coordinates for absolute point in cell volume
-	double *factor; // unit factor if desired
-	ifstream test;
-	ofstream output;
-	string line;
-	atom *first;
-	bool SaveFlag = false;
-	int ExitFlag = 0;
-	int j;
-	double volume = 0.;
-	enum ConfigStatus config_present = absent;
-	clock_t start,end;
-	int argptr;
+  Vector x,y,z,n;  // coordinates for absolute point in cell volume
+  double *factor; // unit factor if desired
+  ifstream test;
+  ofstream output;
+  string line;
+  atom *first;
+  bool SaveFlag = false;
+  int ExitFlag = 0;
+  int j;
+  double volume = 0.;
+  enum ConfigStatus config_present = absent;
+  clock_t start,end;
+  int argptr;
+  molecule *mol = NULL;
   strncpy(configuration.databasepath, LocalPath, MAXSTRINGSIZE-1);
 
-	// simply create a new molecule, wherein the config file is loaded and the manipulation takes place
-	molecule *mol = new molecule(periode);
-	molecules->insert(mol);
-
-	if (argc > 1) { // config file specified as option
-		// 1. : Parse options that just set variables or print help
-		argptr = 1;
-		do {
-			if (argv[argptr][0] == '-') {
-				cout << Verbose(0) << "Recognized command line argument: " << argv[argptr][1] << ".\n";
-				argptr++;
-				switch(argv[argptr-1][1]) {
-					case 'h':
-					case 'H':
-					case '?':
-						cout << "MoleCuilder suite" << endl << "==================" << endl << endl;
-						cout << "Usage: " << argv[0] << "[config file] [-{acefpsthH?vfrp}] [further arguments]" << endl;
-						cout << "or simply " << argv[0] << " without arguments for interactive session." << endl;
-						cout << "\t-a Z x1 x2 x3\tAdd new atom of element Z at coordinates (x1,x2,x3)." << endl;
-						cout << "\t-A <source>\tCreate adjacency list from bonds parsed from 'dbond'-style file." <<endl;
-						cout << "\t-b x1 x2 x3\tCenter atoms in domain with given edge lengths of (x1,x2,x3)." << endl;
-						cout << "\t-B <basis>\tSetting basis to store to MPQC config files." << endl;
-						cout << "\t-c x1 x2 x3\tCenter atoms in domain with a minimum distance to boundary of (x1,x2,x3)." << endl;
-						cout << "\t-D <bond distance>\tDepth-First-Search Analysis of the molecule, giving cycles and tree/back edges." << endl;
-						cout << "\t-O\tCenter atoms in origin." << endl;
-						cout << "\t-d x1 x2 x3\tDuplicate cell along each axis by given factor." << endl;
-						cout << "\t-e <file>\tSets the databases path to be parsed (default: ./)." << endl;
-						cout << "\t-E <id> <Z>\tChange atom <id>'s element to <Z>, <id> begins at 0." << endl;
-						cout << "\t-f/F <dist> <order>\tFragments the molecule in BOSSANOVA manner (with/out rings compressed) and stores config files in same dir as config (return code 0 - fragmented, 2 - no fragmentation necessary)." << endl;
-						cout << "\t-h/-H/-?\tGive this help screen." << endl;
-						cout << "\t-m <0/1>\tCalculate (0)/ Align in(1) PAS with greatest EV along z axis." << endl;
-						cout << "\t-n\tFast parsing (i.e. no trajectories are looked for)." << endl;
-						cout << "\t-N\tGet non-convex-envelope." << endl;
-						cout << "\t-o <out>\tGet volume of the convex envelope (and store to tecplot file)." << endl;
-						cout << "\t-p <file>\tParse given xyz file and create raw config file from it." << endl;
-						cout << "\t-P <file>\tParse given forces file and append as an MD step to config file via Verlet." << endl;
-						cout << "\t-r\t\tConvert file from an old pcp syntax." << endl;
-						cout << "\t-t x1 x2 x3\tTranslate all atoms by this vector (x1,x2,x3)." << endl;
-						cout << "\t-T <file> Store temperatures from the config file in <file>." << endl;
-						cout << "\t-s x1 x2 x3\tScale all atom coordinates by this vector (x1,x2,x3)." << endl;
-						cout << "\t-u rho\tsuspend in water solution and output necessary cell lengths, average density rho and repetition." << endl;
-						cout << "\t-v/-V\t\tGives version information." << endl;
-						cout << "Note: config files must not begin with '-' !" << endl;
-						delete(mol);
-						delete(periode);
-						return (1);
-						break;
-					case 'v':
-					case 'V':
-						cout << argv[0] << " " << VERSIONSTRING << endl;
-						cout << "Build your own molecule position set." << endl;
-						delete(mol);
-						delete(periode);
-						return (1);
-						break;
-					case 'e':
-						if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-							cerr << "Not enough or invalid arguments for specifying element db: -e <db file>" << endl;
-						} else {
-							cout << "Using " << argv[argptr] << " as elements database." << endl;
-							strncpy (configuration.databasepath, argv[argptr], MAXSTRINGSIZE-1);
-							argptr+=1;
-						}
-						break;
-					case 'n':
-						cout << "I won't parse trajectories." << endl;
-						configuration.FastParsing = true;
-						break;
-					default:	 // no match? Step on
-						argptr++;
-						break;
-				}
-			} else
-				argptr++;
-		} while (argptr < argc);
-
-		// 2. Parse the element database
-		if (periode->LoadPeriodentafel(configuration.databasepath)) {
-			cout << Verbose(0) << "Element list loaded successfully." << endl;
-			//periode->Output((ofstream *)&cout);
-		} else {
-			cout << Verbose(0) << "Element list loading failed." << endl;
-			return 1;
-		}
-		// 3. Find config file name and parse if possible
-		if (argv[1][0] != '-') {
-			cout << Verbose(0) << "Config file given." << endl;
-			test.open(argv[1], ios::in);
-			if (test == NULL) {
-				//return (1);
-				output.open(argv[1], ios::out);
-				if (output == NULL) {
-					cout << Verbose(1) << "Specified config file " << argv[1] << " not found." << endl;
-					config_present = absent;
-				} else {
-					cout << "Empty configuration file." << endl;
-					ConfigFileName = argv[1];
-					config_present = empty;
-					output.close();
-				}
-			} else {
-				test.close();
-				ConfigFileName = argv[1];
-				cout << Verbose(1) << "Specified config file found, parsing ... ";
-				switch (configuration.TestSyntax(ConfigFileName, periode, mol)) {
-					case 1:
-						cout << "new syntax." << endl;
-						configuration.Load(ConfigFileName, periode, mol);
-						config_present = present;
-						break;
-					case 0:
-						cout << "old syntax." << endl;
-						configuration.LoadOld(ConfigFileName, periode, mol);
-						config_present = present;
-						break;
-					default:
-						cout << "Unknown syntax or empty, yet present file." << endl;
-						config_present = empty;
-			 }
-			}
-		} else
-			config_present = absent;
-		// 4. parse again through options, now for those depending on elements db and config presence
-		argptr = 1;
-		do {
-			cout << "Current Command line argument: " << argv[argptr] << "." << endl;
-			if (argv[argptr][0] == '-') {
-				argptr++;
-				if ((config_present == present) || (config_present == empty)) {
-					switch(argv[argptr-1][1]) {
-						case 'p':
-							ExitFlag = 1;
-							if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-								ExitFlag = 255;
-								cerr << "Not enough arguments for parsing: -p <xyz file>" << endl;
-							} else {
-								SaveFlag = true;
-								cout << Verbose(1) << "Parsing xyz file for new atoms." << endl;
-								if (!mol->AddXYZFile(argv[argptr]))
-									cout << Verbose(2) << "File not found." << endl;
-								else {
-									cout << Verbose(2) << "File found and parsed." << endl;
-									config_present = present;
-								}
-							}
-							break;
-						case 'a':
-							ExitFlag = 1;
-							if ((argptr >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr+1]))) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments for adding atom: -a <element> <x> <y> <z>" << endl;
-							} else {
-								SaveFlag = true;
-								cout << Verbose(1) << "Adding new atom with element " << argv[argptr] << " at (" << argv[argptr+1] << "," << argv[argptr+2] << "," << argv[argptr+3] << "), ";
-								first = new atom;
-								first->type = periode->FindElement(atoi(argv[argptr]));
-								if (first->type != NULL)
-									cout << Verbose(2) << "found element " << first->type->name << endl;
-								for (int i=NDIM;i--;)
-									first->x.x[i] = atof(argv[argptr+1+i]);
-								if (first->type != NULL) {
-									mol->AddAtom(first);	// add to molecule
-									if ((config_present == empty) && (mol->AtomCount != 0))
-										config_present = present;
-								} else
-									cerr << Verbose(1) << "Could not find the specified element." << endl;
-								argptr+=4;
-							}
-							break;
-						default:	 // no match? Don't step on (this is done in next switch's default)
-							break;
-					}
-				}
-				if (config_present == present) {
-					switch(argv[argptr-1][1]) {
-						case 'B':
-							if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for setting MPQC basis: -B <basis name>" << endl;
-							} else {
-								configuration.basis = argv[argptr];
-								cout << Verbose(1) << "Setting MPQC basis to " << configuration.basis << "." << endl;
-								argptr+=1;
-							}
-							break;
-						case 'D':
-							ExitFlag = 1;
-							{
-								cout << Verbose(1) << "Depth-First-Search Analysis." << endl;
-								MoleculeLeafClass *Subgraphs = NULL;			// list of subgraphs from DFS analysis
-								int *MinimumRingSize = new int[mol->AtomCount];
-								atom ***ListOfLocalAtoms = NULL;
-								int FragmentCounter = 0;
-								class StackClass<bond *> *BackEdgeStack = NULL;
-								class StackClass<bond *> *LocalBackEdgeStack = NULL;
-								mol->CreateAdjacencyList((ofstream *)&cout, atof(argv[argptr]), configuration.GetIsAngstroem());
-								mol->CreateListOfBondsPerAtom((ofstream *)&cout);
-								Subgraphs = mol->DepthFirstSearchAnalysis((ofstream *)&cout, BackEdgeStack);
-								if (Subgraphs != NULL) {
-									Subgraphs->next->FillBondStructureFromReference((ofstream *)&cout, mol, (FragmentCounter = 0), ListOfLocalAtoms, false);	// we want to keep the created ListOfLocalAtoms
-									while (Subgraphs->next != NULL) {
-										Subgraphs = Subgraphs->next;
-										LocalBackEdgeStack = new StackClass<bond *> (Subgraphs->Leaf->BondCount);
-										Subgraphs->Leaf->PickLocalBackEdges((ofstream *)&cout, ListOfLocalAtoms[FragmentCounter++], BackEdgeStack, LocalBackEdgeStack);
-										Subgraphs->Leaf->CyclicStructureAnalysis((ofstream *)&cout, BackEdgeStack, MinimumRingSize);
-										delete(LocalBackEdgeStack);
-										delete(Subgraphs->previous);
-									}
-									delete(Subgraphs);
-									for (int i=0;i<FragmentCounter;i++)
-										Free((void **)&ListOfLocalAtoms[FragmentCounter], "ParseCommandLineOptions: **ListOfLocalAtoms[]");
-									Free((void **)&ListOfLocalAtoms, "ParseCommandLineOptions: ***ListOfLocalAtoms");
-								}
-								delete(BackEdgeStack);
-								delete[](MinimumRingSize);
-							}
-							//argptr+=1;
-							break;
-						case 'E':
-							ExitFlag = 1;
-							if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (argv[argptr+1][0] == '-')) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for changing element: -E <atom nr.> <element>" << endl;
-							} else {
-								SaveFlag = true;
-								cout << Verbose(1) << "Changing atom " << argv[argptr] << " to element " << argv[argptr+1] << "." << endl;
-								first = mol->FindAtom(atoi(argv[argptr]));
-								first->type = periode->FindElement(atoi(argv[argptr+1]));
-								argptr+=2;
-							}
-							break;
-						case 'A':
-							ExitFlag = 1;
-							if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-								ExitFlag =255;
-								cerr << "Missing source file for bonds in molecule: -A <bond sourcefile>" << endl;
-							} else {
-								cout << "Parsing bonds from " << argv[argptr] << "." << endl;
-								ifstream *input = new ifstream(argv[argptr]);
-								mol->CreateAdjacencyList2((ofstream *)&cout, input);
-								input->close();
-								argptr+=1;
-							}
-							break;
-						case 'N':
-							ExitFlag = 1;
-							if ((argptr+1 >= argc) || (argv[argptr+1][0] == '-')){
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for non-convex envelope: -o <radius> <tecplot output file>" << endl;
-							} else {
-								class Tesselation T;
-								string filename(argv[argptr+1]);
-								filename.append(".csv");
-								cout << Verbose(0) << "Evaluating non-convex envelope.";
-								cout << Verbose(1) << "Using rolling ball of radius " << atof(argv[argptr]) << " and storing tecplot data in " << argv[argptr+1] << "." << endl;
-								LinkedCell LCList(mol, atof(argv[argptr])*2.);
-								Find_non_convex_border((ofstream *)&cout, mol, &T, &LCList, argv[argptr+1], atof(argv[argptr]));
-								//FindDistributionOfEllipsoids((ofstream *)&cout, &T, &LCList, N, number, filename.c_str());
-								argptr+=2;
-							}
-							break;
-						case 'T':
-							ExitFlag = 1;
-							if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for storing tempature: -T <temperature file>" << endl;
-							} else {
-								cout << Verbose(1) << "Storing temperatures in " << argv[argptr] << "." << endl;
-								ofstream *output = new ofstream(argv[argptr], ios::trunc);
-								if (!mol->OutputTemperatureFromTrajectories((ofstream *)&cout, 0, mol->MDSteps, output))
-									cout << Verbose(2) << "File could not be written." << endl;
-								else
-									cout << Verbose(2) << "File stored." << endl;
-								output->close();
-								delete(output);
-								argptr+=1;
-							}
-							break;
-						case 'P':
-							ExitFlag = 1;
-							if ((argptr >= argc) || (argv[argptr][0] == '-')) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for parsing and integrating forces: -P <forces file>" << endl;
-							} else {
-								SaveFlag = true;
-								cout << Verbose(1) << "Parsing forces file and Verlet integrating." << endl;
-								if (!mol->VerletForceIntegration(argv[argptr], configuration.Deltat, configuration.GetIsAngstroem()))
-									cout << Verbose(2) << "File not found." << endl;
-								else
-									cout << Verbose(2) << "File found and parsed." << endl;
-								argptr+=1;
-							}
-							break;
-						case 't':
-							ExitFlag = 1;
-							if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for translation: -t <x> <y> <z>" << endl;
-							} else {
-								ExitFlag = 1;
-								SaveFlag = true;
-								cout << Verbose(1) << "Translating all ions to new origin." << endl;
-								for (int i=NDIM;i--;)
-									x.x[i] = atof(argv[argptr+i]);
-								mol->Translate((const Vector *)&x);
-								argptr+=3;
-							}
-							break;
-						case 's':
-							ExitFlag = 1;
-							if ((argptr >= argc) || (!IsValidNumber(argv[argptr])) ) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for scaling: -s <factor/[factor_x]> [factor_y] [factor_z]" << endl;
-							} else {
-								SaveFlag = true;
-								j = -1;
-								cout << Verbose(1) << "Scaling all ion positions by factor." << endl;
-								factor = new double[NDIM];
-								factor[0] = atof(argv[argptr]);
-								if ((argptr < argc) && (IsValidNumber(argv[argptr])))
-									argptr++;
-								factor[1] = atof(argv[argptr]);
-								if ((argptr < argc) && (IsValidNumber(argv[argptr])))
-									argptr++;
-								factor[2] = atof(argv[argptr]);
-								mol->Scale(&factor);
-								for (int i=0;i<NDIM;i++) {
-									j += i+1;
-									x.x[i] = atof(argv[NDIM+i]);
-									mol->cell_size[j]*=factor[i];
-								}
-								delete[](factor);
-								argptr+=1;
-							}
-							break;
-						case 'b':
-							ExitFlag = 1;
-							if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for centering in box: -b <length_x> <length_y> <length_z>" << endl;
-							} else {
-								SaveFlag = true;
-								j = -1;
-								cout << Verbose(1) << "Centering atoms in config file within given simulation box." << endl;
-								j=-1;
-								for (int i=0;i<NDIM;i++) {
-									j += i+1;
-									x.x[i] = atof(argv[argptr++]);
-									mol->cell_size[j] += x.x[i]*2.;
-								}
-								// center
-								mol->CenterInBox((ofstream *)&cout, &x);
-								// update Box of atoms by boundary
-								mol->SetBoxDimension(&x);
-							}
-							break;
-						case 'c':
-							ExitFlag = 1;
-							if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for centering with boundary: -c <boundary_x> <boundary_y> <boundary_z>" << endl;
-							} else {
-								SaveFlag = true;
-								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<NDIM;i++) {
-									j += i+1;
-									x.x[i] = atof(argv[argptr++]);
-									mol->cell_size[j] += x.x[i]*2.;
-								}
-								mol->Translate((const Vector *)&x);
-							}
-							break;
-						case 'O':
-							ExitFlag = 1;
-							SaveFlag = true;
-							cout << Verbose(1) << "Centering atoms in origin." << endl;
-							mol->CenterOrigin((ofstream *)&cout, &x);
-							mol->SetBoxDimension(&x);
-							break;
-						case 'r':
-							ExitFlag = 1;
-							SaveFlag = true;
-							cout << Verbose(1) << "Converting config file from supposed old to new syntax." << endl;
-							break;
-						case 'F':
-						case 'f':
-							ExitFlag = 1;
-							if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1]))) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments for fragmentation: -f <max. bond distance> <bond order>" << endl;
-							} else {
-								cout << "Fragmenting molecule with bond distance " << argv[argptr] << " angstroem, order of " << argv[argptr+1] << "." << endl;
-								cout << Verbose(0) << "Creating connection matrix..." << endl;
-								start = clock();
-								mol->CreateAdjacencyList((ofstream *)&cout, atof(argv[argptr++]), configuration.GetIsAngstroem());
-								cout << Verbose(0) << "Fragmenting molecule with current connection matrix ..." << endl;
-								if (mol->first->next != mol->last) {
-									ExitFlag = mol->FragmentMolecule((ofstream *)&cout, atoi(argv[argptr]), &configuration);
-								}
-								end = clock();
-								cout << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
-								argptr+=2;
-							}
-							break;
-						case 'm':
-							ExitFlag = 1;
-							j = atoi(argv[argptr++]);
-							if ((j<0) || (j>1)) {
-								cerr << Verbose(1) << "ERROR: Argument of '-m' should be either 0 for no-rotate or 1 for rotate." << endl;
-								j = 0;
-							}
-							if (j) {
-								SaveFlag = true;
-								cout << Verbose(0) << "Converting to prinicipal axis system." << endl;
-							} else
-								cout << Verbose(0) << "Evaluating prinicipal axis." << endl;
-							mol->PrincipalAxisSystem((ofstream *)&cout, (bool)j);
-							break;
-						case 'o':
-							ExitFlag = 1;
-							if ((argptr >= argc) || (argv[argptr][0] == '-')){
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for convex envelope: -o <tecplot output file>" << endl;
-							} else {
-								cout << Verbose(0) << "Evaluating volume of the convex envelope.";
-								cout << Verbose(1) << "Storing tecplot data in " << argv[argptr] << "." << endl;
-								VolumeOfConvexEnvelope((ofstream *)&cout, argv[argptr], &configuration, NULL, mol);
-								argptr+=1;
-							}
-							break;
-						case 'U':
-							ExitFlag = 1;
-							if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) ) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for suspension with specified volume: -U <volume> <density>" << endl;
-								volume = -1; // for case 'u': don't print error again
-							} else {
-								volume = atof(argv[argptr++]);
-								cout << Verbose(0) << "Using " << volume << " angstrom^3 as the volume instead of convex envelope one's." << endl;
-							}
-						case 'u':
-							ExitFlag = 1;
-							if ((argptr >= argc) || (!IsValidNumber(argv[argptr])) ) {
-								if (volume != -1)
-									ExitFlag = 255;
-									cerr << "Not enough arguments given for suspension: -u <density>" << endl;
-							} else {
-								double density;
-								SaveFlag = true;
-								cout << Verbose(0) << "Evaluating necessary cell volume for a cluster suspended in water.";
-								density = atof(argv[argptr++]);
-								if (density < 1.0) {
-									cerr << Verbose(0) << "Density must be greater than 1.0g/cm^3 !" << endl;
-									density = 1.3;
-								}
-//								for(int i=0;i<NDIM;i++) {
-//									repetition[i] = atoi(argv[argptr++]);
-//									if (repetition[i] < 1)
-//										cerr << Verbose(0) << "ERROR: repetition value must be greater 1!" << endl;
-//									repetition[i] = 1;
-//								}
-								PrepareClustersinWater((ofstream *)&cout, &configuration, mol, volume, density);	// if volume == 0, will calculate from ConvexEnvelope
-							}
-							break;
-						case 'd':
-							ExitFlag = 1;
-							if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
-								ExitFlag = 255;
-								cerr << "Not enough or invalid arguments given for repeating cells: -d <repeat_x> <repeat_y> <repeat_z>" << endl;
-							} else {
-								SaveFlag = true;
-								for (int axis = 1; axis <= NDIM; axis++) {
-									int faktor = atoi(argv[argptr++]);
-									int count;
-									element ** Elements;
-									Vector ** vectors;
-									if (faktor < 1) {
-										cerr << Verbose(0) << "ERROR: Repetition faktor mus be greater than 1!" << endl;
-										faktor = 1;
-									}
-									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 = new element *[count];
-										vectors = new Vector *[count];
-										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=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, ...)
-											}
-										}
-										// free memory
-										delete[](Elements);
-										delete[](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;
-						default:	 // no match? Step on
-							if ((argptr < argc) && (argv[argptr][0] != '-')) // if it started with a '-' we've already made a step!
-								argptr++;
-							break;
-					}
-				}
-			} else argptr++;
-		} while (argptr < argc);
-		if (SaveFlag)
-			SaveConfig(ConfigFileName, &configuration, periode, molecules);
-	} else {	// no arguments, hence scan the elements db
-		if (periode->LoadPeriodentafel(configuration.databasepath))
-			cout << Verbose(0) << "Element list loaded successfully." << endl;
-		else
-			cout << Verbose(0) << "Element list loading failed." << endl;
-		configuration.RetrieveConfigPathAndName("main_pcp_linux");
-	}
-	return(ExitFlag);
+  if (argc > 1) { // config file specified as option
+    // 1. : Parse options that just set variables or print help
+    argptr = 1;
+    do {
+      if (argv[argptr][0] == '-') {
+        cout << Verbose(0) << "Recognized command line argument: " << argv[argptr][1] << ".\n";
+        argptr++;
+        switch(argv[argptr-1][1]) {
+          case 'h':
+          case 'H':
+          case '?':
+            cout << "MoleCuilder suite" << endl << "==================" << endl << endl;
+            cout << "Usage: " << argv[0] << "[config file] [-{acefpsthH?vfrp}] [further arguments]" << endl;
+            cout << "or simply " << argv[0] << " without arguments for interactive session." << endl;
+            cout << "\t-a Z x1 x2 x3\tAdd new atom of element Z at coordinates (x1,x2,x3)." << endl;
+            cout << "\t-A <source>\tCreate adjacency list from bonds parsed from 'dbond'-style file." <<endl;
+            cout << "\t-b xx xy xz yy yz zz\tCenter atoms in domain with given symmetric matrix of (xx,xy,xz,yy,yz,zz)." << endl;
+            cout << "\t-B <basis>\tSetting basis to store to MPQC config files." << endl;
+            cout << "\t-c x1 x2 x3\tCenter atoms in domain with a minimum distance to boundary of (x1,x2,x3)." << endl;
+            cout << "\t-D <bond distance>\tDepth-First-Search Analysis of the molecule, giving cycles and tree/back edges." << endl;
+            cout << "\t-O\tCenter atoms in origin." << endl;
+            cout << "\t-d x1 x2 x3\tDuplicate cell along each axis by given factor." << endl;
+            cout << "\t-e <file>\tSets the databases path to be parsed (default: ./)." << endl;
+            cout << "\t-E <id> <Z>\tChange atom <id>'s element to <Z>, <id> begins at 0." << endl;
+            cout << "\t-f/F <dist> <order>\tFragments the molecule in BOSSANOVA manner (with/out rings compressed) and stores config files in same dir as config (return code 0 - fragmented, 2 - no fragmentation necessary)." << endl;
+            cout << "\t-h/-H/-?\tGive this help screen." << endl;
+            cout << "\t-m <0/1>\tCalculate (0)/ Align in(1) PAS with greatest EV along z axis." << endl;
+            cout << "\t-n\tFast parsing (i.e. no trajectories are looked for)." << endl;
+            cout << "\t-N <radius> <file>\tGet non-convex-envelope." << endl;
+            cout << "\t-o <out>\tGet volume of the convex envelope (and store to tecplot file)." << endl;
+            cout << "\t-p <file>\tParse given xyz file and create raw config file from it." << endl;
+            cout << "\t-P <file>\tParse given forces file and append as an MD step to config file via Verlet." << endl;
+            cout << "\t-L <step0> <step1> <prefix>\tStore a linear interpolation between two configurations <step0> and <step1> into single config files with prefix <prefix> and as Trajectories into the current config file." << endl; 
+            cout << "\t-r\t\tConvert file from an old pcp syntax." << endl;
+            cout << "\t-R\t\tRemove all atoms out of sphere around a given one." << endl;
+            cout << "\t-t x1 x2 x3\tTranslate all atoms by this vector (x1,x2,x3)." << endl;
+            cout << "\t-T x1 x2 x3\tTranslate periodically all atoms by this vector (x1,x2,x3)." << endl;
+            cout << "\t-S <file> Store temperatures from the config file in <file>." << endl;
+            cout << "\t-s x1 x2 x3\tScale all atom coordinates by this vector (x1,x2,x3)." << endl;
+            cout << "\t-u rho\tsuspend in water solution and output necessary cell lengths, average density rho and repetition." << endl;
+            cout << "\t-v/-V\t\tGives version information." << endl;
+            cout << "Note: config files must not begin with '-' !" << endl;
+            return (1);
+            break;
+          case 'v':
+          case 'V':
+            cout << argv[0] << " " << VERSIONSTRING << endl;
+            cout << "Build your own molecule position set." << endl;
+            return (1);
+            break;
+          case 'e':
+            if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+              cerr << "Not enough or invalid arguments for specifying element db: -e <db file>" << endl;
+            } else {
+              cout << "Using " << argv[argptr] << " as elements database." << endl;
+              strncpy (configuration.databasepath, argv[argptr], MAXSTRINGSIZE-1);
+              argptr+=1;
+            }
+            break;
+          case 'n':
+            cout << "I won't parse trajectories." << endl;
+            configuration.FastParsing = true;
+            break;
+          default:   // no match? Step on
+            argptr++;
+            break;
+        }
+      } else
+        argptr++;
+    } while (argptr < argc);
+
+    // 2. Parse the element database
+    if (periode->LoadPeriodentafel(configuration.databasepath)) {
+      cout << Verbose(0) << "Element list loaded successfully." << endl;
+      //periode->Output((ofstream *)&cout);
+    } else {
+      cout << Verbose(0) << "Element list loading failed." << endl;
+      return 1;
+    }
+    // 3. Find config file name and parse if possible
+    if (argv[1][0] != '-') {
+      // simply create a new molecule, wherein the config file is loaded and the manipulation takes place
+      mol = new molecule(periode);
+      mol->ActiveFlag = true;
+      molecules->insert(mol);
+
+      cout << Verbose(0) << "Config file given." << endl;
+      test.open(argv[1], ios::in);
+      if (test == NULL) {
+        //return (1);
+        output.open(argv[1], ios::out);
+        if (output == NULL) {
+          cout << Verbose(1) << "Specified config file " << argv[1] << " not found." << endl;
+          config_present = absent;
+        } else {
+          cout << "Empty configuration file." << endl;
+          ConfigFileName = argv[1];
+          config_present = empty;
+          output.close();
+        }
+      } else {
+        test.close();
+        ConfigFileName = argv[1];
+        cout << Verbose(1) << "Specified config file found, parsing ... ";
+        switch (configuration.TestSyntax(ConfigFileName, periode, mol)) {
+          case 1:
+            cout << "new syntax." << endl;
+            configuration.Load(ConfigFileName, periode, mol);
+            config_present = present;
+            break;
+          case 0:
+            cout << "old syntax." << endl;
+            configuration.LoadOld(ConfigFileName, periode, mol);
+            config_present = present;
+            break;
+          default:
+            cout << "Unknown syntax or empty, yet present file." << endl;
+            config_present = empty;
+       }
+      }
+    } else
+      config_present = absent;
+    // 4. parse again through options, now for those depending on elements db and config presence
+    argptr = 1;
+    do {
+      cout << "Current Command line argument: " << argv[argptr] << "." << endl;
+      if (argv[argptr][0] == '-') {
+        argptr++;
+        if ((config_present == present) || (config_present == empty)) {
+          switch(argv[argptr-1][1]) {
+            case 'p':
+              ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+                ExitFlag = 255;
+                cerr << "Not enough arguments for parsing: -p <xyz file>" << endl;
+              } else {
+                SaveFlag = true;
+                cout << Verbose(1) << "Parsing xyz file for new atoms." << endl;
+                if (!mol->AddXYZFile(argv[argptr]))
+                  cout << Verbose(2) << "File not found." << endl;
+                else {
+                  cout << Verbose(2) << "File found and parsed." << endl;
+                  config_present = present;
+                }
+              }
+              break;
+            case 'a':
+              ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-') || (!IsValidNumber(argv[argptr+1]))) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments for adding atom: -a <element> <x> <y> <z>" << endl;
+              } else {
+                SaveFlag = true;
+                cout << Verbose(1) << "Adding new atom with element " << argv[argptr] << " at (" << argv[argptr+1] << "," << argv[argptr+2] << "," << argv[argptr+3] << "), ";
+                first = new atom;
+                first->type = periode->FindElement(atoi(argv[argptr]));
+                if (first->type != NULL)
+                  cout << Verbose(2) << "found element " << first->type->name << endl;
+                for (int i=NDIM;i--;)
+                  first->x.x[i] = atof(argv[argptr+1+i]);
+                if (first->type != NULL) {
+                  mol->AddAtom(first);  // add to molecule
+                  if ((config_present == empty) && (mol->AtomCount != 0))
+                    config_present = present;
+                } else
+                  cerr << Verbose(1) << "Could not find the specified element." << endl;
+                argptr+=4;
+              }
+              break;
+            default:   // no match? Don't step on (this is done in next switch's default)
+              break;
+          }
+        }
+        if (config_present == present) {
+          switch(argv[argptr-1][1]) {
+            case 'B':
+              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for setting MPQC basis: -B <basis name>" << endl;
+              } else {
+                configuration.basis = argv[argptr];
+                cout << Verbose(1) << "Setting MPQC basis to " << configuration.basis << "." << endl;
+                argptr+=1;
+              }
+              break;
+            case 'D':
+              ExitFlag = 1;
+              {
+                cout << Verbose(1) << "Depth-First-Search Analysis." << endl;
+                MoleculeLeafClass *Subgraphs = NULL;      // list of subgraphs from DFS analysis
+                int *MinimumRingSize = new int[mol->AtomCount];
+                atom ***ListOfLocalAtoms = NULL;
+                int FragmentCounter = 0;
+                class StackClass<bond *> *BackEdgeStack = NULL;
+                class StackClass<bond *> *LocalBackEdgeStack = NULL;
+                mol->CreateAdjacencyList((ofstream *)&cout, atof(argv[argptr]), configuration.GetIsAngstroem());
+                mol->CreateListOfBondsPerAtom((ofstream *)&cout);
+                Subgraphs = mol->DepthFirstSearchAnalysis((ofstream *)&cout, BackEdgeStack);
+                if (Subgraphs != NULL) {
+                  Subgraphs->next->FillBondStructureFromReference((ofstream *)&cout, mol, (FragmentCounter = 0), ListOfLocalAtoms, false);  // we want to keep the created ListOfLocalAtoms
+                  while (Subgraphs->next != NULL) {
+                    Subgraphs = Subgraphs->next;
+                    LocalBackEdgeStack = new StackClass<bond *> (Subgraphs->Leaf->BondCount);
+                    Subgraphs->Leaf->PickLocalBackEdges((ofstream *)&cout, ListOfLocalAtoms[FragmentCounter++], BackEdgeStack, LocalBackEdgeStack);
+                    Subgraphs->Leaf->CyclicStructureAnalysis((ofstream *)&cout, BackEdgeStack, MinimumRingSize);
+                    delete(LocalBackEdgeStack);
+                    delete(Subgraphs->previous);
+                  }
+                  delete(Subgraphs);
+                  for (int i=0;i<FragmentCounter;i++)
+                    Free((void **)&ListOfLocalAtoms[FragmentCounter], "ParseCommandLineOptions: **ListOfLocalAtoms[]");
+                  Free((void **)&ListOfLocalAtoms, "ParseCommandLineOptions: ***ListOfLocalAtoms");
+                }
+                delete(BackEdgeStack);
+                delete[](MinimumRingSize);
+              }
+              //argptr+=1;
+              break;
+            case 'E':
+              ExitFlag = 1;
+              if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (argv[argptr+1][0] == '-')) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for changing element: -E <atom nr.> <element>" << endl;
+              } else {
+                SaveFlag = true;
+                cout << Verbose(1) << "Changing atom " << argv[argptr] << " to element " << argv[argptr+1] << "." << endl;
+                first = mol->FindAtom(atoi(argv[argptr]));
+                first->type = periode->FindElement(atoi(argv[argptr+1]));
+                argptr+=2;
+              }
+              break;
+            case 'A':
+              ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+                ExitFlag =255;
+                cerr << "Missing source file for bonds in molecule: -A <bond sourcefile>" << endl;
+              } else {
+                cout << "Parsing bonds from " << argv[argptr] << "." << endl;
+                ifstream *input = new ifstream(argv[argptr]);
+                mol->CreateAdjacencyList2((ofstream *)&cout, input);
+                input->close();
+                argptr+=1;
+              }
+              break;
+            case 'N':
+              ExitFlag = 1;
+              if ((argptr+1 >= argc) || (argv[argptr+1][0] == '-')){
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for non-convex envelope: -o <radius> <tecplot output file>" << endl;
+              } else {
+                class Tesselation T;
+                string filename(argv[argptr+1]);
+                filename.append(".csv");
+                cout << Verbose(0) << "Evaluating non-convex envelope.";
+                cout << Verbose(1) << "Using rolling ball of radius " << atof(argv[argptr]) << " and storing tecplot data in " << argv[argptr+1] << "." << endl;
+                LinkedCell LCList(mol, atof(argv[argptr])*2.);
+                Find_non_convex_border((ofstream *)&cout, mol, &T, &LCList, argv[argptr+1], atof(argv[argptr]));
+                //FindDistributionOfEllipsoids((ofstream *)&cout, &T, &LCList, N, number, filename.c_str());
+                argptr+=2;
+              }
+              break;
+            case 'S':
+              ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for storing tempature: -S <temperature file>" << endl;
+              } else {
+                cout << Verbose(1) << "Storing temperatures in " << argv[argptr] << "." << endl;
+                ofstream *output = new ofstream(argv[argptr], ios::trunc);
+                if (!mol->OutputTemperatureFromTrajectories((ofstream *)&cout, 0, mol->MDSteps, output))
+                  cout << Verbose(2) << "File could not be written." << endl;
+                else
+                  cout << Verbose(2) << "File stored." << endl;
+                output->close();
+                delete(output);
+                argptr+=1;
+              }
+              break;
+            case 'L':
+              ExitFlag = 1;
+              SaveFlag = true;
+              cout << Verbose(1) << "Linear interpolation between configuration " << argv[argptr] << " and " << argv[argptr+1] << "." << endl;
+              if (!mol->LinearInterpolationBetweenConfiguration((ofstream *)&cout, atoi(argv[argptr]), atoi(argv[argptr+1]), argv[argptr+2], configuration))
+                cout << Verbose(2) << "Could not store " << argv[argptr+2] << " files." << endl;
+              else
+                cout << Verbose(2) << "Steps created and " << argv[argptr+2] << " files stored." << endl;
+              argptr+=3;
+              break;
+            case 'P':
+              ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-')) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for parsing and integrating forces: -P <forces file>" << endl;
+              } else {
+                SaveFlag = true;
+                cout << Verbose(1) << "Parsing forces file and Verlet integrating." << endl;
+                if (!mol->VerletForceIntegration((ofstream *)&cout, argv[argptr], configuration))
+                  cout << Verbose(2) << "File not found." << endl;
+                else
+                  cout << Verbose(2) << "File found and parsed." << endl;
+                argptr+=1;
+              }
+              break;
+            case 'R':
+              ExitFlag = 1;
+              if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])))  {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for removing atoms: -R <id> <distance>" << endl;
+              } else {
+                SaveFlag = true;
+                cout << Verbose(1) << "Removing atoms around " << argv[argptr] << " with radius " << argv[argptr+1] << "." << endl;
+                double tmp1 = atof(argv[argptr+1]);
+                atom *third = mol->FindAtom(atoi(argv[argptr]));
+                atom *first = mol->start;
+                if ((third != NULL) && (first != mol->end)) {
+                  atom *second = first->next;
+                  while(second != mol->end) {
+                    first = second;
+                    second = first->next;
+                    if (first->x.DistanceSquared((const Vector *)&third->x) > tmp1*tmp1) // distance to first above radius ...
+                      mol->RemoveAtom(first);
+                  }
+                } else {
+                  cerr << "Removal failed due to missing atoms on molecule or wrong id." << endl;
+                }
+                argptr+=2;
+              }
+              break;
+            case 't':
+              ExitFlag = 1;
+              if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for translation: -t <x> <y> <z>" << endl;
+              } else {
+                ExitFlag = 1;
+                SaveFlag = true;
+                cout << Verbose(1) << "Translating all ions to new origin." << endl;
+                for (int i=NDIM;i--;)
+                  x.x[i] = atof(argv[argptr+i]);
+                mol->Translate((const Vector *)&x);
+                argptr+=3;
+              }
+            case 'T':
+              ExitFlag = 1;
+              if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for periodic translation: -T <x> <y> <z>" << endl;
+              } else {
+                ExitFlag = 1;
+                SaveFlag = true;
+                cout << Verbose(1) << "Translating all ions periodically to new origin." << endl;
+                for (int i=NDIM;i--;)
+                  x.x[i] = atof(argv[argptr+i]);
+                mol->TranslatePeriodically((const Vector *)&x);
+                argptr+=3;
+              }
+              break;
+            case 's':
+              ExitFlag = 1;
+              if ((argptr >= argc) || (!IsValidNumber(argv[argptr])) ) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for scaling: -s <factor/[factor_x]> [factor_y] [factor_z]" << endl;
+              } else {
+                SaveFlag = true;
+                j = -1;
+                cout << Verbose(1) << "Scaling all ion positions by factor." << endl;
+                factor = new double[NDIM];
+                factor[0] = atof(argv[argptr]);
+                if ((argptr < argc) && (IsValidNumber(argv[argptr])))
+                  argptr++;
+                factor[1] = atof(argv[argptr]);
+                if ((argptr < argc) && (IsValidNumber(argv[argptr])))
+                  argptr++;
+                factor[2] = atof(argv[argptr]);
+                mol->Scale(&factor);
+                for (int i=0;i<NDIM;i++) {
+                  j += i+1;
+                  x.x[i] = atof(argv[NDIM+i]);
+                  mol->cell_size[j]*=factor[i];
+                }
+                delete[](factor);
+                argptr+=1;
+              }
+              break;
+            case 'b':
+              ExitFlag = 1;
+              if ((argptr+5 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) || (!IsValidNumber(argv[argptr+3])) || (!IsValidNumber(argv[argptr+4])) || (!IsValidNumber(argv[argptr+5])) ) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for centering in box: -b <xx> <xy> <xz> <yy> <yz> <zz>" << endl;
+              } else {
+                SaveFlag = true;
+                j = -1;
+                cout << Verbose(1) << "Centering atoms in config file within given simulation box." << endl;
+                for (int i=0;i<6;i++) {
+                  mol->cell_size[i] = atof(argv[argptr+i]);
+                }
+                // center
+                mol->CenterInBox((ofstream *)&cout);
+                argptr+=6;
+              }
+              break;
+            case 'c':
+              ExitFlag = 1;
+              if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for centering with boundary: -c <boundary_x> <boundary_y> <boundary_z>" << endl;
+              } else {
+                SaveFlag = true;
+                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<NDIM;i++) {
+                  j += i+1;
+                  x.x[i] = atof(argv[argptr+i]);
+                  mol->cell_size[j] += x.x[i]*2.;
+                }
+                mol->Translate((const Vector *)&x);
+                argptr+=3;
+              }
+              break;
+            case 'O':
+              ExitFlag = 1;
+              SaveFlag = true;
+              cout << Verbose(1) << "Centering atoms on edge and setting box dimensions." << endl;
+              x.Zero();
+              mol->CenterEdge((ofstream *)&cout, &x);
+              mol->SetBoxDimension(&x);
+              argptr+=0;
+              break;
+            case 'r':
+              ExitFlag = 1;
+              SaveFlag = true;
+              cout << Verbose(1) << "Converting config file from supposed old to new syntax." << endl;
+              break;
+            case 'F':
+            case 'f':
+              ExitFlag = 1;
+              if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1]))) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments for fragmentation: -f <max. bond distance> <bond order>" << endl;
+              } else {
+                cout << "Fragmenting molecule with bond distance " << argv[argptr] << " angstroem, order of " << argv[argptr+1] << "." << endl;
+                cout << Verbose(0) << "Creating connection matrix..." << endl;
+                start = clock();
+                mol->CreateAdjacencyList((ofstream *)&cout, atof(argv[argptr++]), configuration.GetIsAngstroem());
+                cout << Verbose(0) << "Fragmenting molecule with current connection matrix ..." << endl;
+                if (mol->first->next != mol->last) {
+                  ExitFlag = mol->FragmentMolecule((ofstream *)&cout, atoi(argv[argptr]), &configuration);
+                }
+                end = clock();
+                cout << Verbose(0) << "Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s." << endl;
+                argptr+=2;
+              }
+              break;
+            case 'm':
+              ExitFlag = 1;
+              j = atoi(argv[argptr++]);
+              if ((j<0) || (j>1)) {
+                cerr << Verbose(1) << "ERROR: Argument of '-m' should be either 0 for no-rotate or 1 for rotate." << endl;
+                j = 0;
+              }
+              if (j) {
+                SaveFlag = true;
+                cout << Verbose(0) << "Converting to prinicipal axis system." << endl;
+              } else
+                cout << Verbose(0) << "Evaluating prinicipal axis." << endl;
+              mol->PrincipalAxisSystem((ofstream *)&cout, (bool)j);
+              break;
+            case 'o':
+              ExitFlag = 1;
+              if ((argptr >= argc) || (argv[argptr][0] == '-')){
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for convex envelope: -o <tecplot output file>" << endl;
+              } else {
+                cout << Verbose(0) << "Evaluating volume of the convex envelope.";
+                cout << Verbose(1) << "Storing tecplot data in " << argv[argptr] << "." << endl;
+                LinkedCell LCList(mol, 10.);
+                class Tesselation *TesselStruct = NULL;
+                Find_convex_border((ofstream *)&cout, mol, TesselStruct, &LCList, argv[argptr]);
+                double clustervolume = VolumeOfConvexEnvelope((ofstream *)&cout, TesselStruct, &configuration);
+                cout << Verbose(0) << "The tesselated surface area is " << clustervolume << "." << endl;
+                delete(TesselStruct);
+                argptr+=1;
+              }
+              break;
+            case 'U':
+              ExitFlag = 1;
+              if ((argptr+1 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) ) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for suspension with specified volume: -U <volume> <density>" << endl;
+                volume = -1; // for case 'u': don't print error again
+              } else {
+                volume = atof(argv[argptr++]);
+                cout << Verbose(0) << "Using " << volume << " angstrom^3 as the volume instead of convex envelope one's." << endl;
+              }
+            case 'u':
+              ExitFlag = 1;
+              if ((argptr >= argc) || (!IsValidNumber(argv[argptr])) ) {
+                if (volume != -1)
+                  ExitFlag = 255;
+                  cerr << "Not enough arguments given for suspension: -u <density>" << endl;
+              } else {
+                double density;
+                SaveFlag = true;
+                cout << Verbose(0) << "Evaluating necessary cell volume for a cluster suspended in water.";
+                density = atof(argv[argptr++]);
+                if (density < 1.0) {
+                  cerr << Verbose(0) << "Density must be greater than 1.0g/cm^3 !" << endl;
+                  density = 1.3;
+                }
+//                for(int i=0;i<NDIM;i++) {
+//                  repetition[i] = atoi(argv[argptr++]);
+//                  if (repetition[i] < 1)
+//                    cerr << Verbose(0) << "ERROR: repetition value must be greater 1!" << endl;
+//                  repetition[i] = 1;
+//                }
+                PrepareClustersinWater((ofstream *)&cout, &configuration, mol, volume, density);  // if volume == 0, will calculate from ConvexEnvelope
+              }
+              break;
+            case 'd':
+              ExitFlag = 1;
+              if ((argptr+2 >= argc) || (!IsValidNumber(argv[argptr])) || (!IsValidNumber(argv[argptr+1])) || (!IsValidNumber(argv[argptr+2])) ) {
+                ExitFlag = 255;
+                cerr << "Not enough or invalid arguments given for repeating cells: -d <repeat_x> <repeat_y> <repeat_z>" << endl;
+              } else {
+                SaveFlag = true;
+                for (int axis = 1; axis <= NDIM; axis++) {
+                  int faktor = atoi(argv[argptr++]);
+                  int count;
+                  element ** Elements;
+                  Vector ** vectors;
+                  if (faktor < 1) {
+                    cerr << Verbose(0) << "ERROR: Repetition faktor mus be greater than 1!" << endl;
+                    faktor = 1;
+                  }
+                  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 = new element *[count];
+                    vectors = new Vector *[count];
+                    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=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, ...)
+                      }
+                    }
+                    // free memory
+                    delete[](Elements);
+                    delete[](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;
+            default:   // no match? Step on
+              if ((argptr < argc) && (argv[argptr][0] != '-')) // if it started with a '-' we've already made a step!
+                argptr++;
+              break;
+          }
+        }
+      } else argptr++;
+    } while (argptr < argc);
+    if (SaveFlag)
+      SaveConfig(ConfigFileName, &configuration, periode, molecules);
+  } else {  // no arguments, hence scan the elements db
+    if (periode->LoadPeriodentafel(configuration.databasepath))
+      cout << Verbose(0) << "Element list loaded successfully." << endl;
+    else
+      cout << Verbose(0) << "Element list loading failed." << endl;
+    configuration.RetrieveConfigPathAndName("main_pcp_linux");
+  }
+  return(ExitFlag);
 };
 
@@ -1779,35 +1937,35 @@
 int main(int argc, char **argv)
 {
-	periodentafel *periode = new periodentafel; // and a period table of all elements
-	MoleculeListClass *molecules = new MoleculeListClass;  // list of all molecules
-	molecule *mol = NULL;
-	config configuration;
-	char choice;	// menu choice char
-	Vector x,y,z,n;	// coordinates for absolute point in cell volume
-	ifstream test;
-	ofstream output;
-	string line;
-	char *ConfigFileName = NULL;
-	int j, count;
-
-	// =========================== PARSE COMMAND LINE OPTIONS ====================================
-	j = ParseCommandLineOptions(argc, argv, molecules, periode, configuration, ConfigFileName);
-	switch(j) {
-	  case 0:  // something went wrong
-	    delete(molecules); // also free's all molecules contained
-	    delete(periode);
-	    return j;
-	    break;
-	  case 1:  // just for -v and -h options
-	    delete(molecules); // also free's all molecules contained
-	    delete(periode);
-	    return 0;
-	    break;
-	  default:
-	    break;
-	}
-
-	// General stuff
-	if (molecules->ListOfMolecules.size() == 0) {
+  periodentafel *periode = new periodentafel; // and a period table of all elements
+  MoleculeListClass *molecules = new MoleculeListClass;  // list of all molecules
+  molecule *mol = NULL;
+  config configuration;
+  char choice;  // menu choice char
+  Vector x,y,z,n;  // coordinates for absolute point in cell volume
+  ifstream test;
+  ofstream output;
+  string line;
+  char *ConfigFileName = NULL;
+  int j;
+
+  // =========================== PARSE COMMAND LINE OPTIONS ====================================
+  j = ParseCommandLineOptions(argc, argv, molecules, periode, configuration, ConfigFileName);
+  switch(j) {
+    case 255:  // something went wrong
+      delete(molecules); // also free's all molecules contained
+      delete(periode);
+      return j;
+      break;
+    case 1:  // just for -v and -h options
+      delete(molecules); // also free's all molecules contained
+      delete(periode);
+      return 0;
+      break;
+    default:
+      break;
+  }
+
+  // General stuff
+  if (molecules->ListOfMolecules.size() == 0) {
     mol = new molecule(periode);
     if (mol->cell_size[0] == 0.) {
@@ -1819,17 +1977,17 @@
     }
     molecules->insert(mol);
-	}
-
-	// =========================== START INTERACTIVE SESSION ====================================
-
-	// now the main construction loop
-	cout << Verbose(0) << endl << "Now comes the real construction..." << endl;
-	do {
-		cout << Verbose(0) << endl << endl;
-		cout << Verbose(0) << "============Molecule list=======================" << endl;
-		molecules->Enumerate((ofstream *)&cout);
-		cout << Verbose(0) << "============Menu===============================" << endl;
+  }
+
+  // =========================== START INTERACTIVE SESSION ====================================
+
+  // now the main construction loop
+  cout << Verbose(0) << endl << "Now comes the real construction..." << endl;
+  do {
+    cout << Verbose(0) << endl << endl;
+    cout << Verbose(0) << "============Molecule list=======================" << endl;
+    molecules->Enumerate((ofstream *)&cout);
+    cout << Verbose(0) << "============Menu===============================" << endl;
     cout << Verbose(0) << "a - set molecule (in)active" << endl;
-    cout << Verbose(0) << "e - edit new molecules" << endl;
+    cout << Verbose(0) << "e - edit molecules (load, parse, save)" << endl;
     cout << Verbose(0) << "g - globally manipulate atoms in molecule" << endl;
     cout << Verbose(0) << "M - Merge molecules" << endl;
@@ -1845,20 +2003,18 @@
     cin >> choice;
 
-		switch (choice) {
-			case 'a':  // (in)activate molecule
+    switch (choice) {
+      case 'a':  // (in)activate molecule
         {
           cout << "Enter index of molecule: ";
           cin >> j;
-          count = 1;
-          MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin();
-          for(; ((ListRunner != molecules->ListOfMolecules.end()) && (count < j)); ListRunner++);
-          if (count == j)
-            (*ListRunner)->ActiveFlag = !(*ListRunner)->ActiveFlag;
+          for(MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++)
+            if ((*ListRunner)->IndexNr == j)
+              (*ListRunner)->ActiveFlag = !(*ListRunner)->ActiveFlag;
         }
-			  break;
-
-			case 'c': // edit each field of the configuration
-			 configuration.Edit();
-			 break;
+        break;
+
+      case 'c': // edit each field of the configuration
+       configuration.Edit();
+       break;
 
       case 'e': // create molecule
@@ -1878,29 +2034,29 @@
         break;
 
-			case 'q': // quit
-				break;
-
-			case 's': // save to config file
-				SaveConfig(ConfigFileName, &configuration, periode, molecules);
-				break;
-
-			case 'T':
-				testroutine(molecules);
-				break;
-
-			default:
-			  break;
-		};
-	} while (choice != 'q');
-
-	// save element data base
-	if (periode->StorePeriodentafel(configuration.databasepath)) //ElementsFileName
-		cout << Verbose(0) << "Saving of elements.db successful." << endl;
-	else
-		cout << Verbose(0) << "Saving of elements.db failed." << endl;
-
-	delete(molecules); // also free's all molecules contained
-	delete(periode);
-	return (0);
+      case 'q': // quit
+        break;
+
+      case 's': // save to config file
+        SaveConfig(ConfigFileName, &configuration, periode, molecules);
+        break;
+
+      case 'T':
+        testroutine(molecules);
+        break;
+
+      default:
+        break;
+    };
+  } while (choice != 'q');
+
+  // save element data base
+  if (periode->StorePeriodentafel(configuration.databasepath)) //ElementsFileName
+    cout << Verbose(0) << "Saving of elements.db successful." << endl;
+  else
+    cout << Verbose(0) << "Saving of elements.db failed." << endl;
+
+  delete(molecules); // also free's all molecules contained
+  delete(periode);
+  return (0);
 }
 
Index: src/config.cpp
===================================================================
--- src/config.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/config.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -7,4 +7,154 @@
 #include "molecules.hpp"
 
+/******************************** Functions for class ConfigFileBuffer **********************/
+
+/** Structure containing compare function for Ion_Type sorting.
+ */
+struct IonTypeCompare {
+  bool operator()(const char* s1, const char *s2) const {
+    char number1[8];
+    char number2[8];
+    char *dummy1, *dummy2;
+    //cout << s1 << "  " << s2 << endl;
+    dummy1 = strchr(s1, '_')+sizeof(char)*5;  // go just after "Ion_Type"
+    dummy2 = strchr(dummy1, '_');
+    strncpy(number1, dummy1, dummy2-dummy1); // copy the number
+    number1[dummy2-dummy1]='\0';
+    dummy1 = strchr(s2, '_')+sizeof(char)*5;  // go just after "Ion_Type"
+    dummy2 = strchr(dummy1, '_');
+    strncpy(number2, dummy1, dummy2-dummy1); // copy the number
+    number2[dummy2-dummy1]='\0';
+    if (atoi(number1) != atoi(number2))
+      return (atoi(number1) < atoi(number2));
+    else {
+      dummy1 = strchr(s1, '_')+sizeof(char);
+      dummy1 = strchr(dummy1, '_')+sizeof(char);
+      dummy2 = strchr(dummy1, ' ') < strchr(dummy1, '\t') ? strchr(dummy1, ' ') : strchr(dummy1, '\t');
+      strncpy(number1, dummy1, dummy2-dummy1); // copy the number
+      number1[dummy2-dummy1]='\0';
+      dummy1 = strchr(s2, '_')+sizeof(char);
+      dummy1 = strchr(dummy1, '_')+sizeof(char);
+      dummy2 = strchr(dummy1, ' ') < strchr(dummy1, '\t') ? strchr(dummy1, ' ') : strchr(dummy1, '\t');
+      strncpy(number2, dummy1, dummy2-dummy1); // copy the number
+      number2[dummy2-dummy1]='\0';
+      return (atoi(number1) < atoi(number2));
+    }
+  }
+};
+
+/** Constructor for ConfigFileBuffer class.
+ */
+ConfigFileBuffer::ConfigFileBuffer()
+{
+  NoLines = 0;
+  CurrentLine = 0;
+  buffer = NULL;
+  LineMapping = NULL;
+}
+
+/** Constructor for ConfigFileBuffer class with filename to be parsed.
+ * \param *filename file name
+ */
+ConfigFileBuffer::ConfigFileBuffer(char *filename)
+{
+  NoLines = 0;
+  CurrentLine = 0;
+  buffer = NULL;
+  LineMapping = NULL;
+  ifstream *file = NULL;
+  char line[MAXSTRINGSIZE];
+
+  // prescan number of lines
+  file= new ifstream(filename);
+  if (file == NULL) {
+    cerr << "ERROR: config file " << filename << " missing!" << endl;
+    return;
+  }
+  NoLines = 0; // we're overcounting by one
+  long file_position = file->tellg(); // mark current position
+  do {
+    file->getline(line, 256);
+    NoLines++;
+  } while (!file->eof());
+  file->clear();
+  file->seekg(file_position, ios::beg);
+  cout << Verbose(1) << NoLines-1 << " lines were recognized." << endl;
+
+  // allocate buffer's 1st dimension
+  if (buffer != NULL) {
+    cerr << "ERROR: FileBuffer->buffer is not NULL!" << endl;
+    return;
+  } else
+    buffer = (char **) Malloc(sizeof(char *)*NoLines, "ConfigFileBuffer::ConfigFileBuffer: **buffer");
+
+  // scan each line and put into buffer
+  int lines=0;
+  int i;
+  do {
+    buffer[lines] = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "ConfigFileBuffer::ConfigFileBuffer: *buffer[]");
+    file->getline(buffer[lines], MAXSTRINGSIZE-1);
+    i = strlen(buffer[lines]);
+    buffer[lines][i] = '\n';
+    buffer[lines][i+1] = '\0';
+    lines++;
+  } while((!file->eof()) && (lines < NoLines));
+  cout << Verbose(1) << lines-1 << " lines were read into the buffer." << endl;
+
+  // close and exit
+  file->close();
+  file->clear();
+  delete(file);
+}
+
+/** Destructor for ConfigFileBuffer class.
+ */
+ConfigFileBuffer::~ConfigFileBuffer()
+{
+  for(int i=0;i<NoLines;++i)
+    Free((void **)&buffer[i], "ConfigFileBuffer::~ConfigFileBuffer: *buffer[]");
+  Free((void **)&buffer, "ConfigFileBuffer::~ConfigFileBuffer: **buffer");
+  Free((void **)&LineMapping, "ConfigFileBuffer::~ConfigFileBuffer: *LineMapping");
+}
+
+
+/** Create trivial mapping.
+ */
+void ConfigFileBuffer::InitMapping()
+{
+  LineMapping = (int *) Malloc(sizeof(int)*NoLines, "ConfigFileBuffer::InitMapping: *LineMapping");
+  for (int i=0;i<NoLines;i++)
+    LineMapping[i] = i;
+}
+
+/** Creates a mapping for the \a *FileBuffer's lines containing the Ion_Type keyword such that they are sorted.
+ * \a *map on return contains a list of NoAtom entries such that going through the list, yields indices to the
+ * lines in \a *FileBuffer in a sorted manner of the Ion_Type?_? keywords. We assume that ConfigFileBuffer::CurrentLine
+ * points to first Ion_Type entry.
+ * \param *FileBuffer pointer to buffer structure
+ * \param NoAtoms of subsequent lines to look at
+ */
+void ConfigFileBuffer::MapIonTypesInBuffer(int NoAtoms)
+{
+  map<const char *, int, IonTypeCompare> LineList;
+  if (LineMapping == NULL) {
+    cerr << "map pointer is NULL: " << LineMapping << endl;
+    return;
+  }
+
+  // put all into hashed map
+  for (int i=0; i<NoAtoms; ++i) {
+    LineList.insert(pair<const char *, int> (buffer[CurrentLine+i], CurrentLine+i));
+  }
+
+  // fill map
+  int nr=0;
+  for (map<const char *, int, IonTypeCompare>::iterator runner = LineList.begin(); runner != LineList.end(); ++runner) {
+    if (CurrentLine+nr < NoLines)
+      LineMapping[CurrentLine+(nr++)] = runner->second;
+    else
+      cerr << "config::MapIonTypesInBuffer - NoAtoms is wrong: We are past the end of the file!" << endl;
+  }
+}
+
 /************************************* Functions for class config ***************************/
 
@@ -13,75 +163,97 @@
 config::config()
 {
-	mainname = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: mainname");
-	defaultpath = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: defaultpath");
-	pseudopotpath = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: pseudopotpath");
+  mainname = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: mainname");
+  defaultpath = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: defaultpath");
+  pseudopotpath = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: pseudopotpath");
   databasepath = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: databasepath");
-	configpath = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: configpath");
-	configname = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: configname");
-	strcpy(mainname,"pcp");
-	strcpy(defaultpath,"not specified");
-	strcpy(pseudopotpath,"not specified");
-	configpath[0]='\0';
-	configname[0]='\0';
-	basis = "3-21G";
-
-	FastParsing = false;
-	ProcPEGamma=8;
-	ProcPEPsi=1;
-	DoOutVis=0;
-	DoOutMes=1;
-	DoOutNICS=0;
-	DoOutOrbitals=0;
-	DoOutCurrent=0;
-	DoPerturbation=0;
-	DoFullCurrent=0;
-	DoWannier=0;
-	CommonWannier=0;
-	SawtoothStart=0.01;
-	VectorPlane=0;
-	VectorCut=0;
-	UseAddGramSch=1;
-	Seed=1;
-
-	MaxOuterStep=0;
-	Deltat=1;
-	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;
+  configpath = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: configpath");
+  configname = (char *) MallocString(sizeof(char)*MAXSTRINGSIZE,"config constructor: configname");
+  ThermostatImplemented = (int *) Malloc((MaxThermostats)*(sizeof(int)), "config constructor: *ThermostatImplemented");
+  ThermostatNames = (char **) Malloc((MaxThermostats)*(sizeof(char *)), "config constructor: *ThermostatNames");
+  for (int j=0;j<MaxThermostats;j++)
+    ThermostatNames[j] = (char *) MallocString(12*(sizeof(char)), "config constructor: ThermostatNames[]");
+  Thermostat = 4;
+  alpha = 0.;
+  ScaleTempStep = 25;
+  TempFrequency = 2.5;
+  strcpy(mainname,"pcp");
+  strcpy(defaultpath,"not specified");
+  strcpy(pseudopotpath,"not specified");
+  configpath[0]='\0';
+  configname[0]='\0';
+  basis = "3-21G";
+
+  strcpy(ThermostatNames[0],"None");
+  ThermostatImplemented[0] = 1;
+  strcpy(ThermostatNames[1],"Woodcock"); 
+  ThermostatImplemented[1] = 1;
+  strcpy(ThermostatNames[2],"Gaussian"); 
+  ThermostatImplemented[2] = 1;
+  strcpy(ThermostatNames[3],"Langevin"); 
+  ThermostatImplemented[3] = 1;
+  strcpy(ThermostatNames[4],"Berendsen"); 
+  ThermostatImplemented[4] = 1;
+  strcpy(ThermostatNames[5],"NoseHoover"); 
+  ThermostatImplemented[5] = 1;
+
+  FastParsing = false;
+  ProcPEGamma=8;
+  ProcPEPsi=1;
+  DoOutVis=0;
+  DoOutMes=1;
+  DoOutNICS=0;
+  DoOutOrbitals=0;
+  DoOutCurrent=0;
+  DoPerturbation=0;
+  DoFullCurrent=0;
+  DoWannier=0;
+  DoConstrainedMD=0;
+  CommonWannier=0;
+  SawtoothStart=0.01;
+  VectorPlane=0;
+  VectorCut=0;
+  UseAddGramSch=1;
+  Seed=1;
+
+  MaxOuterStep=0;
+  Deltat=0.01;
+  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;
 };
 
@@ -91,11 +263,91 @@
 config::~config()
 {
-	Free((void **)&mainname, "config::~config: *mainname");
-	Free((void **)&defaultpath, "config::~config: *defaultpath");
-	Free((void **)&pseudopotpath, "config::~config: *pseudopotpath");
+  Free((void **)&mainname, "config::~config: *mainname");
+  Free((void **)&defaultpath, "config::~config: *defaultpath");
+  Free((void **)&pseudopotpath, "config::~config: *pseudopotpath");
   Free((void **)&databasepath, "config::~config: *databasepath");
-	Free((void **)&configpath, "config::~config: *configpath");
-	Free((void **)&configname, "config::~config: *configname");
+  Free((void **)&configpath, "config::~config: *configpath");
+  Free((void **)&configname, "config::~config: *configname");
+  Free((void **)&ThermostatImplemented, "config::~config: *ThermostatImplemented");
+  for (int j=0;j<MaxThermostats;j++)
+    Free((void **)&ThermostatNames[j], "config::~config: *ThermostatNames[]");
+  Free((void **)&ThermostatNames, "config::~config: **ThermostatNames");
 };
+
+/** Readin of Thermostat related values from parameter file.
+ * \param *source parameter file
+ */
+void config::InitThermostats(ifstream *source)
+{
+  char *thermo = MallocString(12, "IonsInitRead: thermo");
+  int verbose = 0;
+
+  // read desired Thermostat from file along with needed additional parameters
+  if (ParseForParameter(verbose,source,"Thermostat", 0, 1, 1, string_type, thermo, 1, optional)) {
+    if (strcmp(thermo, ThermostatNames[0]) == 0) { // None
+      if (ThermostatImplemented[0] == 1) {
+        Thermostat = None;
+      } else {
+        cout << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        Thermostat = None;
+      }
+    } else if (strcmp(thermo, ThermostatNames[1]) == 0) { // Woodcock
+      if (ThermostatImplemented[1] == 1) {
+        Thermostat = Woodcock;
+        ParseForParameter(verbose,source,"Thermostat", 0, 2, 1, int_type, &ScaleTempStep, 1, critical); // read scaling frequency
+      } else {
+        cout << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        Thermostat = None;
+      }
+    } else if (strcmp(thermo, ThermostatNames[2]) == 0) { // Gaussian
+      if (ThermostatImplemented[2] == 1) {
+        Thermostat = Gaussian;
+        ParseForParameter(verbose,source,"Thermostat", 0, 2, 1, int_type, &ScaleTempStep, 1, critical); // read collision rate
+      } else {
+        cout << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        Thermostat = None;
+      }
+    } else if (strcmp(thermo, ThermostatNames[3]) == 0) { // Langevin
+      if (ThermostatImplemented[3] == 1) {
+        Thermostat = Langevin;
+        ParseForParameter(verbose,source,"Thermostat", 0, 2, 1, double_type, &TempFrequency, 1, critical); // read gamma
+        if (ParseForParameter(verbose,source,"Thermostat", 0, 3, 1, double_type, &alpha, 1, optional)) {
+          cout << Verbose(2) << "Extended Stochastic Thermostat detected with interpolation coefficient " << alpha << "." << endl;
+        } else {
+          alpha = 1.;
+        }
+      } else {
+        cout << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        Thermostat = None;
+      }
+    } else if (strcmp(thermo, ThermostatNames[4]) == 0) { // Berendsen
+      if (ThermostatImplemented[4] == 1) {
+        Thermostat = Berendsen;
+        ParseForParameter(verbose,source,"Thermostat", 0, 2, 1, double_type, &TempFrequency, 1, critical); // read \tau_T
+      } else {
+        cout << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        Thermostat = None;
+      }
+    } else if (strcmp(thermo, ThermostatNames[5]) == 0) { // Nose-Hoover
+      if (ThermostatImplemented[5] == 1) {
+        Thermostat = NoseHoover;
+        ParseForParameter(verbose,source,"Thermostat", 0, 2, 1, double_type, &HooverMass, 1, critical); // read Hoovermass
+        alpha = 0.;
+      } else {
+        cout << Verbose(1) << "Warning: " << ThermostatNames[0] << " thermostat not implemented, falling back to None." << endl;
+        Thermostat = None;
+      }
+    } else {
+      cout << Verbose(1) << " Warning: thermostat name was not understood!" << endl;
+      Thermostat = None;
+    }
+  } else {
+    if ((MaxOuterStep > 0) && (TargetTemp != 0)) 
+      cout << Verbose(2) <<  "No thermostat chosen despite finite temperature MD, falling back to None." << endl;
+    Thermostat = None;
+  }
+  Free((void **)&thermo, "InitThermostats: thermo");
+};
+
 
 /** Displays menu for editing each entry of the config file.
@@ -105,259 +357,259 @@
 void config::Edit()
 {
-	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');
+  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');
 };
 
@@ -370,19 +622,19 @@
 int config::TestSyntax(char *filename, periodentafel *periode, molecule *mol)
 {
-	int test;
-	ifstream file(filename);
-
-	// search file for keyword: ProcPEGamma (new syntax)
-	if (ParseForParameter(1,&file,"ProcPEGamma", 0, 1, 1, int_type, &test, 1, optional)) {
-		file.close();
-		return 1;
-	}
-	// search file for keyword: ProcsGammaPsi (old syntax)
-	if (ParseForParameter(1,&file,"ProcsGammaPsi", 0, 1, 1, int_type, &test, 1, optional)) {
-		file.close();
-		return 0;
-	}
-	file.close();
-	return -1;
+  int test;
+  ifstream file(filename);
+
+  // search file for keyword: ProcPEGamma (new syntax)
+  if (ParseForParameter(1,&file,"ProcPEGamma", 0, 1, 1, int_type, &test, 1, optional)) {
+    file.close();
+    return 1;
+  }
+  // search file for keyword: ProcsGammaPsi (old syntax)
+  if (ParseForParameter(1,&file,"ProcsGammaPsi", 0, 1, 1, int_type, &test, 1, optional)) {
+    file.close();
+    return 0;
+  }
+  file.close();
+  return -1;
 }
 
@@ -392,5 +644,5 @@
 bool config::GetIsAngstroem() const
 {
-	return (IsAngstroem == 1);
+  return (IsAngstroem == 1);
 };
 
@@ -400,5 +652,5 @@
 char * config::GetDefaultPath() const
 {
-	return defaultpath;
+  return defaultpath;
 };
 
@@ -409,5 +661,5 @@
 void config::SetDefaultPath(const char *path)
 {
-	strcpy(defaultpath, path);
+  strcpy(defaultpath, path);
 };
 
@@ -417,24 +669,24 @@
 void config::RetrieveConfigPathAndName(string filename)
 {
-	char *ptr = NULL;
-	char *buffer = new char[MAXSTRINGSIZE];
-	strncpy(buffer, filename.c_str(), MAXSTRINGSIZE);
-	int last = -1;
-	for(last=MAXSTRINGSIZE;last--;) {
-		if (buffer[last] == '/')
-			break;
-	}
-	if (last == -1) { // no path in front, set to local directory.
-		strcpy(configpath, "./");
-		ptr = buffer;
-	} else {
-		strncpy(configpath, buffer, last+1);
-		ptr = &buffer[last+1];
-		if (last < 254)
-			configpath[last+1]='\0';
-	}
-	strcpy(configname, ptr);
-	cout << "Found configpath: " << configpath << ", dir slash was found at " << last << ", config name is " << configname << "." << endl;
-	delete[](buffer);
+  char *ptr = NULL;
+  char *buffer = new char[MAXSTRINGSIZE];
+  strncpy(buffer, filename.c_str(), MAXSTRINGSIZE);
+  int last = -1;
+  for(last=MAXSTRINGSIZE;last--;) {
+    if (buffer[last] == '/')
+      break;
+  }
+  if (last == -1) { // no path in front, set to local directory.
+    strcpy(configpath, "./");
+    ptr = buffer;
+  } else {
+    strncpy(configpath, buffer, last+1);
+    ptr = &buffer[last+1];
+    if (last < 254)
+      configpath[last+1]='\0';
+  }
+  strcpy(configname, ptr);
+  cout << "Found configpath: " << configpath << ", dir slash was found at " << last << ", config name is " << configname << "." << endl;
+  delete[](buffer);
 };
 
@@ -447,324 +699,357 @@
 void config::Load(char *filename, periodentafel *periode, molecule *mol)
 {
-	ifstream *file = new ifstream(filename);
-	if (file == NULL) {
-		cerr << "ERROR: config file " << filename << " missing!" << endl;
-		return;
-	}
-	RetrieveConfigPathAndName(filename);
-	// ParseParameters
-
-	/* Oeffne Hauptparameterdatei */
-	int di;
-	double BoxLength[9];
-	string zeile;
-	string dummy;
-	element *elementhash[MAX_ELEMENTS];
-	char name[MAX_ELEMENTS];
-	char keyword[MAX_ELEMENTS];
-	int Z, No[MAX_ELEMENTS];
-	int verbose = 0;
-	double value[3];
-
-	/* 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,"DoWannier", 0, 1, 1, int_type, &(config::DoWannier), 1, optional)) {
-		config::DoWannier = 0;
-	} else {
-		if (config::DoWannier < 0) config::DoWannier = 0;
-		if (config::DoWannier > 1) config::DoWannier = 1;
-	}
-	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);
-	if (!ParseForParameter(verbose,file,"Deltat", 0, 1, 1, double_type, &(config::Deltat), 1, optional))
-		config::Deltat = 1;
-	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;
-	if (MaxTypes == 0) {
-		cerr << "There are no atoms according to MaxTypes in this config file." << endl;
-	} else {
-		// prescan number of ions per type
-		cout << Verbose(0) << "Prescanning ions per type: " << endl;
-		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[i], 1, critical);
-			ParseForParameter(verbose,file, name, 0, 2, 1, int_type, &Z, 1, critical);
-			elementhash[i] = periode->FindElement(Z);
-			cout << Verbose(1) << i << ". Z = " << elementhash[i]->Z << " with " << No[i] << " ions." << endl;
-		}
-		int repetition = 0; // which repeated keyword shall be read
-
-		map<int, atom *> AtomList[config::MaxTypes];
-		if (!FastParsing) {
-			// parse in trajectories
-			bool status = true;
-			atom *neues = NULL;
-			while (status) {
-				cout << "Currently parsing MD step " << repetition << "." << endl;
-				for (int i=0; i < config::MaxTypes; i++) {
-					sprintf(name,"Ion_Type%i",i+1);
-					for(int j=0;j<No[i];j++) {
-						sprintf(keyword,"%s_%i",name, j+1);
-						if (repetition == 0) {
-							neues = new atom();
-							AtomList[i][j] = neues;
-							neues->type = elementhash[i]; // find element type
-							mol->AddAtom(neues);
-						} else
-							neues = AtomList[i][j];
-						status = (status &&
-										ParseForParameter(verbose,file, keyword, 0, 1, 1, double_type, &neues->x.x[0], 1, (repetition == 0) ? critical : optional) &&
-										ParseForParameter(verbose,file, keyword, 0, 2, 1, double_type, &neues->x.x[1], 1, (repetition == 0) ? critical : optional) &&
-										ParseForParameter(verbose,file, keyword, 0, 3, 1, double_type, &neues->x.x[2], 1, (repetition == 0) ? critical : optional) &&
-										ParseForParameter(verbose,file, keyword, 0, 4, 1, int_type, &neues->FixedIon, 1, (repetition == 0) ? critical : optional));
-						if (!status) break;
-
-						// check size of vectors
-						if (mol->Trajectories[neues].R.size() <= (unsigned int)(repetition)) {
-							//cout << "Increasing size for trajectory array of " << keyword << " to " << (repetition+10) << "." << endl;
-							mol->Trajectories[neues].R.resize(repetition+10);
-							mol->Trajectories[neues].U.resize(repetition+10);
-							mol->Trajectories[neues].F.resize(repetition+10);
-						}
-
-						// put into trajectories list
-						for (int d=0;d<NDIM;d++)
-							mol->Trajectories[neues].R.at(repetition).x[d] = neues->x.x[d];
-
-						// parse velocities if present
-						if(!ParseForParameter(verbose,file, keyword, 0, 5, 1, double_type, &neues->v.x[0], 1,optional))
-							neues->v.x[0] = 0.;
-						if(!ParseForParameter(verbose,file, keyword, 0, 6, 1, double_type, &neues->v.x[1], 1,optional))
-							neues->v.x[1] = 0.;
-						if(!ParseForParameter(verbose,file, keyword, 0, 7, 1, double_type, &neues->v.x[2], 1,optional))
-							neues->v.x[2] = 0.;
-						for (int d=0;d<NDIM;d++)
-							mol->Trajectories[neues].U.at(repetition).x[d] = neues->v.x[d];
-
-						// parse forces if present
-						if(!ParseForParameter(verbose,file, keyword, 0, 8, 1, double_type, &value[0], 1,optional))
-							value[0] = 0.;
-						if(!ParseForParameter(verbose,file, keyword, 0, 9, 1, double_type, &value[1], 1,optional))
-							value[1] = 0.;
-						if(!ParseForParameter(verbose,file, keyword, 1, 10, 1, double_type, &value[2], 1,optional))
-							value[2] = 0.;
-						for (int d=0;d<NDIM;d++)
-							mol->Trajectories[neues].F.at(repetition).x[d] = value[d];
-
-	//						cout << "Parsed position of step " << (repetition) << ": (";
-	//						for (int d=0;d<NDIM;d++)
-	//							cout << mol->Trajectories[neues].R.at(repetition).x[d] << " ";					// next step
-	//						cout << ")\t(";
-	//						for (int d=0;d<NDIM;d++)
-	//							cout << mol->Trajectories[neues].U.at(repetition).x[d] << " ";					// next step
-	//						cout << ")\t(";
-	//						for (int d=0;d<NDIM;d++)
-	//							cout << mol->Trajectories[neues].F.at(repetition).x[d] << " ";					// next step
-	//						cout << ")" << endl;
-					}
-				}
-				repetition++;
-			}
-			repetition--;
-			cout << "Found " << repetition << " trajectory steps." << endl;
-			mol->MDSteps = repetition;
-		} else {
-			// find the maximum number of MD steps so that we may parse last one (Ion_Type1_1 must always be present, because is the first atom)
-			repetition = 0;
-			while ( ParseForParameter(verbose,file, "Ion_Type1_1", 0, 1, 1, double_type, &value[0], repetition, (repetition == 0) ? critical : optional) &&
-							ParseForParameter(verbose,file, "Ion_Type1_1", 0, 2, 1, double_type, &value[1], repetition, (repetition == 0) ? critical : optional) &&
-							ParseForParameter(verbose,file, "Ion_Type1_1", 0, 3, 1, double_type, &value[2], repetition, (repetition == 0) ? critical : optional))
-				repetition++;
-			cout << "I found " << repetition << " times the keyword Ion_Type1_1." << endl;
-			// parse in molecule coordinates
-			for (int i=0; i < config::MaxTypes; i++) {
-				sprintf(name,"Ion_Type%i",i+1);
-				for(int j=0;j<No[i];j++) {
-					sprintf(keyword,"%s_%i",name, j+1);
-					atom *neues = new atom();
-					// then parse for each atom the coordinates as often as present
-					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);
-					ParseForParameter(verbose,file, keyword, 0, 4, 1, int_type, &neues->FixedIon, repetition,critical);
-					if(!ParseForParameter(verbose,file, keyword, 0, 5, 1, double_type, &neues->v.x[0], repetition,optional))
-						neues->v.x[0] = 0.;
-					if(!ParseForParameter(verbose,file, keyword, 0, 6, 1, double_type, &neues->v.x[1], repetition,optional))
-						neues->v.x[1] = 0.;
-					if(!ParseForParameter(verbose,file, keyword, 0, 7, 1, double_type, &neues->v.x[2], repetition,optional))
-						neues->v.x[2] = 0.;
-					// here we don't care if forces are present (last in trajectories is always equal to current position)
-					neues->type = elementhash[i]; // find element type
-					mol->AddAtom(neues);
-				}
-			}
-		}
-	}
-	file->close();
-	delete(file);
+  ifstream *file = new ifstream(filename);
+  if (file == NULL) {
+    cerr << "ERROR: config file " << filename << " missing!" << endl;
+    return;
+  }
+  RetrieveConfigPathAndName(filename);
+
+  // ParseParameterFile
+  struct ConfigFileBuffer *FileBuffer = new ConfigFileBuffer(filename);
+  FileBuffer->InitMapping();
+
+  /* Oeffne Hauptparameterdatei */
+  int di;
+  double BoxLength[9];
+  string zeile;
+  string dummy;
+  element *elementhash[MAX_ELEMENTS];
+  char name[MAX_ELEMENTS];
+  char keyword[MAX_ELEMENTS];
+  int Z, No[MAX_ELEMENTS];
+  int verbose = 0;
+  double value[3];
+  
+  InitThermostats(file);
+  
+  /* Namen einlesen */
+
+  ParseForParameter(verbose,FileBuffer, "mainname", 0, 1, 1, string_type, (config::mainname), 1, critical);
+  ParseForParameter(verbose,FileBuffer, "defaultpath", 0, 1, 1, string_type, (config::defaultpath), 1, critical);
+  ParseForParameter(verbose,FileBuffer, "pseudopotpath", 0, 1, 1, string_type, (config::pseudopotpath), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"ProcPEGamma", 0, 1, 1, int_type, &(config::ProcPEGamma), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"ProcPEPsi", 0, 1, 1, int_type, &(config::ProcPEPsi), 1, critical);
+
+  if (!ParseForParameter(verbose,FileBuffer,"Seed", 0, 1, 1, int_type, &(config::Seed), 1, optional))
+    config::Seed = 1;
+
+  if(!ParseForParameter(verbose,FileBuffer,"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,FileBuffer,"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,FileBuffer,"VectorPlane", 0, 1, 1, int_type, &(config::VectorPlane), 1, optional))
+    config::VectorPlane = -1;
+  if (!ParseForParameter(verbose,FileBuffer,"VectorCut", 0, 1, 1, double_type, &(config::VectorCut), 1, optional))
+    config::VectorCut = 0.;
+  ParseForParameter(verbose,FileBuffer,"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,FileBuffer,"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,FileBuffer,"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,FileBuffer,"DoWannier", 0, 1, 1, int_type, &(config::DoWannier), 1, optional)) {
+    config::DoWannier = 0;
+  } else {
+    if (config::DoWannier < 0) config::DoWannier = 0;
+    if (config::DoWannier > 1) config::DoWannier = 1;
+  }
+  if(!ParseForParameter(verbose,FileBuffer,"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,FileBuffer,"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.;
+  }
+  
+  if (ParseForParameter(verbose,FileBuffer,"DoConstrainedMD", 0, 1, 1, int_type, &(config::DoConstrainedMD), 1, optional))
+    if (config::DoConstrainedMD < 0) 
+      config::DoConstrainedMD = 0;
+  ParseForParameter(verbose,FileBuffer,"MaxOuterStep", 0, 1, 1, int_type, &(config::MaxOuterStep), 1, critical);
+  if (!ParseForParameter(verbose,FileBuffer,"Deltat", 0, 1, 1, double_type, &(config::Deltat), 1, optional))
+    config::Deltat = 1;
+  ParseForParameter(verbose,FileBuffer,"OutVisStep", 0, 1, 1, int_type, &(config::OutVisStep), 1, optional);
+  ParseForParameter(verbose,FileBuffer,"OutSrcStep", 0, 1, 1, int_type, &(config::OutSrcStep), 1, optional);
+  ParseForParameter(verbose,FileBuffer,"TargetTemp", 0, 1, 1, double_type, &(config::TargetTemp), 1, optional);
+  //ParseForParameter(verbose,FileBuffer,"Thermostat", 0, 1, 1, int_type, &(config::ScaleTempStep), 1, optional);
+  if (!ParseForParameter(verbose,FileBuffer,"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,FileBuffer,"MaxPsiStep", 0, 1, 1, int_type, &(config::MaxPsiStep), 1, critical);
+  if (config::MaxPsiStep <= 0) config::MaxPsiStep = 3;
+
+  ParseForParameter(verbose,FileBuffer,"MaxMinStep", 0, 1, 1, int_type, &(config::MaxMinStep), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"RelEpsTotalE", 0, 1, 1, double_type, &(config::RelEpsTotalEnergy), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"RelEpsKineticE", 0, 1, 1, double_type, &(config::RelEpsKineticEnergy), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"MaxMinStopStep", 0, 1, 1, int_type, &(config::MaxMinStopStep), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"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,FileBuffer,"MaxInitMinStep", 0, 1, 1, int_type, &(config::MaxInitMinStep), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"InitRelEpsTotalE", 0, 1, 1, double_type, &(config::InitRelEpsTotalEnergy), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"InitRelEpsKineticE", 0, 1, 1, double_type, &(config::InitRelEpsKineticEnergy), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"InitMaxMinStopStep", 0, 1, 1, int_type, &(config::InitMaxMinStopStep), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"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,FileBuffer, "BoxLength", 0, 3, 3, lower_trigrid, BoxLength, 1, critical); /* Lattice->RealBasis */
+  mol->cell_size[0] = BoxLength[0];
+  mol->cell_size[1] = BoxLength[3];
+  mol->cell_size[2] = BoxLength[4];
+  mol->cell_size[3] = BoxLength[6];
+  mol->cell_size[4] = BoxLength[7];
+  mol->cell_size[5] = BoxLength[8];
+  //if (1) fprintf(stderr,"\n");
+
+  ParseForParameter(verbose,FileBuffer,"DoPerturbation", 0, 1, 1, int_type, &(config::DoPerturbation), 1, optional);
+  ParseForParameter(verbose,FileBuffer,"DoOutNICS", 0, 1, 1, int_type, &(config::DoOutNICS), 1, optional);
+  if (!ParseForParameter(verbose,FileBuffer,"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,FileBuffer,"ECut", 0, 1, 1, double_type, &(config::ECut), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"MaxLevel", 0, 1, 1, int_type, &(config::MaxLevel), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"Level0Factor", 0, 1, 1, int_type, &(config::Lev0Factor), 1, critical);
+  if (config::Lev0Factor < 2) {
+    config::Lev0Factor = 2;
+  }
+  ParseForParameter(verbose,FileBuffer,"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,FileBuffer,"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,FileBuffer,"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,FileBuffer,"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,FileBuffer,"MaxPsiDouble", 0, 1, 1, int_type, &(config::MaxPsiDouble), 1, critical);
+    ParseForParameter(verbose,FileBuffer,"AddPsis", 0, 1, 1, int_type, &(config::AddPsis), 1, optional);
+    break;
+  case 1: // SpinUpDown
+    if (config::ProcPEGamma % 2) config::ProcPEGamma*=2;
+    ParseForParameter(verbose,FileBuffer,"PsiMaxNoUp", 0, 1, 1, int_type, &(config::PsiMaxNoUp), 1, critical);
+    ParseForParameter(verbose,FileBuffer,"PsiMaxNoDown", 0, 1, 1, int_type, &(config::PsiMaxNoDown), 1, critical);
+    ParseForParameter(verbose,FileBuffer,"AddPsis", 0, 1, 1, int_type, &(config::AddPsis), 1, optional);
+    break;
+  }
+
+  // IonsInitRead
+
+  ParseForParameter(verbose,FileBuffer,"RCut", 0, 1, 1, double_type, &(config::RCut), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"IsAngstroem", 0, 1, 1, int_type, &(config::IsAngstroem), 1, critical);
+  ParseForParameter(verbose,FileBuffer,"MaxTypes", 0, 1, 1, int_type, &(config::MaxTypes), 1, critical);
+  if (!ParseForParameter(verbose,FileBuffer,"RelativeCoord", 0, 1, 1, int_type, &(config::RelativeCoord) , 1, optional))
+    config::RelativeCoord = 0;
+  if (!ParseForParameter(verbose,FileBuffer,"StructOpt", 0, 1, 1, int_type, &(config::StructOpt), 1, optional))
+    config::StructOpt = 0;
+  if (MaxTypes == 0) {
+    cerr << "There are no atoms according to MaxTypes in this config file." << endl;
+  } else {
+    // prescan number of ions per type
+    cout << Verbose(0) << "Prescanning ions per type: " << endl;
+    int NoAtoms = 0;
+    for (int i=0; i < config::MaxTypes; i++) {
+      sprintf(name,"Ion_Type%i",i+1);
+      ParseForParameter(verbose,FileBuffer, (const char*)name, 0, 1, 1, int_type, &No[i], 1, critical);
+      ParseForParameter(verbose,FileBuffer, name, 0, 2, 1, int_type, &Z, 1, critical);
+      elementhash[i] = periode->FindElement(Z);
+      cout << Verbose(1) << i << ". Z = " << elementhash[i]->Z << " with " << No[i] << " ions." << endl;
+      NoAtoms += No[i];
+    }
+    int repetition = 0; // which repeated keyword shall be read
+
+    // sort the lines via the LineMapping
+    sprintf(name,"Ion_Type%i",config::MaxTypes);
+    if (!ParseForParameter(verbose,FileBuffer, (const char*)name, 1, 1, 1, int_type, &value[0], 1, critical)) {
+      cerr << "There are no atoms in the config file!" << endl;
+      return;
+    }
+    FileBuffer->CurrentLine++;
+    //cout << FileBuffer->buffer[ FileBuffer->LineMapping[FileBuffer->CurrentLine]];
+    FileBuffer->MapIonTypesInBuffer(NoAtoms);
+    //for (int i=0; i<(NoAtoms < 100 ? NoAtoms : 100 < 100 ? NoAtoms : 100);++i) {
+    //  cout << FileBuffer->buffer[ FileBuffer->LineMapping[FileBuffer->CurrentLine+i]];
+    //}
+
+    map<int, atom *> AtomList[config::MaxTypes];
+    map<int, atom *> LinearList;
+    atom *neues = NULL;
+    if (!FastParsing) {
+      // parse in trajectories
+      bool status = true;
+      while (status) {
+        cout << "Currently parsing MD step " << repetition << "." << endl;
+        for (int i=0; i < config::MaxTypes; i++) {
+          sprintf(name,"Ion_Type%i",i+1);
+          for(int j=0;j<No[i];j++) {
+            sprintf(keyword,"%s_%i",name, j+1);
+            if (repetition == 0) {
+              neues = new atom();
+              AtomList[i][j] = neues;
+              LinearList[ FileBuffer->LineMapping[FileBuffer->CurrentLine] ] = neues;
+              neues->type = elementhash[i]; // find element type
+            } else
+              neues = AtomList[i][j];
+            status = (status &&
+                    ParseForParameter(verbose,FileBuffer, keyword, 0, 1, 1, double_type, &neues->x.x[0], 1, (repetition == 0) ? critical : optional) &&
+                    ParseForParameter(verbose,FileBuffer, keyword, 0, 2, 1, double_type, &neues->x.x[1], 1, (repetition == 0) ? critical : optional) &&
+                    ParseForParameter(verbose,FileBuffer, keyword, 0, 3, 1, double_type, &neues->x.x[2], 1, (repetition == 0) ? critical : optional) &&
+                    ParseForParameter(verbose,FileBuffer, keyword, 0, 4, 1, int_type, &neues->FixedIon, 1, (repetition == 0) ? critical : optional));
+            if (!status) break;
+
+            // check size of vectors
+            if (mol->Trajectories[neues].R.size() <= (unsigned int)(repetition)) {
+              //cout << "Increasing size for trajectory array of " << keyword << " to " << (repetition+10) << "." << endl;
+              mol->Trajectories[neues].R.resize(repetition+10);
+              mol->Trajectories[neues].U.resize(repetition+10);
+              mol->Trajectories[neues].F.resize(repetition+10);
+            }
+
+            // put into trajectories list
+            for (int d=0;d<NDIM;d++)
+              mol->Trajectories[neues].R.at(repetition).x[d] = neues->x.x[d];
+
+            // parse velocities if present
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 5, 1, double_type, &neues->v.x[0], 1,optional))
+              neues->v.x[0] = 0.;
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 6, 1, double_type, &neues->v.x[1], 1,optional))
+              neues->v.x[1] = 0.;
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 7, 1, double_type, &neues->v.x[2], 1,optional))
+              neues->v.x[2] = 0.;
+            for (int d=0;d<NDIM;d++)
+              mol->Trajectories[neues].U.at(repetition).x[d] = neues->v.x[d];
+
+            // parse forces if present
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 8, 1, double_type, &value[0], 1,optional))
+              value[0] = 0.;
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 9, 1, double_type, &value[1], 1,optional))
+              value[1] = 0.;
+            if(!ParseForParameter(verbose,FileBuffer, keyword, 1, 10, 1, double_type, &value[2], 1,optional))
+              value[2] = 0.;
+            for (int d=0;d<NDIM;d++)
+              mol->Trajectories[neues].F.at(repetition).x[d] = value[d];
+
+  //            cout << "Parsed position of step " << (repetition) << ": (";
+  //            for (int d=0;d<NDIM;d++)
+  //              cout << mol->Trajectories[neues].R.at(repetition).x[d] << " ";          // next step
+  //            cout << ")\t(";
+  //            for (int d=0;d<NDIM;d++)
+  //              cout << mol->Trajectories[neues].U.at(repetition).x[d] << " ";          // next step
+  //            cout << ")\t(";
+  //            for (int d=0;d<NDIM;d++)
+  //              cout << mol->Trajectories[neues].F.at(repetition).x[d] << " ";          // next step
+  //            cout << ")" << endl;
+          }
+        }
+        repetition++;
+      }
+      repetition--;
+      cout << "Found " << repetition << " trajectory steps." << endl;
+      mol->MDSteps = repetition;
+    } else {
+      // find the maximum number of MD steps so that we may parse last one (Ion_Type1_1 must always be present, because is the first atom)
+      repetition = 0;
+      while ( ParseForParameter(verbose,FileBuffer, "Ion_Type1_1", 0, 1, 1, double_type, &value[0], repetition, (repetition == 0) ? critical : optional) &&
+              ParseForParameter(verbose,FileBuffer, "Ion_Type1_1", 0, 2, 1, double_type, &value[1], repetition, (repetition == 0) ? critical : optional) &&
+              ParseForParameter(verbose,FileBuffer, "Ion_Type1_1", 0, 3, 1, double_type, &value[2], repetition, (repetition == 0) ? critical : optional))
+        repetition++;
+      cout << "I found " << repetition << " times the keyword Ion_Type1_1." << endl;
+      // parse in molecule coordinates
+      for (int i=0; i < config::MaxTypes; i++) {
+        sprintf(name,"Ion_Type%i",i+1);
+        for(int j=0;j<No[i];j++) {
+          sprintf(keyword,"%s_%i",name, j+1);
+          if (repetition == 0) {
+            neues = new atom();
+            AtomList[i][j] = neues;
+            LinearList[ FileBuffer->LineMapping[FileBuffer->CurrentLine] ] = neues;
+            neues->type = elementhash[i]; // find element type
+          } else
+            neues = AtomList[i][j];
+          // then parse for each atom the coordinates as often as present
+          ParseForParameter(verbose,FileBuffer, keyword, 0, 1, 1, double_type, &neues->x.x[0], repetition,critical);
+          ParseForParameter(verbose,FileBuffer, keyword, 0, 2, 1, double_type, &neues->x.x[1], repetition,critical);
+          ParseForParameter(verbose,FileBuffer, keyword, 0, 3, 1, double_type, &neues->x.x[2], repetition,critical);
+          ParseForParameter(verbose,FileBuffer, keyword, 0, 4, 1, int_type, &neues->FixedIon, repetition,critical);
+          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 5, 1, double_type, &neues->v.x[0], repetition,optional))
+            neues->v.x[0] = 0.;
+          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 6, 1, double_type, &neues->v.x[1], repetition,optional))
+            neues->v.x[1] = 0.;
+          if(!ParseForParameter(verbose,FileBuffer, keyword, 0, 7, 1, double_type, &neues->v.x[2], repetition,optional))
+            neues->v.x[2] = 0.;
+          // here we don't care if forces are present (last in trajectories is always equal to current position)
+          neues->type = elementhash[i]; // find element type
+          mol->AddAtom(neues);
+        }
+      }
+    }
+    // put atoms into the molecule in their original order
+    for(map<int, atom*>::iterator runner = LinearList.begin(); runner != LinearList.end(); ++runner) {
+      mol->AddAtom(runner->second);
+    }
+  }
+  delete(FileBuffer);
 };
 
@@ -776,199 +1061,199 @@
 void config::LoadOld(char *filename, periodentafel *periode, molecule *mol)
 {
-	ifstream *file = new ifstream(filename);
-	if (file == NULL) {
-		cerr << "ERROR: config file " << filename << " missing!" << endl;
-		return;
-	}
-	RetrieveConfigPathAndName(filename);
-	// 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=MAX_ELEMENTS;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++;
-		}
-	}
-	file->close();
-	delete(file);
+  ifstream *file = new ifstream(filename);
+  if (file == NULL) {
+    cerr << "ERROR: config file " << filename << " missing!" << endl;
+    return;
+  }
+  RetrieveConfigPathAndName(filename);
+  // 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=MAX_ELEMENTS;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++;
+    }
+  }
+  file->close();
+  delete(file);
 };
 
@@ -980,102 +1265,125 @@
 bool config::Save(const char *filename, periodentafel *periode, molecule *mol) const
 {
-	bool result = true;
-	// bring MaxTypes up to date
-	mol->CountElements();
-	ofstream *output = NULL;
-	output = new ofstream(filename, ios::out);
-	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);
-		if (mol->MDSteps <=1 )
-			result = result && mol->Output(output);
-		else
-			result = result && mol->OutputTrajectories(output);
-		output->close();
-		output->clear();
-		delete(output);
-		return result;
-	} else
-		return false;
+  bool result = true;
+  // bring MaxTypes up to date
+  mol->CountElements();
+  ofstream *output = NULL;
+  output = new ofstream(filename, ios::out);
+  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 << "DoConstrainedMD\t" << config::DoConstrainedMD << "\t# Do perform a constrained (>0, relating to current MD step) instead of unconstrained (0) MD" << endl;
+    *output << "Thermostat\t" << ThermostatNames[Thermostat] << "\t";
+    switch(Thermostat) {
+      default:
+      case None:
+        break;
+      case Woodcock:
+        *output << ScaleTempStep;
+        break;
+      case Gaussian:
+        *output << ScaleTempStep;
+        break;
+      case Langevin:
+        *output << TempFrequency << "\t" << alpha;
+        break;
+      case Berendsen:
+        *output << TempFrequency;
+        break;
+      case NoseHoover:
+        *output << HooverMass;
+        break;
+    };
+    *output << "\t# Which Thermostat and its parameters to use in MD case." << 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);
+    if (mol->MDSteps <=1 )
+      result = result && mol->Output(output);
+    else
+      result = result && mol->OutputTrajectories(output);
+    output->close();
+    output->clear();
+    delete(output);
+    return result;
+  } else
+    return false;
 };
 
@@ -1087,112 +1395,112 @@
 bool config::SaveMPQC(const char *filename, molecule *mol) const
 {
-	int ElementNo = 0;
-	int AtomNo;
-	atom *Walker = NULL;
-	element *runner = NULL;
-	Vector *center = NULL;
-	ofstream *output = NULL;
-	stringstream *fname = NULL;
-
-	// first without hessian
-	fname = new stringstream;
-	*fname << filename << ".in";
-	output = new ofstream(fname->str().c_str(), ios::out);
-	*output << "% Created by MoleCuilder" << endl;
-	*output << "mpqc: (" << endl;
-	*output << "\tsavestate = no" << endl;
-	*output << "\tdo_gradient = yes" << endl;
-	*output << "\tmole<MBPT2>: (" << endl;
-	*output << "\t\tmaxiter = 200" << endl;
-	*output << "\t\tbasis = $:basis" << endl;
-	*output << "\t\tmolecule = $:molecule" << endl;
-	*output << "\t\treference<CLHF>: (" << endl;
-	*output << "\t\t\tbasis = $:basis" << endl;
-	*output << "\t\t\tmolecule = $:molecule" << endl;
-	*output << "\t\t)" << endl;
-	*output << "\t)" << endl;
-	*output << ")" << endl;
-	*output << "molecule<Molecule>: (" << endl;
-	*output << "\tunit = " << (IsAngstroem ? "angstrom" : "bohr" ) << endl;
-	*output << "\t{ atoms geometry } = {" << endl;
-	center = mol->DetermineCenterOfAll(output);
-	// output of atoms
-	runner = mol->elemente->start;
-	while (runner->next != mol->elemente->end) { // go through every element
-		runner = runner->next;
-		if (mol->ElementsInMolecule[runner->Z]) { // if this element got atoms
-			ElementNo++;
-			AtomNo = 0;
-			Walker = mol->start;
-			while (Walker->next != mol->end) { // go through every atom of this element
-				Walker = Walker->next;
-				if (Walker->type == runner) { // if this atom fits to element
-					AtomNo++;
-					*output << "\t\t" << Walker->type->symbol << " [ " << Walker->x.x[0]-center->x[0] << "\t" << Walker->x.x[1]-center->x[1] << "\t" << Walker->x.x[2]-center->x[2] << " ]" << endl;
-				}
-			}
-		}
-	}
-	delete(center);
-	*output << "\t}" << endl;
-	*output << ")" << endl;
-	*output << "basis<GaussianBasisSet>: (" << endl;
-	*output << "\tname = \""<< basis << "\"" << endl;
-	*output << "\tmolecule = $:molecule" << endl;
-	*output << ")" << endl;
-	output->close();
-	delete(output);
-	delete(fname);
-
-	// second with hessian
-	fname = new stringstream;
-	*fname << filename << ".hess.in";
-	output = new ofstream(fname->str().c_str(), ios::out);
-	*output << "% Created by MoleCuilder" << endl;
-	*output << "mpqc: (" << endl;
-	*output << "\tsavestate = no" << endl;
-	*output << "\tdo_gradient = yes" << endl;
-	*output << "\tmole<CLHF>: (" << endl;
-	*output << "\t\tmaxiter = 200" << endl;
-	*output << "\t\tbasis = $:basis" << endl;
-	*output << "\t\tmolecule = $:molecule" << endl;
-	*output << "\t)" << endl;
-	*output << "\tfreq<MolecularFrequencies>: (" << endl;
-	*output << "\t\tmolecule=$:molecule" << endl;
-	*output << "\t)" << endl;
-	*output << ")" << endl;
-	*output << "molecule<Molecule>: (" << endl;
-	*output << "\tunit = " << (IsAngstroem ? "angstrom" : "bohr" ) << endl;
-	*output << "\t{ atoms geometry } = {" << endl;
-	center = mol->DetermineCenterOfAll(output);
-	// output of atoms
-	runner = mol->elemente->start;
-	while (runner->next != mol->elemente->end) { // go through every element
-		runner = runner->next;
-		if (mol->ElementsInMolecule[runner->Z]) { // if this element got atoms
-			ElementNo++;
-			AtomNo = 0;
-			Walker = mol->start;
-			while (Walker->next != mol->end) { // go through every atom of this element
-				Walker = Walker->next;
-				if (Walker->type == runner) { // if this atom fits to element
-					AtomNo++;
-					*output << "\t\t" << Walker->type->symbol << " [ " << Walker->x.x[0]-center->x[0] << "\t" << Walker->x.x[1]-center->x[1] << "\t" << Walker->x.x[2]-center->x[2] << " ]" << endl;
-				}
-			}
-		}
-	}
-	delete(center);
-	*output << "\t}" << endl;
-	*output << ")" << endl;
-	*output << "basis<GaussianBasisSet>: (" << endl;
-	*output << "\tname = \"3-21G\"" << endl;
-	*output << "\tmolecule = $:molecule" << endl;
-	*output << ")" << endl;
-	output->close();
-	delete(output);
-	delete(fname);
-
-	return true;
+  int ElementNo = 0;
+  int AtomNo;
+  atom *Walker = NULL;
+  element *runner = NULL;
+  Vector *center = NULL;
+  ofstream *output = NULL;
+  stringstream *fname = NULL;
+
+  // first without hessian
+  fname = new stringstream;
+  *fname << filename << ".in";
+  output = new ofstream(fname->str().c_str(), ios::out);
+  *output << "% Created by MoleCuilder" << endl;
+  *output << "mpqc: (" << endl;
+  *output << "\tsavestate = no" << endl;
+  *output << "\tdo_gradient = yes" << endl;
+  *output << "\tmole<MBPT2>: (" << endl;
+  *output << "\t\tmaxiter = 200" << endl;
+  *output << "\t\tbasis = $:basis" << endl;
+  *output << "\t\tmolecule = $:molecule" << endl;
+  *output << "\t\treference<CLHF>: (" << endl;
+  *output << "\t\t\tbasis = $:basis" << endl;
+  *output << "\t\t\tmolecule = $:molecule" << endl;
+  *output << "\t\t)" << endl;
+  *output << "\t)" << endl;
+  *output << ")" << endl;
+  *output << "molecule<Molecule>: (" << endl;
+  *output << "\tunit = " << (IsAngstroem ? "angstrom" : "bohr" ) << endl;
+  *output << "\t{ atoms geometry } = {" << endl;
+  center = mol->DetermineCenterOfAll(output);
+  // output of atoms
+  runner = mol->elemente->start;
+  while (runner->next != mol->elemente->end) { // go through every element
+    runner = runner->next;
+    if (mol->ElementsInMolecule[runner->Z]) { // if this element got atoms
+      ElementNo++;
+      AtomNo = 0;
+      Walker = mol->start;
+      while (Walker->next != mol->end) { // go through every atom of this element
+        Walker = Walker->next;
+        if (Walker->type == runner) { // if this atom fits to element
+          AtomNo++;
+          *output << "\t\t" << Walker->type->symbol << " [ " << Walker->x.x[0]-center->x[0] << "\t" << Walker->x.x[1]-center->x[1] << "\t" << Walker->x.x[2]-center->x[2] << " ]" << endl;
+        }
+      }
+    }
+  }
+  delete(center);
+  *output << "\t}" << endl;
+  *output << ")" << endl;
+  *output << "basis<GaussianBasisSet>: (" << endl;
+  *output << "\tname = \"" << basis << "\"" << endl;
+  *output << "\tmolecule = $:molecule" << endl;
+  *output << ")" << endl;
+  output->close();
+  delete(output);
+  delete(fname);
+
+  // second with hessian
+  fname = new stringstream;
+  *fname << filename << ".hess.in";
+  output = new ofstream(fname->str().c_str(), ios::out);
+  *output << "% Created by MoleCuilder" << endl;
+  *output << "mpqc: (" << endl;
+  *output << "\tsavestate = no" << endl;
+  *output << "\tdo_gradient = yes" << endl;
+  *output << "\tmole<CLHF>: (" << endl;
+  *output << "\t\tmaxiter = 200" << endl;
+  *output << "\t\tbasis = $:basis" << endl;
+  *output << "\t\tmolecule = $:molecule" << endl;
+  *output << "\t)" << endl;
+  *output << "\tfreq<MolecularFrequencies>: (" << endl;
+  *output << "\t\tmolecule=$:molecule" << endl;
+  *output << "\t)" << endl;
+  *output << ")" << endl;
+  *output << "molecule<Molecule>: (" << endl;
+  *output << "\tunit = " << (IsAngstroem ? "angstrom" : "bohr" ) << endl;
+  *output << "\t{ atoms geometry } = {" << endl;
+  center = mol->DetermineCenterOfAll(output);
+  // output of atoms
+  runner = mol->elemente->start;
+  while (runner->next != mol->elemente->end) { // go through every element
+    runner = runner->next;
+    if (mol->ElementsInMolecule[runner->Z]) { // if this element got atoms
+      ElementNo++;
+      AtomNo = 0;
+      Walker = mol->start;
+      while (Walker->next != mol->end) { // go through every atom of this element
+        Walker = Walker->next;
+        if (Walker->type == runner) { // if this atom fits to element
+          AtomNo++;
+          *output << "\t\t" << Walker->type->symbol << " [ " << Walker->x.x[0]-center->x[0] << "\t" << Walker->x.x[1]-center->x[1] << "\t" << Walker->x.x[2]-center->x[2] << " ]" << endl;
+        }
+      }
+    }
+  }
+  delete(center);
+  *output << "\t}" << endl;
+  *output << ")" << endl;
+  *output << "basis<GaussianBasisSet>: (" << endl;
+  *output << "\tname = \"3-21G\"" << endl;
+  *output << "\tmolecule = $:molecule" << endl;
+  *output << ")" << endl;
+  output->close();
+  delete(output);
+  delete(fname);
+
+  return true;
 };
 
@@ -1203,10 +1511,10 @@
  * \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 *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!)
+ *        (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
@@ -1219,215 +1527,424 @@
  */
 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 (dummy != NULL && dummy1 != NULL && ((dummy1[0] == '#') || (dummy1[0] == '\0'))); // 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 %i ends at %i, newline at %i\n", line, strlen(dummy1), strchr(dummy1,'\n')-free_dummy);
-
-		if (dummy1 == NULL) {
-			if (verbose) fprintf(stderr,"Error reading line %i\n",line);
-		} else {
-			//fprintf(stderr,"Now parsing the 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
-							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);
-							}
-							if (*dummy1 == '#') {
-								// found comment, skipping rest of line
-								//if (verbose) fprintf(stderr,"Error: '#' at %i and still missing %i value(s) for parameter %s\n", line, yth-j, name);
-								if (!sequential) { // here we need it!
-									file->seekg(file_position, ios::beg);	// rewind to start position
-								}
-								Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");
-								return 0;
-							}
-							//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
-										maxlength = MAXSTRINGSIZE;
-										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
+  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 (dummy != NULL && dummy1 != NULL && ((dummy1[0] == '#') || (dummy1[0] == '\0'))); // 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 %i ends at %i, newline at %i\n", line, strlen(dummy1), strchr(dummy1,'\n')-free_dummy);
+
+    if (dummy1 == NULL) {
+      if (verbose) fprintf(stderr,"Error reading line %i\n",line);
+    } else {
+      //fprintf(stderr,"Now parsing the 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
+              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);
+              }
+              if (*dummy1 == '#') {
+                // found comment, skipping rest of line
+                //if (verbose) fprintf(stderr,"Error: '#' at %i and still missing %i value(s) for parameter %s\n", line, yth-j, name);
+                if (!sequential) { // here we need it!
+                  file->seekg(file_position, ios::beg);  // rewind to start position
+                }
+                Free((void **)&free_dummy, "config::ParseForParameter: *free_dummy");
+                return 0;
+              }
+              //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
+                    maxlength = MAXSTRINGSIZE;
+                    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
 }
+
+
+/** 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 *FileBuffer pointer to buffer structure
+ * \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, struct ConfigFileBuffer *FileBuffer, 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;
+  int OldCurrentLine = FileBuffer->CurrentLine;
+  char *dummy1, *dummy;    // pointers in the line that is read in per step
+
+  //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 = NULL;
+    do {
+      dummy1 = FileBuffer->buffer[ FileBuffer->LineMapping[FileBuffer->CurrentLine++] ];
+      if (FileBuffer->CurrentLine >= FileBuffer->NoLines) {
+        if ((critical) && (found == 0)) {
+          //Error(InitReading, name);
+          fprintf(stderr,"Error:InitReading, critical %s not found\n", name);
+          exit(255);
+        } else {
+          FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
+          return 0;
+        }
+      }
+      if (dummy1 == NULL) {
+        if (verbose) fprintf(stderr,"Error reading line %i\n",line);
+      } else {
+        //fprintf(stderr,"Now parsing the line %i: %s\n", line, dummy1);
+      }
+      line++;
+    } while (dummy1 != NULL && ((dummy1[0] == '#') || (dummy1[0] == '\0'))); // skip commentary and empty lines
+
+    // 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 = NULL;
+            do {
+              dummy1 = FileBuffer->buffer[ FileBuffer->LineMapping[ FileBuffer->CurrentLine++] ];
+              if (FileBuffer->CurrentLine >= FileBuffer->NoLines) {
+                if ((critical) && (found == 0)) {
+                  //Error(InitReading, name);
+                  fprintf(stderr,"Error:InitReading, critical %s not found\n", name);
+                  exit(255);
+                } else {
+                  FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
+                  return 0;
+                }
+              }
+              if (dummy1 == NULL) {
+                if (verbose) fprintf(stderr,"Error reading line %i\n", line);
+              } else {
+                //fprintf(stderr,"Reading next line %i: %s\n", line, dummy1);
+              }
+              line++;
+            } while (dummy1 != NULL && (dummy1[0] == '#') || (dummy1[0] == '\n'));
+            dummy = dummy1;
+          } else { // simple int, strings or doubles start in the same line
+            while ((*dummy == '\t') || (*dummy == ' '))  // skip interjacent tabs and spaces
+              dummy++;
+          }
+
+          for (j=((type >= grid) ? 0 : yth-1);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
+              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);
+                    //return 0;
+                    exit(255);
+                    //Error(FileOpenParams, NULL);
+                  } else {
+                    if (!sequential) { // here we need it!
+                      FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
+                    }
+                    return 0;
+                  }
+                }
+              } else {
+                //fprintf(stderr,"found tab at %i\n",(char *)dummy-(char *)free_dummy);
+              }
+              if (*dummy1 == '#') {
+                // found comment, skipping rest of line
+                //if (verbose) fprintf(stderr,"Error: '#' at %i and still missing %i value(s) for parameter %s\n", line, yth-j, name);
+                if (!sequential) { // here we need it!
+                  FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
+                }
+                return 0;
+              }
+              //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
+                    maxlength = MAXSTRINGSIZE;
+                    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");
+  if (!sequential) {
+    FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
+  }
+  //fprintf(stderr, "End of Parsing\n\n");
+
+  return (found); // true if found, false if not
+}
Index: src/datacreator.cpp
===================================================================
--- src/datacreator.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/datacreator.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -19,12 +19,12 @@
 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;
+  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;
 };
 
@@ -37,12 +37,12 @@
 bool AppendOutputFile(ofstream &output, const char *dir, const char *filename)
 {
-	stringstream name;
-	name << dir << "/" << filename;
-	output.open(name.str().c_str(), ios::app);
-	if (output == NULL) {
-		cout << "Unable to open " << name.str() << " for writing, is directory correct?" << endl;
-		return false;
-	}
-	return true;
+  stringstream name;
+  name << dir << "/" << filename;
+  output.open(name.str().c_str(), ios::app);
+  if (output == NULL) {
+    cout << "Unable to open " << name.str() << " for writing, is directory correct?" << endl;
+    return false;
+  }
+  return true;
 };
 
@@ -56,25 +56,25 @@
 bool CreateDataEnergyOrder(class EnergyMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const 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" << Fragments.Header << endl;
-	for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
-		for(int i=KeySet.FragmentsPerOrder[BondOrder];i--;) {
-			for(int j=Fragments.RowCounter[ KeySet.OrderSet[BondOrder][i] ];j--;)
-				for(int k=Fragments.ColumnCounter;k--;)
-					Fragments.Matrix[Fragments.MatrixCounter][j][k] += Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
-		}
-		output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
-		for (int l=0;l<Fragments.ColumnCounter;l++)
-			output << scientific << "\t" << Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter]-1 ][l];
-		output << endl;
-	}
-	output.close();
-	return true;
+  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" << Fragments.Header[Fragments.MatrixCounter] << endl;
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    for(int i=KeySet.FragmentsPerOrder[BondOrder];i--;) {
+      for(int j=Fragments.RowCounter[ KeySet.OrderSet[BondOrder][i] ];j--;)
+        for(int k=Fragments.ColumnCounter[ KeySet.OrderSet[BondOrder][i] ];k--;)
+          Fragments.Matrix[Fragments.MatrixCounter][j][k] += Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+    }
+    output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
+    for (int l=0;l<Fragments.ColumnCounter[Fragments.MatrixCounter];l++)
+      output << scientific << "\t" << Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter]-1 ][l];
+    output << endl;
+  }
+  output.close();
+  return true;
 };
 
@@ -89,29 +89,29 @@
 bool CreateDataDeltaEnergyOrder(class EnergyMatrix &Energy, class EnergyMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const 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" << Fragments.Header << endl;
-	Fragments.SetLastMatrix(Energy.Matrix[Energy.MatrixCounter],0);
-	for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
-		for(int i=KeySet.FragmentsPerOrder[BondOrder];i--;) {
-			for(int j=Fragments.RowCounter[ KeySet.OrderSet[BondOrder][i] ];j--;)
-				for(int k=Fragments.ColumnCounter;k--;)
-					Fragments.Matrix[Fragments.MatrixCounter][j][k] -= Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
-		}
-		output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
-		for (int l=0;l<Fragments.ColumnCounter;l++)
-			if (fabs(Energy.Matrix[Energy.MatrixCounter][ Energy.RowCounter[Energy.MatrixCounter]-1 ][l]) < MYEPSILON)
-				output << scientific << "\t" << Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter]-1 ][l];
-			else
-				output << scientific << "\t" << (Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter]-1 ][l] / Energy.Matrix[Energy.MatrixCounter][ Energy.RowCounter[Energy.MatrixCounter]-1 ][l]);
-		output << endl;
-	}
-	output.close();
-	return true;
+  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" << Fragments.Header[Fragments.MatrixCounter] << endl;
+  Fragments.SetLastMatrix(Energy.Matrix[Energy.MatrixCounter],0);
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    for(int i=KeySet.FragmentsPerOrder[BondOrder];i--;) {
+      for(int j=Fragments.RowCounter[ KeySet.OrderSet[BondOrder][i] ];j--;)
+        for(int k=Fragments.ColumnCounter[ KeySet.OrderSet[BondOrder][i] ];k--;)
+          Fragments.Matrix[Fragments.MatrixCounter][j][k] -= Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+    }
+    output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
+    for (int l=0;l<Fragments.ColumnCounter[Energy.MatrixCounter];l++)
+      if (fabs(Energy.Matrix[Energy.MatrixCounter][ Energy.RowCounter[Energy.MatrixCounter]-1 ][l]) < MYEPSILON)
+        output << scientific << "\t" << Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter]-1 ][l];
+      else
+        output << scientific << "\t" << (Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter]-1 ][l] / Energy.Matrix[Energy.MatrixCounter][ Energy.RowCounter[Energy.MatrixCounter]-1 ][l]);
+    output << endl;
+  }
+  output.close();
+  return true;
 };
 
@@ -126,23 +126,23 @@
 bool CreateDataForcesOrder(class ForceMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix,const  char *msg, const 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" << Fragments.Header << endl;
-	Fragments.SetLastMatrix(0.,0);
-	for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
-		Fragments.SumSubForces(Fragments, KeySet, BondOrder, 1.);
-		output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
-		CreateForce(Fragments, Fragments.MatrixCounter);
-		for (int l=0;l<Fragments.ColumnCounter;l++)
-			 output << scientific << "\t" << Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter] ][l];
-		output << endl;
-	}
-	output.close();
-	return true;
+  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" << Fragments.Header[Fragments.MatrixCounter] << endl;
+  Fragments.SetLastMatrix(0.,0);
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    Fragments.SumSubForces(Fragments, KeySet, BondOrder, 1.);
+    output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
+    CreateForce(Fragments, Fragments.MatrixCounter);
+    for (int l=0;l<Fragments.ColumnCounter[Fragments.MatrixCounter];l++)
+       output << scientific << "\t" << Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter] ][l];
+    output << endl;
+  }
+  output.close();
+  return true;
 };
 
@@ -158,23 +158,23 @@
 bool CreateDataDeltaForcesOrder(class ForceMatrix &Force, class ForceMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const 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" << Fragments.Header << endl;
-	Fragments.SetLastMatrix(Force.Matrix[Force.MatrixCounter],0);
-	for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
-		Fragments.SumSubForces(Fragments, KeySet, BondOrder, -1.);
-		output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
-		CreateForce(Fragments, Fragments.MatrixCounter);
-		for (int l=0;l<Fragments.ColumnCounter;l++)
-			 output << scientific << "\t" << Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter] ][l];
-		output << endl;
-	}
-	output.close();
-	return true;
+  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" << Fragments.Header[Fragments.MatrixCounter] << endl;
+  Fragments.SetLastMatrix(Force.Matrix[Force.MatrixCounter],0);
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    Fragments.SumSubForces(Fragments, KeySet, BondOrder, -1.);
+    output << BondOrder+1 << "\t" << KeySet.FragmentsPerOrder[BondOrder];
+    CreateForce(Fragments, Fragments.MatrixCounter);
+    for (int l=0;l<Fragments.ColumnCounter[Fragments.MatrixCounter];l++)
+       output << scientific << "\t" << Fragments.Matrix[Fragments.MatrixCounter][ Fragments.RowCounter[Fragments.MatrixCounter] ][l];
+    output << endl;
+  }
+  output.close();
+  return true;
 };
 
@@ -190,39 +190,39 @@
 bool CreateDataDeltaForcesOrderPerAtom(class ForceMatrix &Force, class ForceMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum)
 {
-	stringstream filename;
-	ofstream output;
-	double norm = 0.;
-
-	filename << prefix << ".dat";
-	if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
-	cout << msg << endl;
-	output << "# " << msg << ", created on " << datum;
-	output << "# AtomNo\t" << Fragments.Header << endl;
-	Fragments.SetLastMatrix(Force.Matrix[Force.MatrixCounter], 0);
-	for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
-		//cout << "Current order is " << BondOrder << "." << endl;
-		Fragments.SumSubForces(Fragments, KeySet, BondOrder, -1.);
-		// errors per atom
-		output << endl << "#Order\t" << BondOrder+1 << endl;
-		for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) {
-			output << Fragments.Indices[Fragments.MatrixCounter][j] << "\t";
-			for (int l=0;l<Fragments.ColumnCounter;l++) {
-				if (((l+1) % 3) == 0) {
-					norm = 0.;
-					for (int m=0;m<NDIM;m++)
-						norm += Force.Matrix[Force.MatrixCounter][ j ][l+m]*Force.Matrix[Force.MatrixCounter][ j ][l+m];
-					norm = sqrt(norm);
-				}
-//				if (norm < MYEPSILON)
-					output << scientific << Fragments.Matrix[Fragments.MatrixCounter][ j ][l] << "\t";
-//				else
-//					output << scientific << (Fragments.Matrix[Fragments.MatrixCounter][ j ][l] / norm) << "\t";
-			}
-			output << endl;
-		}
-		output << endl;
-	}
-	output.close();
-	return true;
+  stringstream filename;
+  ofstream output;
+  double norm = 0.;
+
+  filename << prefix << ".dat";
+  if (!OpenOutputFile(output, dir, filename.str().c_str())) return false;
+  cout << msg << endl;
+  output << "# " << msg << ", created on " << datum;
+  output << "# AtomNo\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
+  Fragments.SetLastMatrix(Force.Matrix[Force.MatrixCounter], 0);
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    //cout << "Current order is " << BondOrder << "." << endl;
+    Fragments.SumSubForces(Fragments, KeySet, BondOrder, -1.);
+    // errors per atom
+    output << endl << "#Order\t" << BondOrder+1 << endl;
+    for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) {
+      output << Fragments.Indices[Fragments.MatrixCounter][j] << "\t";
+      for (int l=0;l<Fragments.ColumnCounter[ Fragments.MatrixCounter ];l++) {
+        if (((l+1) % 3) == 0) {
+          norm = 0.;
+          for (int m=0;m<NDIM;m++)
+            norm += Force.Matrix[Force.MatrixCounter][ j ][l+m]*Force.Matrix[Force.MatrixCounter][ j ][l+m];
+          norm = sqrt(norm);
+        }                                                                                                    
+//        if (norm < MYEPSILON)
+          output << scientific << Fragments.Matrix[Fragments.MatrixCounter][ j ][l] << "\t";
+//        else
+//          output << scientific << (Fragments.Matrix[Fragments.MatrixCounter][ j ][l] / norm) << "\t";
+      }
+      output << endl;
+    }
+    output << endl;
+  }
+  output.close();
+  return true;
 };
 
@@ -237,27 +237,147 @@
 bool CreateDataForcesOrderPerAtom(class ForceMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const 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 << "# AtomNo\t" << Fragments.Header << endl;
-	for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
-		//cout << "Current order is " << BondOrder << "." << endl;
-		Fragments.SumSubForces(Fragments, KeySet, BondOrder, 1.);
-		// errors per atom
-		output << endl << "#Order\t" << BondOrder+1 << endl;
-		for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) {
-			output << Fragments.Indices[Fragments.MatrixCounter][j] << "\t";
-			for (int l=0;l<Fragments.ColumnCounter;l++)
-				output << scientific << Fragments.Matrix[Fragments.MatrixCounter][ j ][l] << "\t";
-			output << endl;
-		}
-		output << endl;
-	}
-	output.close();
-	return true;
+  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 << "# AtomNo\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    //cout << "Current order is " << BondOrder << "." << endl;
+    Fragments.SumSubForces(Fragments, KeySet, BondOrder, 1.);
+    // errors per atom
+    output << endl << "#Order\t" << BondOrder+1 << endl;
+    for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) {
+      output << Fragments.Indices[Fragments.MatrixCounter][j] << "\t";
+      for (int l=0;l<Fragments.ColumnCounter[ Fragments.MatrixCounter ];l++)
+        output << scientific << Fragments.Matrix[Fragments.MatrixCounter][ j ][l] << "\t";
+      output << endl;
+    }
+    output << endl;
+  }
+  output.close();
+  return true;
+};
+
+
+/** Plot hessian error vs. vs atom vs. order.
+ * \param &Hessian HessianMatrix containing reference values (in MatrixCounter matrix)
+ * \param &Fragments HessianMatrix 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
+ * \param *datum current date and time
+ * \return true if file was written successfully
+ */
+bool CreateDataDeltaHessianOrderPerAtom(class HessianMatrix &Hessian, class HessianMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const 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 << "# AtomNo\t" << Fragments.Header[Fragments.MatrixCounter] << endl;
+  Fragments.SetLastMatrix(Hessian.Matrix[Hessian.MatrixCounter], 0);
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    //cout << "Current order is " << BondOrder << "." << endl;
+    Fragments.SumSubHessians(Fragments, KeySet, BondOrder, -1.);
+    // errors per atom
+    output << endl << "#Order\t" << BondOrder+1 << endl;
+    for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) { 
+      output << Fragments.Indices[Fragments.MatrixCounter][j] << "\t";
+      for (int l=0;l<Fragments.ColumnCounter[ Fragments.MatrixCounter ];l++) {
+        output << scientific << Fragments.Matrix[Fragments.MatrixCounter][ j ][l] << "\t";
+      }
+      output << endl;
+    }
+    output << endl;
+  }
+  output.close();
+  return true;
+};
+
+/** Plot hessian error vs. vs atom vs. order in the frobenius norm.
+ * \param &Hessian HessianMatrix containing reference values (in MatrixCounter matrix)
+ * \param &Fragments HessianMatrix 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
+ * \param *datum current date and time
+ * \return true if file was written successfully
+ */
+bool CreateDataDeltaFrobeniusOrderPerAtom(class HessianMatrix &Hessian, class HessianMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum) 
+{
+  stringstream filename;
+  ofstream output;
+  double norm = 0;
+  double tmp;
+
+  filename << prefix << ".dat";
+  if (!OpenOutputFile(output, dir, filename.str().c_str())) return false; 
+  cout << msg << endl;
+  output << "# " << msg << ", created on " << datum;
+  output << "# AtomNo\t";
+  Fragments.SetLastMatrix(Hessian.Matrix[Hessian.MatrixCounter], 0);
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    output << "Order" << BondOrder+1 << "\t";
+  }
+  output << endl;
+  output << Fragments.RowCounter[ Fragments.MatrixCounter ] << "\t";
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    //cout << "Current order is " << BondOrder << "." << endl;
+    Fragments.SumSubHessians(Fragments, KeySet, BondOrder, -1.);
+    // frobenius norm of errors per atom
+    norm = 0.;
+    for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) { 
+      for (int l=0;l<Fragments.ColumnCounter[ Fragments.MatrixCounter ];l++) {
+        tmp = Fragments.Matrix[Fragments.MatrixCounter][ j ][l];
+        norm += tmp*tmp;
+      }
+    }
+    output << scientific << sqrt(norm)/(Fragments.RowCounter[ Fragments.MatrixCounter ]*Fragments.ColumnCounter[ Fragments.MatrixCounter] ) << "\t";
+  }
+  output << endl;
+  output.close();
+  return true;
+};
+
+/** Plot hessian error vs. vs atom vs. order.
+ * \param &Fragments HessianMatrix 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
+ * \param *datum current date and time
+ * \return true if file was written successfully
+ */
+bool CreateDataHessianOrderPerAtom(class HessianMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const 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 << "# AtomNo\t" << Fragments.Header[ Fragments.MatrixCounter ] << endl;
+  Fragments.SetLastMatrix(0., 0);
+  for (int BondOrder=0;BondOrder<KeySet.Order;BondOrder++) {
+    //cout << "Current order is " << BondOrder << "." << endl;
+    Fragments.SumSubHessians(Fragments, KeySet, BondOrder, 1.);
+    // errors per atom
+    output << endl << "#Order\t" << BondOrder+1 << endl;
+    for(int j=0;j<Fragments.RowCounter[ Fragments.MatrixCounter ];j++) { 
+      output << Fragments.Indices[Fragments.MatrixCounter][j] << "\t";
+      for (int l=0;l<Fragments.ColumnCounter[ Fragments.MatrixCounter ];l++)
+        output << scientific << Fragments.Matrix[Fragments.MatrixCounter][ j ][l] << "\t";
+      output << endl;
+    }
+    output << endl;
+  }
+  output.close();
+  return true;
 };
 
@@ -266,23 +386,23 @@
 bool CreateDataFragment(class MatrixContainer &Fragment, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const 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 << endl;
-	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;
+  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 << endl;
+  output << "#Order\tFrag.No.\t" << Fragment.Header[ Fragment.MatrixCounter ] << 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[ KeySet.OrderSet[BondOrder][i] ];l++)
+        output << scientific << "\t" << Fragment.Matrix[ KeySet.OrderSet[BondOrder][i] ][ Fragment.RowCounter[ KeySet.OrderSet[BondOrder][i] ] ][l];
+      output << endl;
+    }
+  }
+  output.close();
+  return true;
 };
 
@@ -294,12 +414,12 @@
 void CreateMaxFragmentOrder(class MatrixContainer &Fragments, class KeySetsContainer &KeySet, int BondOrder)
 {
-	for(int j=Fragments.RowCounter[ Fragments.MatrixCounter ];j--;) {
-		for(int 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=Fragments.ColumnCounter;k--;)
-					Fragments.Matrix[ Fragments.MatrixCounter ][j][k] = Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
-			}
-		}
-	}
+  for(int j=Fragments.RowCounter[ Fragments.MatrixCounter ];j--;) {
+    for(int 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=Fragments.ColumnCounter[ Fragments.MatrixCounter ];k--;)
+          Fragments.Matrix[ Fragments.MatrixCounter ][j][k] = Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+      }
+    }
+  }
 };
 
@@ -311,18 +431,18 @@
 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=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=Fragments.ColumnCounter;k--;)
-					Fragments.Matrix[ Fragments.MatrixCounter ][j][k] = Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
-			}
-		}
-	}
+  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=Fragments.ColumnCounter[ Fragments.MatrixCounter ];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=Fragments.ColumnCounter[ Fragments.MatrixCounter ];k--;)
+          Fragments.Matrix[ Fragments.MatrixCounter ][j][k] = Fragments.Matrix[ KeySet.OrderSet[BondOrder][i] ][j][k];
+      }
+    }
+  }
 };
 
@@ -331,23 +451,23 @@
 bool CreateDataFragmentOrder(class MatrixContainer &Fragment, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const 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;
+  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[ Fragment.MatrixCounter ] << 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[ Fragment.MatrixCounter ];l++)
+      output << scientific << "\t" << Fragment.Matrix[ Fragment.MatrixCounter ][ Fragment.RowCounter[ Fragment.MatrixCounter ]-1 ][l];
+    output << endl;
+  }
+  output.close();
+  return true;
 };
 
@@ -358,6 +478,6 @@
 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];
+  for(int k=0;k<Energy.ColumnCounter[MatrixNumber];k++)
+    Energy.Matrix[MatrixNumber][ Energy.RowCounter[MatrixNumber] ] [k] =  Energy.Matrix[MatrixNumber][ Energy.RowCounter[MatrixNumber]-1 ] [k];
 };
 
@@ -369,29 +489,29 @@
 void CreateMinimumForce(class MatrixContainer &Force, int MatrixNumber)
 {
-	for (int 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=NDIM;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=NDIM;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=NDIM;m--;)
-					Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l+m]	= Force.Matrix[MatrixNumber][ k ][l+m];
-				stored = tmp;
-			}
-		}
-	}
+  for (int l=Force.ColumnCounter[MatrixNumber];l--;)
+    Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] = 0.;
+  for (int l=5;l<Force.ColumnCounter[MatrixNumber];l+=3) {
+    double stored = 0;
+    int k=0;
+    do {
+      for (int m=NDIM;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=NDIM;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=NDIM;m--;)
+          Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l+m]  = Force.Matrix[MatrixNumber][ k ][l+m];
+        stored = tmp;
+      }
+    }
+  }
 };
 
@@ -399,24 +519,24 @@
  * 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
+  * \param MatrixNumber the index for the ForceMatrix::matrix array
  */
 void CreateMeanForce(class MatrixContainer &Force, int MatrixNumber)
 {
-	int divisor = 0;
-	for (int 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=Force.RowCounter[MatrixNumber];k--;) {
-			double norm = 0.;
-			for (int m=NDIM;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;
-	}
+  int divisor = 0;
+  for (int l=Force.ColumnCounter[MatrixNumber];l--;)
+    Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] = 0.;
+  for (int l=5;l<Force.ColumnCounter[MatrixNumber];l+=3) {
+    double tmp = 0;
+    for (int k=Force.RowCounter[MatrixNumber];k--;) {
+      double norm = 0.;
+      for (int m=NDIM;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;
+  }
 };
 
@@ -428,18 +548,18 @@
 void CreateMaximumForce(class MatrixContainer &Force, int MatrixNumber)
 {
-	for (int l=5;l<Force.ColumnCounter;l+=3) {
-		double stored = 0;
-		for (int k=Force.RowCounter[MatrixNumber];k--;) {
-			double tmp = 0;
-			for (int m=NDIM;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=NDIM;m--;)
-					Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l+m]	= Force.Matrix[MatrixNumber][ k ][l+m];
-				stored = tmp;
-			}
-		}
-	}
+  for (int l=5;l<Force.ColumnCounter[MatrixNumber];l+=3) {
+    double stored = 0;
+    for (int k=Force.RowCounter[MatrixNumber];k--;) {
+      double tmp = 0;
+      for (int m=NDIM;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=NDIM;m--;)
+          Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l+m]  = Force.Matrix[MatrixNumber][ k ][l+m];
+        stored = tmp;
+      }
+    }
+  }
 };
 
@@ -450,5 +570,5 @@
 void CreateSameForce(class MatrixContainer &Force, int MatrixNumber)
 {
-	// does nothing
+  // does nothing
 };
 
@@ -460,10 +580,10 @@
 void CreateVectorSumForce(class MatrixContainer &Force, int MatrixNumber)
 {
-	for (int l=Force.ColumnCounter;l--;)
-		Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] = 0.;
-	for (int l=0;l<Force.ColumnCounter;l++) {
-		for (int k=Force.RowCounter[MatrixNumber];k--;)
-			Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] += Force.Matrix[MatrixNumber][k][l];
-	}
+  for (int l=Force.ColumnCounter[MatrixNumber];l--;)
+    Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] = 0.;
+  for (int l=0;l<Force.ColumnCounter[MatrixNumber];l++) {
+    for (int k=Force.RowCounter[MatrixNumber];k--;)
+      Force.Matrix[MatrixNumber][ Force.RowCounter[MatrixNumber] ][l] += Force.Matrix[MatrixNumber][k][l];
+  }
 };
 
@@ -480,18 +600,18 @@
 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 != NULL)
-		output << "set logscale " << logscale << endl;
-	if (extraline != NULL)
-		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;
+  //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 != NULL)
+    output << "set logscale " << logscale << endl;
+  if (extraline != NULL)
+    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;
 };
 
@@ -517,14 +637,14 @@
 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;
+  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;
 };
 
@@ -538,17 +658,17 @@
 void AbsEnergyPlotLine(ofstream &output, class MatrixContainer &Energy, const char *prefix, const char *xargument, const char *uses)
 {
-	stringstream line(Energy.Header);
-	string token;
-
-	getline(line, token, '\t');
-	for (int i=2; i<= Energy.ColumnCounter;i++) {
-		getline(line, token, '\t');
-		while (token[0] == ' ') // remove leading white spaces
-			token.erase(0,1);
-		output << "'" << prefix << ".dat' title '" << token << "' using " << xargument << ":(abs($" << i+2 << ")) " << uses;
-		if (i != (Energy.ColumnCounter))
-			output << ", \\";
-		output << endl;
-	}
+  stringstream line(Energy.Header[ Energy.MatrixCounter ]);
+  string token;
+
+  getline(line, token, '\t');
+  for (int i=2; i<= Energy.ColumnCounter[Energy.MatrixCounter];i++) {
+    getline(line, token, '\t');
+    while (token[0] == ' ') // remove leading white spaces
+      token.erase(0,1);
+    output << "'" << prefix << ".dat' title '" << token << "' using " << xargument << ":(abs($" << i+2 << ")) " << uses;
+    if (i != (Energy.ColumnCounter[Energy.MatrixCounter]))
+      output << ", \\";
+    output << endl;
+  }
 };
 
@@ -562,17 +682,17 @@
 void EnergyPlotLine(ofstream &output, class MatrixContainer &Energy, const char *prefix, const char *xargument, const char *uses)
 {
-	stringstream line(Energy.Header);
-	string token;
-
-	getline(line, token, '\t');
-	for (int i=1; i<= Energy.ColumnCounter;i++) {
-		getline(line, token, '\t');
-		while (token[0] == ' ') // remove leading white spaces
-			token.erase(0,1);
-		output << "'" << prefix << ".dat' title '" << token << "' using " << xargument << ":" << i+2 << " " << uses;
-		if (i != (Energy.ColumnCounter))
-			output << ", \\";
-		output << endl;
-	}
+  stringstream line(Energy.Header[Energy.MatrixCounter]);
+  string token;
+
+  getline(line, token, '\t');
+  for (int i=1; i<= Energy.ColumnCounter[Energy.MatrixCounter];i++) {
+    getline(line, token, '\t');
+    while (token[0] == ' ') // remove leading white spaces
+      token.erase(0,1);
+    output << "'" << prefix << ".dat' title '" << token << "' using " << xargument << ":" << i+2 << " " << uses;
+    if (i != (Energy.ColumnCounter[Energy.MatrixCounter]))
+      output << ", \\";
+    output << endl;
+  }
 };
 
@@ -586,24 +706,24 @@
 void ForceMagnitudePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses)
 {
-	stringstream line(Force.Header);
-	string token;
-
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	for (int i=7; i< Force.ColumnCounter;i+=NDIM) {
-		getline(line, token, '\t');
-		while (token[0] == ' ') // remove leading white spaces
-			token.erase(0,1);
-		token.erase(token.length(), 1);	// kill residual index char (the '0')
-		output << "'" << prefix << ".dat' title '" << token << "' using " << xargument << ":(sqrt($" << i+1 << "*$" << i+1 << "+$" << i+2 << "*$" << i+2 << "+$" << i+3 << "*$" << i+3 << ")) " << uses;
-		if (i != (Force.ColumnCounter-1))
-			output << ", \\";
-		output << endl;
-		getline(line, token, '\t');
-		getline(line, token, '\t');
-	}
+  stringstream line(Force.Header[Force.MatrixCounter]);
+  string token;
+
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  for (int i=7; i< Force.ColumnCounter[Force.MatrixCounter];i+=NDIM) {
+    getline(line, token, '\t');
+    while (token[0] == ' ') // remove leading white spaces
+      token.erase(0,1);
+    token.erase(token.length(), 1);  // kill residual index char (the '0')
+    output << "'" << prefix << ".dat' title '" << token << "' using " << xargument << ":(sqrt($" << i+1 << "*$" << i+1 << "+$" << i+2 << "*$" << i+2 << "+$" << i+3 << "*$" << i+3 << ")) " << uses;
+    if (i != (Force.ColumnCounter[Force.MatrixCounter]-1))
+      output << ", \\";
+    output << endl;
+    getline(line, token, '\t');
+    getline(line, token, '\t');
+  }
 };
 
@@ -617,24 +737,24 @@
 void AbsFirstForceValuePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses)
 {
-	stringstream line(Force.Header);
-	string token;
-
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	for (int i=7; i< Force.ColumnCounter;i+=NDIM) {
-		getline(line, token, '\t');
-		while (token[0] == ' ') // remove leading white spaces
-			token.erase(0,1);
-		token.erase(token.length(), 1);	// kill residual index char (the '0')
-		output << "'" << prefix << ".dat' title '" << token << "' using " << xargument << ":(abs($" << i+1 << ")) " << uses;
-		if (i != (Force.ColumnCounter-1))
-			output << ", \\";
-		output << endl;
-		getline(line, token, '\t');
-		getline(line, token, '\t');
-	}
+  stringstream line(Force.Header[Force.MatrixCounter]);
+  string token;
+
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  for (int i=7; i< Force.ColumnCounter[Force.MatrixCounter];i+=NDIM) {
+    getline(line, token, '\t');
+    while (token[0] == ' ') // remove leading white spaces
+      token.erase(0,1);
+    token.erase(token.length(), 1);  // kill residual index char (the '0')
+    output << "'" << prefix << ".dat' title '" << token << "' using " << xargument << ":(abs($" << i+1 << ")) " << uses;
+    if (i != (Force.ColumnCounter[Force.MatrixCounter]-1))
+      output << ", \\";
+    output << endl;
+    getline(line, token, '\t');
+    getline(line, token, '\t');
+  }
 };
 
@@ -648,25 +768,25 @@
 void BoxesForcePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses)
 {
-	stringstream line(Force.Header);
-	const char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
-	string token;
-
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	for (int i=7; i< Force.ColumnCounter;i+=NDIM) {
-		getline(line, token, '\t');
-		while (token[0] == ' ') // remove leading white spaces
-			token.erase(0,1);
-		token.erase(token.length(), 1);	// kill residual index char (the '0')
-		output << "'" << prefix << ".dat' title '" << token << "' 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;
-		getline(line, token, '\t');
-		getline(line, token, '\t');
-	}
+  stringstream line(Force.Header[Force.MatrixCounter]);
+  char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
+  string token;
+
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  for (int i=7; i< Force.ColumnCounter[Force.MatrixCounter];i+=NDIM) {
+    getline(line, token, '\t');
+    while (token[0] == ' ') // remove leading white spaces
+      token.erase(0,1);
+    token.erase(token.length(), 1);  // kill residual index char (the '0')
+    output << "'" << prefix << ".dat' title '" << token << "' 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[Force.MatrixCounter]-1))
+      output << ", \\";
+    output << endl;
+    getline(line, token, '\t');
+    getline(line, token, '\t');
+  }
 };
 
@@ -680,24 +800,24 @@
 void BoxesFirstForceValuePlotLine(ofstream &output, class MatrixContainer &Force, const char *prefix, const char *xargument, const char *uses)
 {
-	stringstream line(Force.Header);
-	const char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
-	string token;
-
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	getline(line, token, '\t');
-	for (int i=7; i< Force.ColumnCounter;i+=NDIM) {
-		getline(line, token, '\t');
-		while (token[0] == ' ') // remove leading white spaces
-			token.erase(0,1);
-		token.erase(token.length(), 1);	// kill residual index char (the '0')
-		output << "'" << prefix << ".dat' title '" << token << "' 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;
-		getline(line, token, '\t');
-		getline(line, token, '\t');
-	}
-};
+  stringstream line(Force.Header[Force.MatrixCounter]);
+  char *fillcolor[5] = {"black", "red", "blue", "green", "cyan"};
+  string token;
+
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  getline(line, token, '\t');
+  for (int i=7; i< Force.ColumnCounter[Force.MatrixCounter];i+=NDIM) {
+    getline(line, token, '\t');
+    while (token[0] == ' ') // remove leading white spaces
+      token.erase(0,1);
+    token.erase(token.length(), 1);  // kill residual index char (the '0')
+    output << "'" << prefix << ".dat' title '" << token << "' using ($" << xargument << "+" << fixed << setprecision(1) << (double)((i-7)/3)*0.2 << "):" << i+1 << " " << uses << " " << fillcolor[(i-7)/3];
+    if (i != (Force.ColumnCounter[Force.MatrixCounter]-1))
+      output << ", \\";
+    output << endl;
+    getline(line, token, '\t');
+    getline(line, token, '\t');
+  }
+};
Index: src/datacreator.hpp
===================================================================
--- src/datacreator.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/datacreator.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -25,5 +25,8 @@
 bool CreateDataForcesOrderPerAtom(class ForceMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum);
 bool CreateDataDeltaForcesOrder(class ForceMatrix &Force, class ForceMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum, void (*CreateForce)(class MatrixContainer &, int));
-bool CreateDataDeltaForcesOrderPerAtom(class ForceMatrix &Force, class ForceMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum);
+bool CreateDataDeltaForcesOrderPerAtom(class ForceMatrix &Force, class ForceMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum); 
+bool CreateDataHessianOrderPerAtom(class HessianMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum); 
+bool CreateDataDeltaHessianOrderPerAtom(class HessianMatrix &Hessian, class HessianMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum); 
+bool CreateDataDeltaFrobeniusOrderPerAtom(class HessianMatrix &Hessian, class HessianMatrix &Fragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum); 
 bool CreateDataFragment(class MatrixContainer &ForceFragments, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum, void (*CreateForce)(class MatrixContainer &, int));
 bool CreateDataFragmentOrder(class MatrixContainer &Fragment, class KeySetsContainer &KeySet, const char *dir, const char *prefix, const char *msg, const char *datum, void (*CreateFragmentOrder)(class MatrixContainer &, class KeySetsContainer &, int));
Index: src/defs.hpp
===================================================================
--- src/defs.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/defs.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -10,10 +10,19 @@
 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 
-#define AtomicEnergyToKelvin 315774.67	//!< conversion factor from atomic energy to kelvin via boltzmann factor
+#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 
+#define AtomicEnergyToKelvin 315774.67  //!< conversion factor from atomic energy to kelvin via boltzmann factor
+#define KelvinToAtomicTemperature 3.1668152e-06    //!< conversion factor for Kelvin to atomic temperature (Hartree over k_B)
+#define KelvinToeV 8.6173422e-05                   //!< conversion factor for Kelvin to Ht (k_B * T = energy), thus Boltzmann constant in eV/K
+#define AtomicMassUnitsToeV 931494088.        //!< conversion factor for atomic weight in units to mass in eV
+#define AtomicMassUnitsToHt 34480864.        //!< conversion factor for atomic weight in units to mass in Ht (protonmass/electronmass * electron_mass_in_Ht
+#define ElectronMass_Ht 18778.865            //!< electron mass in Ht
+#define ElectronMass_eV 510998.903           //!< electron mass in eV
+#define Units2Electronmass (AtomicMassUnitsToeV/ElectronMass_eV) //!< atomic mass unit in eV/ electron mass in eV = 1 822.88863
+#define Atomictime2Femtoseconds 0.024188843     //!< Atomictime in fs
+
 #define VERSIONSTRING "v1.0"
 
@@ -24,12 +33,12 @@
 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 Shading { white, lightgray, darkgray, black };  //!< color in Breadth-First-Search analysis
 
-//enum CutCyclicBond { KeepBond,	SaturateBond }; //!< Saturation scheme either atom- or bondwise 
+//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
-							 };
+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 status of the on command line given config file
@@ -43,23 +52,23 @@
 
 // various standard filenames
-#define DEFAULTCONFIG "main_pcp_linux"		//!< default filename of config file
-#define CONVEXENVELOPE "ConvexEnvelope.dat"		//!< default filename of convex envelope tecplot data file
-#define KEYSETFILE "KeySets.dat"		//!< default filename of BOSSANOVA key sets file
-#define ADJACENCYFILE "Adjacency.dat"		//!< default filename of BOSSANOVA adjacancy file
-#define TEFACTORSFILE "TE-Factors.dat"		//!< default filename of BOSSANOVA total energy factors file
-#define FORCESFILE "Forces-Factors.dat"		//!< default filename of BOSSANOVA force factors file
-#define HCORRECTIONSUFFIX "Hcorrection.dat"		//!< default filename of BOSSANOVA H correction file (unwanted saturation interaction)
-#define FITCONSTANTSUFFIX "FitConstant.dat"	 //!< suffix of default filename of BOSSANOVA fit constants file (unwanted saturation interaction)
-#define SHIELDINGSUFFIX "sigma_all.csv"								//!< default filename of BOSSANOVA shieldings file
-#define SHIELDINGPASSUFFIX "sigma_all_PAS.csv"								 //!< default filename of BOSSANOVA shieldings PAS file
-#define ORDERATSITEFILE "OrderAtSite.dat"		//!< default filename of BOSSANOVA Bond Order at each atom file
-#define ENERGYPERFRAGMENT "EnergyPerFragment"		//!< default filename of BOSSANOVA Energy contribution Per Fragment file
-#define FRAGMENTPREFIX "BondFragment"		//!< default filename prefix of BOSSANOVA fragment config and directories 
-#define STANDARDCONFIG "unknown.conf"		//!< default filename of standard config file
-#define STANDARDELEMENTSDB "elements.db"		//!< default filename of elements data base with masses, Z, VanDerWaals radii, ...
-#define STANDARDVALENCEDB "valence.db"		//!< default filename of valence number per element database
-#define STANDARDORBITALDB "orbitals.db"		//!< default filename of orbitals per element database
-#define STANDARDHBONDDISTANCEDB "Hbonddistance.db"		//!< default filename of typial bond distance to hydrogen database
-#define STANDARDHBONDANGLEDB "Hbondangle.db"		//!< default filename of typial bond angle to hydrogen database
+#define DEFAULTCONFIG "main_pcp_linux"    //!< default filename of config file
+#define CONVEXENVELOPE "ConvexEnvelope.dat"    //!< default filename of convex envelope tecplot data file
+#define KEYSETFILE "KeySets.dat"    //!< default filename of BOSSANOVA key sets file
+#define ADJACENCYFILE "Adjacency.dat"    //!< default filename of BOSSANOVA adjacancy file
+#define TEFACTORSFILE "TE-Factors.dat"    //!< default filename of BOSSANOVA total energy factors file
+#define FORCESFILE "Forces-Factors.dat"    //!< default filename of BOSSANOVA force factors file
+#define HCORRECTIONSUFFIX "Hcorrection.dat"    //!< default filename of BOSSANOVA H correction file (unwanted saturation interaction)
+#define FITCONSTANTSUFFIX "FitConstant.dat"   //!< suffix of default filename of BOSSANOVA fit constants file (unwanted saturation interaction)
+#define SHIELDINGSUFFIX "sigma_all.csv"                //!< default filename of BOSSANOVA shieldings file
+#define SHIELDINGPASSUFFIX "sigma_all_PAS.csv"                 //!< default filename of BOSSANOVA shieldings PAS file
+#define ORDERATSITEFILE "OrderAtSite.dat"    //!< default filename of BOSSANOVA Bond Order at each atom file
+#define ENERGYPERFRAGMENT "EnergyPerFragment"    //!< default filename of BOSSANOVA Energy contribution Per Fragment file
+#define FRAGMENTPREFIX "BondFragment"    //!< default filename prefix of BOSSANOVA fragment config and directories 
+#define STANDARDCONFIG "unknown.conf"    //!< default filename of standard config file
+#define STANDARDELEMENTSDB "elements.db"    //!< default filename of elements data base with masses, Z, VanDerWaals radii, ...
+#define STANDARDVALENCEDB "valence.db"    //!< default filename of valence number per element database
+#define STANDARDORBITALDB "orbitals.db"    //!< default filename of orbitals per element database
+#define STANDARDHBONDDISTANCEDB "Hbonddistance.db"    //!< default filename of typial bond distance to hydrogen database
+#define STANDARDHBONDANGLEDB "Hbondangle.db"    //!< default filename of typial bond angle to hydrogen database
 
 // some values
@@ -68,5 +77,5 @@
 
 
-#define UPDATECOUNT 10	//!< update ten sites per BOSSANOVA interval
+#define UPDATECOUNT 10  //!< update ten sites per BOSSANOVA interval
 
 #endif /*DEFS_HPP_*/
Index: src/element.cpp
===================================================================
--- src/element.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/element.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -12,9 +12,9 @@
  */
 element::element() {
-	Z = -1;
-	No = -1;
-	previous = NULL;
-	next = NULL;
-	sort = NULL;
+  Z = -1;
+  No = -1;
+  previous = NULL;
+  next = NULL;
+  sort = NULL;
 };
 
@@ -28,23 +28,23 @@
 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;
+  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 No  cardinal number of element
  * \param NoOfAtoms total number of atom of this element type
  */
 bool element::Checkout(ofstream *out, const int Number, const int NoOfAtoms) const
 { 
-	if (out != NULL) {
-		*out << "Ion_Type" << Number << "\t" << NoOfAtoms << "\t" << Z << "\t1.0\t3\t3\t" << fixed << setprecision(11) << showpoint << mass << "\t" << name << "\t" << symbol <<endl;
-		return true;
-	} else
-		return false;
+  if (out != NULL) {
+    *out << "Ion_Type" << Number << "\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: src/ellipsoid.cpp
===================================================================
--- src/ellipsoid.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/ellipsoid.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -2,6 +2,6 @@
  * ellipsoid.cpp
  *
- *	Created on: Jan 20, 2009
- *			Author: heber
+ *  Created on: Jan 20, 2009
+ *      Author: heber
  */
 
@@ -17,65 +17,65 @@
 double SquaredDistanceToEllipsoid(Vector &x, Vector &EllipsoidCenter, double *EllipsoidLength, double *EllipsoidAngle)
 {
-	Vector helper, RefPoint;
-	double distance = -1.;
-	double Matrix[NDIM*NDIM];
-	double InverseLength[3];
-	double psi,theta,phi; // euler angles in ZX'Z'' convention
-
-	//cout << Verbose(3) << "Begin of SquaredDistanceToEllipsoid" << endl;
-
-	for(int i=0;i<3;i++)
-		InverseLength[i] = 1./EllipsoidLength[i];
-
-	// 1. translate coordinate system so that ellipsoid center is in origin
-	helper.CopyVector(&x);
-	helper.SubtractVector(&EllipsoidCenter);
-	RefPoint.CopyVector(&helper);
-	//cout << Verbose(4) << "Translated given point is at " << RefPoint << "." << endl;
-
-	// 2. transform coordinate system by inverse of rotation matrix and of diagonal matrix
-	psi = EllipsoidAngle[0];
-	theta = EllipsoidAngle[1];
-	phi = EllipsoidAngle[2];
-	Matrix[0] = cos(psi)*cos(phi) - sin(psi)*cos(theta)*sin(phi);
-	Matrix[1] = -cos(psi)*sin(phi) - sin(psi)*cos(theta)*cos(phi);
-	Matrix[2] = sin(psi)*sin(theta);
-	Matrix[3] = sin(psi)*cos(phi) + cos(psi)*cos(theta)*sin(phi);
-	Matrix[4] = cos(psi)*cos(theta)*cos(phi) - sin(psi)*sin(phi);
-	Matrix[5] = -cos(psi)*sin(theta);
-	Matrix[6] = sin(theta)*sin(phi);
-	Matrix[7] = sin(theta)*cos(phi);
-	Matrix[8] = cos(theta);
-	helper.MatrixMultiplication(Matrix);
-	helper.Scale(InverseLength);
-	//cout << Verbose(4) << "Transformed RefPoint is at " << helper << "." << endl;
-
-	// 3. construct intersection point with unit sphere and ray between origin and x
-	helper.Normalize(); // is simply normalizes vector in distance direction
-	//cout << Verbose(4) << "Transformed intersection is at " << helper << "." << endl;
-
-	// 4. transform back the constructed intersection point
-	psi = -EllipsoidAngle[0];
-	theta = -EllipsoidAngle[1];
-	phi = -EllipsoidAngle[2];
-	helper.Scale(EllipsoidLength);
-	Matrix[0] = cos(psi)*cos(phi) - sin(psi)*cos(theta)*sin(phi);
-	Matrix[1] = -cos(psi)*sin(phi) - sin(psi)*cos(theta)*cos(phi);
-	Matrix[2] = sin(psi)*sin(theta);
-	Matrix[3] = sin(psi)*cos(phi) + cos(psi)*cos(theta)*sin(phi);
-	Matrix[4] = cos(psi)*cos(theta)*cos(phi) - sin(psi)*sin(phi);
-	Matrix[5] = -cos(psi)*sin(theta);
-	Matrix[6] = sin(theta)*sin(phi);
-	Matrix[7] = sin(theta)*cos(phi);
-	Matrix[8] = cos(theta);
-	helper.MatrixMultiplication(Matrix);
-	//cout << Verbose(4) << "Intersection is at " << helper << "." << endl;
-
-	// 5. determine distance between backtransformed point and x
-	distance = RefPoint.DistanceSquared(&helper);
-	//cout << Verbose(4) << "Squared distance between intersection and RefPoint is " << distance << "." << endl;
-
-	return distance;
-	//cout << Verbose(3) << "End of SquaredDistanceToEllipsoid" << endl;
+  Vector helper, RefPoint;
+  double distance = -1.;
+  double Matrix[NDIM*NDIM];
+  double InverseLength[3];
+  double psi,theta,phi; // euler angles in ZX'Z'' convention
+
+  //cout << Verbose(3) << "Begin of SquaredDistanceToEllipsoid" << endl;
+
+  for(int i=0;i<3;i++)
+    InverseLength[i] = 1./EllipsoidLength[i];
+
+  // 1. translate coordinate system so that ellipsoid center is in origin
+  helper.CopyVector(&x);
+  helper.SubtractVector(&EllipsoidCenter);
+  RefPoint.CopyVector(&helper);
+  //cout << Verbose(4) << "Translated given point is at " << RefPoint << "." << endl;
+
+  // 2. transform coordinate system by inverse of rotation matrix and of diagonal matrix
+  psi = EllipsoidAngle[0];
+  theta = EllipsoidAngle[1];
+  phi = EllipsoidAngle[2];
+  Matrix[0] = cos(psi)*cos(phi) - sin(psi)*cos(theta)*sin(phi);
+  Matrix[1] = -cos(psi)*sin(phi) - sin(psi)*cos(theta)*cos(phi);
+  Matrix[2] = sin(psi)*sin(theta);
+  Matrix[3] = sin(psi)*cos(phi) + cos(psi)*cos(theta)*sin(phi);
+  Matrix[4] = cos(psi)*cos(theta)*cos(phi) - sin(psi)*sin(phi);
+  Matrix[5] = -cos(psi)*sin(theta);
+  Matrix[6] = sin(theta)*sin(phi);
+  Matrix[7] = sin(theta)*cos(phi);
+  Matrix[8] = cos(theta);
+  helper.MatrixMultiplication(Matrix);
+  helper.Scale(InverseLength);
+  //cout << Verbose(4) << "Transformed RefPoint is at " << helper << "." << endl;
+
+  // 3. construct intersection point with unit sphere and ray between origin and x
+  helper.Normalize(); // is simply normalizes vector in distance direction
+  //cout << Verbose(4) << "Transformed intersection is at " << helper << "." << endl;
+
+  // 4. transform back the constructed intersection point
+  psi = -EllipsoidAngle[0];
+  theta = -EllipsoidAngle[1];
+  phi = -EllipsoidAngle[2];
+  helper.Scale(EllipsoidLength);
+  Matrix[0] = cos(psi)*cos(phi) - sin(psi)*cos(theta)*sin(phi);
+  Matrix[1] = -cos(psi)*sin(phi) - sin(psi)*cos(theta)*cos(phi);
+  Matrix[2] = sin(psi)*sin(theta);
+  Matrix[3] = sin(psi)*cos(phi) + cos(psi)*cos(theta)*sin(phi);
+  Matrix[4] = cos(psi)*cos(theta)*cos(phi) - sin(psi)*sin(phi);
+  Matrix[5] = -cos(psi)*sin(theta);
+  Matrix[6] = sin(theta)*sin(phi);
+  Matrix[7] = sin(theta)*cos(phi);
+  Matrix[8] = cos(theta);
+  helper.MatrixMultiplication(Matrix);
+  //cout << Verbose(4) << "Intersection is at " << helper << "." << endl;
+
+  // 5. determine distance between backtransformed point and x
+  distance = RefPoint.DistanceSquared(&helper);
+  //cout << Verbose(4) << "Squared distance between intersection and RefPoint is " << distance << "." << endl;
+
+  return distance;
+  //cout << Verbose(3) << "End of SquaredDistanceToEllipsoid" << endl;
 };
 
@@ -83,6 +83,6 @@
  */
 struct EllipsoidMinimisation {
-	int N;			//!< dimension of vector set
-	Vector *x;	//!< array of vectors
+  int N;      //!< dimension of vector set
+  Vector *x;  //!< array of vectors
 };
 
@@ -94,31 +94,31 @@
 double SumSquaredDistance (const gsl_vector * x, void * params)
 {
-	Vector *set= ((struct EllipsoidMinimisation *)params)->x;
-	int N = ((struct EllipsoidMinimisation *)params)->N;
-	double SumDistance = 0.;
-	double distance;
-	Vector Center;
-	double EllipsoidLength[3], EllipsoidAngle[3];
-
-	// put parameters into suitable ellipsoid form
-	for (int i=0;i<3;i++) {
-		Center.x[i] = gsl_vector_get(x, i+0);
-		EllipsoidLength[i] = gsl_vector_get(x, i+3);
-		EllipsoidAngle[i] = gsl_vector_get(x, i+6);
-	}
-
-	// go through all points and sum distance
-	for (int i=0;i<N;i++) {
-		distance = SquaredDistanceToEllipsoid(set[i], Center, EllipsoidLength, EllipsoidAngle);
-		if (!isnan(distance)) {
-			SumDistance += distance;
-		} else {
-			SumDistance = GSL_NAN;
-			break;
-		}
-	}
-
-	//cout << "Current summed distance is " << SumDistance << "." << endl;
-	return SumDistance;
+  Vector *set= ((struct EllipsoidMinimisation *)params)->x;
+  int N = ((struct EllipsoidMinimisation *)params)->N;
+  double SumDistance = 0.;
+  double distance;
+  Vector Center;
+  double EllipsoidLength[3], EllipsoidAngle[3];
+
+  // put parameters into suitable ellipsoid form
+  for (int i=0;i<3;i++) {
+    Center.x[i] = gsl_vector_get(x, i+0);
+    EllipsoidLength[i] = gsl_vector_get(x, i+3);
+    EllipsoidAngle[i] = gsl_vector_get(x, i+6);
+  }
+
+  // go through all points and sum distance
+  for (int i=0;i<N;i++) {
+    distance = SquaredDistanceToEllipsoid(set[i], Center, EllipsoidLength, EllipsoidAngle);
+    if (!isnan(distance)) {
+      SumDistance += distance;
+    } else {
+      SumDistance = GSL_NAN;
+      break;
+    }
+  }
+
+  //cout << "Current summed distance is " << SumDistance << "." << endl;
+  return SumDistance;
 };
 
@@ -132,76 +132,76 @@
 bool FitPointSetToEllipsoid(ofstream *out, Vector *set, int N, Vector *EllipsoidCenter, double *EllipsoidLength, double *EllipsoidAngle)
 {
-	int status = GSL_SUCCESS;
-	*out << Verbose(2) << "Begin of FitPointSetToEllipsoid " << endl;
-	if (N >= 3) { // check that enough points are given (9 d.o.f.)
-		struct EllipsoidMinimisation 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;
-		double size;
-
-		/* Starting point */
-		x = gsl_vector_alloc (9);
-		for (int i=0;i<3;i++) {
-			gsl_vector_set (x, i+0, EllipsoidCenter->x[i]);
-			gsl_vector_set (x, i+3, EllipsoidLength[i]);
-			gsl_vector_set (x, i+6, EllipsoidAngle[i]);
-		}
-		par.x = set;
-		par.N = N;
-
-		/* Set initial step sizes */
-		ss = gsl_vector_alloc (9);
-		for (int i=0;i<3;i++) {
-			gsl_vector_set (ss, i+0, 0.1);
-			gsl_vector_set (ss, i+3, 1.0);
-			gsl_vector_set (ss, i+6, M_PI/20.);
-		}
-
-		/* Initialize method and iterate */
-		minex_func.n = 9;
-		minex_func.f = &SumSquaredDistance;
-		minex_func.params = (void *)&par;
-
-		s = gsl_multimin_fminimizer_alloc (T, 9);
-		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) {
-				for (int i=0;i<3;i++) {
-					EllipsoidCenter->x[i] = gsl_vector_get (s->x,i+0);
-					EllipsoidLength[i] = gsl_vector_get (s->x, i+3);
-					EllipsoidAngle[i] = gsl_vector_get (s->x, i+6);
-				}
-				*out << setprecision(3) << Verbose(4) << "Converged fit at: " << *EllipsoidCenter << ", lengths " << EllipsoidLength[0] << ", " << EllipsoidLength[1] << ", " << EllipsoidLength[2] << ", angles " << EllipsoidAngle[0] << ", " << EllipsoidAngle[1] << ", " << EllipsoidAngle[2] << " with summed distance " << s->fval << "." << endl;
-			}
-
-		} while (status == GSL_CONTINUE && iter < 1000);
-
-		gsl_vector_free(x);
-		gsl_vector_free(ss);
-		gsl_multimin_fminimizer_free (s);
-
-	} else {
-		*out << Verbose(3) << "Not enough points provided for fit to ellipsoid." << endl;
-		return false;
-	}
-	*out << Verbose(2) << "End of FitPointSetToEllipsoid" << endl;
-	if (status == GSL_SUCCESS)
-		return true;
-	else
-		return false;
+  int status = GSL_SUCCESS;
+  *out << Verbose(2) << "Begin of FitPointSetToEllipsoid " << endl;
+  if (N >= 3) { // check that enough points are given (9 d.o.f.)
+    struct EllipsoidMinimisation 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;
+    double size;
+
+    /* Starting point */
+    x = gsl_vector_alloc (9);
+    for (int i=0;i<3;i++) {
+      gsl_vector_set (x, i+0, EllipsoidCenter->x[i]);
+      gsl_vector_set (x, i+3, EllipsoidLength[i]);
+      gsl_vector_set (x, i+6, EllipsoidAngle[i]);
+    }
+    par.x = set;
+    par.N = N;
+
+    /* Set initial step sizes */
+    ss = gsl_vector_alloc (9);
+    for (int i=0;i<3;i++) {
+      gsl_vector_set (ss, i+0, 0.1);
+      gsl_vector_set (ss, i+3, 1.0);
+      gsl_vector_set (ss, i+6, M_PI/20.);
+    }
+
+    /* Initialize method and iterate */
+    minex_func.n = 9;
+    minex_func.f = &SumSquaredDistance;
+    minex_func.params = (void *)&par;
+
+    s = gsl_multimin_fminimizer_alloc (T, 9);
+    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) {
+        for (int i=0;i<3;i++) {
+          EllipsoidCenter->x[i] = gsl_vector_get (s->x,i+0);
+          EllipsoidLength[i] = gsl_vector_get (s->x, i+3);
+          EllipsoidAngle[i] = gsl_vector_get (s->x, i+6);
+        }
+        *out << setprecision(3) << Verbose(4) << "Converged fit at: " << *EllipsoidCenter << ", lengths " << EllipsoidLength[0] << ", " << EllipsoidLength[1] << ", " << EllipsoidLength[2] << ", angles " << EllipsoidAngle[0] << ", " << EllipsoidAngle[1] << ", " << EllipsoidAngle[2] << " with summed distance " << s->fval << "." << endl;
+      }
+
+    } while (status == GSL_CONTINUE && iter < 1000);
+
+    gsl_vector_free(x);
+    gsl_vector_free(ss);
+    gsl_multimin_fminimizer_free (s);
+
+  } else {
+    *out << Verbose(3) << "Not enough points provided for fit to ellipsoid." << endl;
+    return false;
+  }
+  *out << Verbose(2) << "End of FitPointSetToEllipsoid" << endl;
+  if (status == GSL_SUCCESS)
+    return true;
+  else
+    return false;
 };
 
@@ -217,96 +217,96 @@
   size_t PointsLeft = 0;
   size_t PointsPicked = 0;
-	int Nlower[NDIM], Nupper[NDIM];
-	set<int> PickedAtomNrs;	 // ordered list of picked atoms
-	set<int>::iterator current;
-	int index;
-	atom *Candidate = NULL;
-	LinkedAtoms *List = NULL;
-	*out << Verbose(2) << "Begin of PickRandomPointSet" << endl;
-
-	// allocate array
-	if (x == NULL) {
-		x = new Vector[PointsToPick];
-	} else {
-		*out << "WARNING: Given pointer to vector array seems already allocated." << endl;
-	}
-
-	do {
-		for(int i=0;i<NDIM;i++) // pick three random indices
-			LC->n[i] = (rand() % LC->N[i]);
-		*out << Verbose(2) << "INFO: Center cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " ... ";
-		// get random cell
-		List = LC->GetCurrentCell();
-		if (List == NULL) {	// set index to it
-			continue;
-		}
-		*out << "with No. " << LC->index << "." << endl;
-
-		*out << Verbose(2) << "LC Intervals:";
-		for (int i=0;i<NDIM;i++) {
-			Nlower[i] = ((LC->n[i]-1) >= 0) ? LC->n[i]-1 : 0;
-			Nupper[i] = ((LC->n[i]+1) < LC->N[i]) ? LC->n[i]+1 : LC->N[i]-1;
-			*out << " [" << Nlower[i] << "," << Nupper[i] << "] ";
-		}
-		*out << endl;
-
-		// count whether there are sufficient atoms in this cell+neighbors
-		PointsLeft=0;
-		for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
-			for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
-				for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-					List = LC->GetCurrentCell();
-					PointsLeft += List->size();
-				}
-		*out << Verbose(2) << "There are " << PointsLeft << " atoms in this neighbourhood." << endl;
-		if (PointsLeft < PointsToPick) {	// ensure that we can pick enough points in its neighbourhood at all.
-			continue;
-		}
-
-		// pre-pick a fixed number of atoms
-		PickedAtomNrs.clear();
-		do {
-			index = (rand() % PointsLeft);
-			current = PickedAtomNrs.find(index);	// not present?
-			if (current == PickedAtomNrs.end()) {
-				//*out << Verbose(2) << "Picking atom nr. " << index << "." << endl;
-				PickedAtomNrs.insert(index);
-			}
-		} while (PickedAtomNrs.size() < PointsToPick);
-
-		index = 0; // now go through all and pick those whose from PickedAtomsNr
-		PointsPicked=0;
-		current = PickedAtomNrs.begin();
-		for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
-			for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
-				for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
-					List = LC->GetCurrentCell();
-//					*out << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << " containing " << List->size() << " points." << endl;
-					if (List != NULL) {
-//						if (List->begin() != List->end())
-//							*out << Verbose(2) << "Going through candidates ... " << endl;
-//						else
-//							*out << Verbose(2) << "Cell is empty ... " << endl;
-						for (LinkedAtoms::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
-							if ((current != PickedAtomNrs.end()) && (*current == index)) {
-								Candidate = (*Runner);
-								*out << Verbose(2) << "Current picked node is " << **Runner << " with index " << index << "." << endl;
-								x[PointsPicked++].CopyVector(&(Candidate->x));		// we have one more atom picked
-								current++;		// next pre-picked atom
-							}
-							index++;	// next atom nr.
-						}
-//					} else {
-//						*out << Verbose(2) << "List for this index not allocated!" << endl;
-					}
-				}
-		*out << Verbose(2) << "The following points were picked: " << endl;
-		for (size_t i=0;i<PointsPicked;i++)
-			*out << Verbose(2) << x[i] << endl;
-		if (PointsPicked == PointsToPick)	// break out of loop if we have all
-			break;
-	} while(1);
-
-	*out << Verbose(2) << "End of PickRandomPointSet" << endl;
+  int Nlower[NDIM], Nupper[NDIM];
+  set<int> PickedAtomNrs;   // ordered list of picked atoms
+  set<int>::iterator current;
+  int index;
+  atom *Candidate = NULL;
+  LinkedAtoms *List = NULL;
+  *out << Verbose(2) << "Begin of PickRandomPointSet" << endl;
+
+  // allocate array
+  if (x == NULL) {
+    x = new Vector[PointsToPick];
+  } else {
+    *out << "WARNING: Given pointer to vector array seems already allocated." << endl;
+  }
+
+  do {
+    for(int i=0;i<NDIM;i++) // pick three random indices
+      LC->n[i] = (rand() % LC->N[i]);
+    *out << Verbose(2) << "INFO: Center cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " ... ";
+    // get random cell
+    List = LC->GetCurrentCell();
+    if (List == NULL) {  // set index to it
+      continue;
+    }
+    *out << "with No. " << LC->index << "." << endl;
+
+    *out << Verbose(2) << "LC Intervals:";
+    for (int i=0;i<NDIM;i++) {
+      Nlower[i] = ((LC->n[i]-1) >= 0) ? LC->n[i]-1 : 0;
+      Nupper[i] = ((LC->n[i]+1) < LC->N[i]) ? LC->n[i]+1 : LC->N[i]-1;
+      *out << " [" << Nlower[i] << "," << Nupper[i] << "] ";
+    }
+    *out << endl;
+
+    // count whether there are sufficient atoms in this cell+neighbors
+    PointsLeft=0;
+    for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
+      for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
+        for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
+          List = LC->GetCurrentCell();
+          PointsLeft += List->size();
+        }
+    *out << Verbose(2) << "There are " << PointsLeft << " atoms in this neighbourhood." << endl;
+    if (PointsLeft < PointsToPick) {  // ensure that we can pick enough points in its neighbourhood at all.
+      continue;
+    }
+
+    // pre-pick a fixed number of atoms
+    PickedAtomNrs.clear();
+    do {
+      index = (rand() % PointsLeft);
+      current = PickedAtomNrs.find(index);  // not present?
+      if (current == PickedAtomNrs.end()) {
+        //*out << Verbose(2) << "Picking atom nr. " << index << "." << endl;
+        PickedAtomNrs.insert(index);
+      }
+    } while (PickedAtomNrs.size() < PointsToPick);
+
+    index = 0; // now go through all and pick those whose from PickedAtomsNr
+    PointsPicked=0;
+    current = PickedAtomNrs.begin();
+    for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
+      for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
+        for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
+          List = LC->GetCurrentCell();
+//          *out << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << " containing " << List->size() << " points." << endl;
+          if (List != NULL) {
+//            if (List->begin() != List->end())
+//              *out << Verbose(2) << "Going through candidates ... " << endl;
+//            else
+//              *out << Verbose(2) << "Cell is empty ... " << endl;
+            for (LinkedAtoms::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+              if ((current != PickedAtomNrs.end()) && (*current == index)) {
+                Candidate = (*Runner);
+                *out << Verbose(2) << "Current picked node is " << **Runner << " with index " << index << "." << endl;
+                x[PointsPicked++].CopyVector(&(Candidate->x));    // we have one more atom picked
+                current++;    // next pre-picked atom
+              }
+              index++;  // next atom nr.
+            }
+//          } else {
+//            *out << Verbose(2) << "List for this index not allocated!" << endl;
+          }
+        }
+    *out << Verbose(2) << "The following points were picked: " << endl;
+    for (size_t i=0;i<PointsPicked;i++)
+      *out << Verbose(2) << x[i] << endl;
+    if (PointsPicked == PointsToPick)  // break out of loop if we have all
+      break;
+  } while(1);
+
+  *out << Verbose(2) << "End of PickRandomPointSet" << endl;
 };
 
@@ -321,34 +321,34 @@
   size_t PointsLeft = (size_t) T->PointsOnBoundaryCount;
   size_t PointsPicked = 0;
-	double value, threshold;
-	PointMap *List = &T->PointsOnBoundary;
-	*out << Verbose(2) << "Begin of PickRandomPointSet" << endl;
-
-	// allocate array
-	if (x == NULL) {
-		x = new Vector[PointsToPick];
-	} else {
-		*out << "WARNING: Given pointer to vector array seems already allocated." << endl;
-	}
-
-	if (List != NULL)
-		for (PointMap::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
-			threshold = 1. - (double)(PointsToPick - PointsPicked)/(double)PointsLeft;
-			value = (double)rand()/(double)RAND_MAX;
-			//*out << Verbose(3) << "Current node is " << *Runner->second->node << " with " << value << " ... " << threshold << ": ";
-			if (value > threshold) {
-				x[PointsPicked].CopyVector(&(Runner->second->node->x));
-				PointsPicked++;
-				//*out << "IN." << endl;
-			} else {
-				//*out << "OUT." << endl;
-			}
-			PointsLeft--;
-		}
-	*out << Verbose(2) << "The following points were picked: " << endl;
-	for (size_t i=0;i<PointsPicked;i++)
-		*out << Verbose(3) << x[i] << endl;
-
-	*out << Verbose(2) << "End of PickRandomPointSet" << endl;
+  double value, threshold;
+  PointMap *List = &T->PointsOnBoundary;
+  *out << Verbose(2) << "Begin of PickRandomPointSet" << endl;
+
+  // allocate array
+  if (x == NULL) {
+    x = new Vector[PointsToPick];
+  } else {
+    *out << "WARNING: Given pointer to vector array seems already allocated." << endl;
+  }
+
+  if (List != NULL)
+    for (PointMap::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
+      threshold = 1. - (double)(PointsToPick - PointsPicked)/(double)PointsLeft;
+      value = (double)rand()/(double)RAND_MAX;
+      //*out << Verbose(3) << "Current node is " << *Runner->second->node << " with " << value << " ... " << threshold << ": ";
+      if (value > threshold) {
+        x[PointsPicked].CopyVector(&(Runner->second->node->x));
+        PointsPicked++;
+        //*out << "IN." << endl;
+      } else {
+        //*out << "OUT." << endl;
+      }
+      PointsLeft--;
+    }
+  *out << Verbose(2) << "The following points were picked: " << endl;
+  for (size_t i=0;i<PointsPicked;i++)
+    *out << Verbose(3) << x[i] << endl;
+
+  *out << Verbose(2) << "End of PickRandomPointSet" << endl;
 };
 
@@ -363,71 +363,71 @@
 void FindDistributionOfEllipsoids(ofstream *out, class Tesselation *T, class LinkedCell *LCList, int N, int number, const char *filename)
 {
-	ofstream output;
-	Vector *x = NULL;
-	Vector Center;
-	Vector EllipsoidCenter;
-	double EllipsoidLength[3];
-	double EllipsoidAngle[3];
-	double distance, MaxDistance, MinDistance;
-	*out << Verbose(0) << "Begin of FindDistributionOfEllipsoids" << endl;
-
-	// construct center of gravity of boundary point set for initial ellipsoid center
-	Center.Zero();
-	for (PointMap::iterator Runner = T->PointsOnBoundary.begin(); Runner != T->PointsOnBoundary.end(); Runner++)
-		Center.AddVector(&Runner->second->node->x);
-	Center.Scale(1./T->PointsOnBoundaryCount);
-	*out << Verbose(1) << "Center is at " << Center << "." << endl;
-
-	// Output header
-	output.open(filename, ios::trunc);
-	output << "# Nr.\tCenterX\tCenterY\tCenterZ\ta\tb\tc\tpsi\ttheta\tphi" << endl;
-
-	// loop over desired number of parameter sets
-	for (;number >0;number--) {
-		*out << Verbose(1) << "Determining data set " << number << " ... " << endl;
-		// pick the point set
-		x = NULL;
-		//PickRandomPointSet(out, T, LCList, x, N);
-		PickRandomNeighbouredPointSet(out, T, LCList, x, N);
-
-		// calculate some sensible starting values for parameter fit
-		MaxDistance = 0.;
-		MinDistance = x[0].ScalarProduct(&x[0]);
-		for (int i=0;i<N;i++) {
-			distance = x[i].ScalarProduct(&x[i]);
-			if (distance > MaxDistance)
-				MaxDistance = distance;
-			if (distance < MinDistance)
-				MinDistance = distance;
-		}
-		//*out << Verbose(2) << "MinDistance " << MinDistance << ", MaxDistance " << MaxDistance << "." << endl;
-		EllipsoidCenter.CopyVector(&Center);	// use Center of Gravity as initial center of ellipsoid
-		for (int i=0;i<3;i++)
-			EllipsoidAngle[i] = 0.;
-		EllipsoidLength[0] = sqrt(MaxDistance);
-		EllipsoidLength[1] = sqrt((MaxDistance+MinDistance)/2.);
-		EllipsoidLength[2] = sqrt(MinDistance);
-
-		// fit the parameters
-		if (FitPointSetToEllipsoid(out, x, N, &EllipsoidCenter, &EllipsoidLength[0], &EllipsoidAngle[0])) {
-			*out << Verbose(1) << "Picking succeeded!" << endl;
-			// output obtained parameter set
-			output << number << "\t";
-			for (int i=0;i<3;i++)
-				output << setprecision(9) << EllipsoidCenter.x[i] << "\t";
-			for (int i=0;i<3;i++)
-				output << setprecision(9) << EllipsoidLength[i] << "\t";
-			for (int i=0;i<3;i++)
-				output << setprecision(9) << EllipsoidAngle[i] << "\t";
-			output << endl;
-		} else { // increase N to pick one more
-			*out << Verbose(1) << "Picking failed!" << endl;
-			number++;
-		}
-		delete[](x);	// free allocated memory for point set
-	}
-	// close output and finish
-	output.close();
-
-	*out << Verbose(0) << "End of FindDistributionOfEllipsoids" << endl;
-};
+  ofstream output;
+  Vector *x = NULL;
+  Vector Center;
+  Vector EllipsoidCenter;
+  double EllipsoidLength[3];
+  double EllipsoidAngle[3];
+  double distance, MaxDistance, MinDistance;
+  *out << Verbose(0) << "Begin of FindDistributionOfEllipsoids" << endl;
+
+  // construct center of gravity of boundary point set for initial ellipsoid center
+  Center.Zero();
+  for (PointMap::iterator Runner = T->PointsOnBoundary.begin(); Runner != T->PointsOnBoundary.end(); Runner++)
+    Center.AddVector(&Runner->second->node->x);
+  Center.Scale(1./T->PointsOnBoundaryCount);
+  *out << Verbose(1) << "Center is at " << Center << "." << endl;
+
+  // Output header
+  output.open(filename, ios::trunc);
+  output << "# Nr.\tCenterX\tCenterY\tCenterZ\ta\tb\tc\tpsi\ttheta\tphi" << endl;
+
+  // loop over desired number of parameter sets
+  for (;number >0;number--) {
+    *out << Verbose(1) << "Determining data set " << number << " ... " << endl;
+    // pick the point set
+    x = NULL;
+    //PickRandomPointSet(out, T, LCList, x, N);
+    PickRandomNeighbouredPointSet(out, T, LCList, x, N);
+
+    // calculate some sensible starting values for parameter fit
+    MaxDistance = 0.;
+    MinDistance = x[0].ScalarProduct(&x[0]);
+    for (int i=0;i<N;i++) {
+      distance = x[i].ScalarProduct(&x[i]);
+      if (distance > MaxDistance)
+        MaxDistance = distance;
+      if (distance < MinDistance)
+        MinDistance = distance;
+    }
+    //*out << Verbose(2) << "MinDistance " << MinDistance << ", MaxDistance " << MaxDistance << "." << endl;
+    EllipsoidCenter.CopyVector(&Center);  // use Center of Gravity as initial center of ellipsoid
+    for (int i=0;i<3;i++)
+      EllipsoidAngle[i] = 0.;
+    EllipsoidLength[0] = sqrt(MaxDistance);
+    EllipsoidLength[1] = sqrt((MaxDistance+MinDistance)/2.);
+    EllipsoidLength[2] = sqrt(MinDistance);
+
+    // fit the parameters
+    if (FitPointSetToEllipsoid(out, x, N, &EllipsoidCenter, &EllipsoidLength[0], &EllipsoidAngle[0])) {
+      *out << Verbose(1) << "Picking succeeded!" << endl;
+      // output obtained parameter set
+      output << number << "\t";
+      for (int i=0;i<3;i++)
+        output << setprecision(9) << EllipsoidCenter.x[i] << "\t";
+      for (int i=0;i<3;i++)
+        output << setprecision(9) << EllipsoidLength[i] << "\t";
+      for (int i=0;i<3;i++)
+        output << setprecision(9) << EllipsoidAngle[i] << "\t";
+      output << endl;
+    } else { // increase N to pick one more
+      *out << Verbose(1) << "Picking failed!" << endl;
+      number++;
+    }
+    delete[](x);  // free allocated memory for point set
+  }
+  // close output and finish
+  output.close();
+
+  *out << Verbose(0) << "End of FindDistributionOfEllipsoids" << endl;
+};
Index: src/ellipsoid.hpp
===================================================================
--- src/ellipsoid.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/ellipsoid.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -2,6 +2,6 @@
  * ellipsoid.hpp
  *
- *	Created on: Jan 20, 2009
- *			Author: heber
+ *  Created on: Jan 20, 2009
+ *      Author: heber
  */
 
Index: src/graph.cpp
===================================================================
--- src/graph.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/graph.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -7,10 +7,56 @@
 using namespace std;
 
+#include "graph.hpp"
 
-#include <iostream>
-#include <list>
-#include <vector>
+/***************************************** Implementations for graph classes ********************************/
 
-/***************************************** Functions for class graph ********************************/
+/** Constructor of class Graph.
+ */
+Graph::Graph()
+{
+};
 
+/** Destructor of class Graph.
+ * Destructor does release memory for nodes and edges contained in its lists as well.
+ */
+Graph::~Graph()
+{
+};
 
+/** Constructor of class SubGraph.
+ */
+SubGraph::SubGraph()
+{
+};
+
+/** Destructor of class SubGraph.
+ * Note that destructor does not deallocate either nodes or edges! (this is done by its subgraph!)
+ */
+SubGraph::~SubGraph()
+{
+};
+
+/** Constructor of class Node.
+ */
+Node::Node()
+{
+};
+
+/** Destructor of class Node.
+ */
+Node::~Node()
+{
+};
+
+/** Constructor of class Edge.
+ */
+Edge::Edge()
+{
+};
+
+/** Destructor of class Edge.
+ */
+Edge::~Edge()
+{
+};
+
Index: src/graph.hpp
===================================================================
--- src/graph.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
+++ src/graph.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -0,0 +1,68 @@
+/** \file graph.cpp
+ * 
+ * Function definitions for the class graph.
+ * 
+ */
+
+#ifndef GRAPH_HPP_
+#define GRAPH_HPP_
+
+// include config.h
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+// STL headers
+#include <map>
+#include <multimap>
+
+#include "molecules.hpp"
+
+class Graph;
+class SubGraph;
+class Node;
+class Edge;
+
+/***************************************** Various graph-related STL defines ********************************/
+
+#define NodeMap pair < int, class Node* >
+#define EdgeMap multimap < class Node*, class Edge* >
+
+/***************************************** Definition for classes ********************************/
+
+/** Graph class containing the graphs behind molecules.
+ */
+class Graph
+{
+	NodeMap ListOfNodes;		//!< tree-list of all nodes in this graph
+	EdgeMap ListOfEdges;		//!< tree-multi-list of all nodes, referenced to node id
+};
+
+/** Class describing subgraphs of the Class \a Graph.
+ * SubGraph has its own node and edge lists, however also a pointer to its father graph
+ * and hence access to its list as well. 
+ */
+class SubGraph : class Graph
+{
+	class Graph *FatherGraph;		//!< Graph whose subgraph we are
+};
+
+/** Class containing the nodes of a graph.
+ */
+class Node
+{
+	int	id;				//!< individual id of the node
+	char *Name;		//!< Name of the node for pretty printing
+};
+
+/** Class containing egdes in a Graph strructure.
+ */
+class Edge
+{
+	class Node *leftnode;		//!< pointer to first node
+	class Node *atomnode;		//!< pointer to second node
+};
+
+
+
+#endif /*GRAPH_HPP_*/
Index: src/helpers.cpp
===================================================================
--- src/helpers.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/helpers.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -15,10 +15,10 @@
 double ask_value(const char *text)
 {
-	double test = 0.1439851348959832147598734598273456723948652983045928346598365;
-	do {
-		cout << Verbose(0) << text;
-		cin >> test;
-	} while (test == 0.1439851348959832147598734598273456723948652983045928346598365);
-	return test;
+  double test = 0.1439851348959832147598734598273456723948652983045928346598365;
+  do {
+    cout << Verbose(0) << text;
+    cin >> test;
+  } while (test == 0.1439851348959832147598734598273456723948652983045928346598365);
+  return test;
 };
 
@@ -29,8 +29,8 @@
 #ifdef HAVE_DEBUG
 void debug_in(const char *output, const char *file, const int line) {
-	if (output) fprintf(stderr,"DEBUG: in %s at line %i: %s\n", file, line, output);
+  if (output) fprintf(stderr,"DEBUG: in %s at line %i: %s\n", file, line, output);
 }
 #else
-void debug_in(const char *output, const char *file, const int line) {}	// print nothing
+void debug_in(const char *output, const char *file, const int line) {}  // print nothing
 #endif
 
@@ -42,9 +42,9 @@
 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);
+  void *buffer = NULL;
+  buffer = (void *)malloc(size); // alloc
+  if (buffer == NULL)
+    cout << Verbose(0) << "Malloc failed - pointer is NULL: " << output << endl;
+  return(buffer);
 };
 
@@ -56,9 +56,9 @@
 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);
+  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);
 };
 
@@ -71,13 +71,13 @@
 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 *)malloc(size); // malloc
-	else
-		buffer = (void *)realloc(OldPointer, size); // realloc
-	if (buffer == NULL)
-		cout << Verbose(0) << "ReAlloc failed - new is NULL: " << output << endl;
-	return(buffer);
+  void *buffer = NULL;
+  if (OldPointer == NULL)
+    //cout << Verbose(0) << "ReAlloc impossible - old is NULL: " << output << endl;
+    buffer = (void *)malloc(size); // malloc
+  else
+    buffer = (void *)realloc(OldPointer, size); // realloc
+  if (buffer == NULL)
+    cout << Verbose(0) << "ReAlloc failed - new is NULL: " << output << endl;
+  return(buffer);
 };
 
@@ -88,10 +88,10 @@
 void Free(void ** buffer, const char* output)
 {
-	if (*buffer == NULL) {
-		//cout << Verbose(5) << "Free not necesary: " << output << endl;
-	} else {
-		free(*buffer);
-		*buffer = NULL;
-	}
+  if (*buffer == NULL) {
+    //cout << Verbose(5) << "Free not necesary: " << output << endl;
+  } else {
+    free(*buffer);
+    *buffer = NULL;
+  }
 };
 
@@ -103,13 +103,13 @@
 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=size;i--;)	// reset
-		buffer[i] = i % 2 == 0 ? 'p': 'c';
-	buffer[size] = '\0'; // and set length marker on its end
-	return(buffer);
+  size_t i;
+  char *buffer;
+  buffer = (char *)malloc(sizeof(char) * (size+1)); // alloc
+  if (buffer == NULL)
+    cout << Verbose(0) << output << endl;
+  for (i=size;i--;)  // reset
+    buffer[i] = i % 2 == 0 ? 'p': 'c';
+  buffer[size] = '\0'; // and set length marker on its end
+  return(buffer);
 }
 
@@ -121,9 +121,9 @@
 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;
+  double step = (upper_bound - lower_bound);
+  while (*b >= upper_bound)
+    *b -= step;
+  while (*b < lower_bound)
+    *b += step;
 };
 
@@ -134,8 +134,8 @@
 void flip(double *x, double *y)
 {
-	double tmp;
-	tmp = *x;
-	*x = *y;
-	*y = tmp;
+  double tmp;
+  tmp = *x;
+  *x = *y;
+  *y = tmp;
 };
 
@@ -147,9 +147,9 @@
 int pot(int base, int n)
 {
-	int res = 1;
-	int j;
-	for (j=n;j--;)
-		res *= base;
-	return res;
+  int res = 1;
+  int j;
+  for (j=n;j--;)
+    res *= base;
+  return res;
 };
 
@@ -161,23 +161,23 @@
 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), "FixedDigitNumber: *returnstring");
-	// terminate	and fill string array from end backward
-	returnstring[order] = '\0';
-	number = digits;
-	for (int i=order;i--;) {
-		returnstring[i] = '0' + (char)(number % 10);
-		number = (int)floor(((double)number / 10.));
-	}
-	//cout << returnstring << endl;
-	return returnstring;
+  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), "FixedDigitNumber: *returnstring");
+  // terminate  and fill string array from end backward
+  returnstring[order] = '\0';
+  number = digits;
+  for (int i=order;i--;) {
+    returnstring[i] = '0' + (char)(number % 10);
+    number = (int)floor(((double)number / 10.));
+  }
+  //cout << returnstring << endl;
+  return returnstring;
 };
 
@@ -188,10 +188,10 @@
 bool IsValidNumber( const char *string)
 {
-	int ptr = 0;
-	if ((string[ptr] == '.') || (string[ptr] == '-')) // number may be negative or start with dot
-		ptr++;
-	if ((string[ptr] >= '0') && (string[ptr] <= '9'))
-		return true;
-	return false;
+  int ptr = 0;
+  if ((string[ptr] == '.') || (string[ptr] == '-')) // number may be negative or start with dot
+    ptr++;
+  if ((string[ptr] >= '0') && (string[ptr] <= '9'))
+    return true;
+  return false;
 };
 
Index: src/helpers.hpp
===================================================================
--- src/helpers.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/helpers.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -38,13 +38,13 @@
 
 /* Behandelt aufgetretene Fehler. error ist der Fehlertyp(enum Errors)
-	 void *SpecialData ist ein untypisierter Zeiger auf Spezielle Daten zur Fehlerbehandlung.
-	 Man koennte auch noch einen Zeiger auf eine Funktion uebergeben */
+   void *SpecialData ist ein untypisierter Zeiger auf Spezielle Daten zur Fehlerbehandlung.
+   Man koennte auch noch einen Zeiger auf eine Funktion uebergeben */
 extern void /*@exits@*/ debug(const char *output);
-	//__attribute__ ((__return__));
+  //__attribute__ ((__return__));
 #define debug(data) debug_in((data), __FILE__, __LINE__)
 
 extern void /*@exits@*/ debug_in(const char *output,
-		const char *file, const int line);
-	//__attribute__ ((__return__));
+    const char *file, const int line);
+  //__attribute__ ((__return__));
 
 double ask_value(const char *text);
@@ -73,50 +73,50 @@
 template <typename T> bool CreateFatherLookupTable(ofstream *out, T *start, T *end, T **&LookupTable, int count = 0)
 {
-	bool status = true;
-	T *Walker = NULL;
-	int AtomNo;
-
-	if (LookupTable != NULL) {
-		*out << "Pointer for Lookup table is not NULL! Aborting ..." <<endl;
-		return false;
-	}
-
-	// count them
-	if (count == 0) {
-		Walker = start;
-		while (Walker->next != end) { // create a lookup table (Atom::nr -> atom) used as a marker table lateron
-			Walker = Walker->next;
-			count = (count < Walker->GetTrueFather()->nr) ? Walker->GetTrueFather()->nr : count;
-		}
-	}
-	if (count <= 0) {
-		*out << "Count of lookup list is 0 or less." << endl;
-		return false;
-	}
-
-	// allocat and fill
-	LookupTable = (T **) Malloc(sizeof(T *)*count, "CreateFatherLookupTable - **LookupTable");
-	if (LookupTable == NULL) {
-		cerr << "LookupTable memory allocation failed!" << endl;
-		status = false;
-	} else {
-		for (int i=0;i<count;i++)
-			LookupTable[i] = NULL;
-		Walker = start;
-		while (Walker->next != end) { // create a lookup table (Atom::nr -> atom) used as a marker table lateron
-			Walker = Walker->next;
-			AtomNo = Walker->GetTrueFather()->nr;
-			if ((AtomNo >= 0) && (AtomNo < count)) {
-				//*out << "Setting LookupTable[" << AtomNo << "] to " << *Walker << endl;
-				LookupTable[AtomNo] = Walker;
-			} else {
-				*out << "Walker " << *Walker << " exceeded range of nuclear ids [0, " << count << ")." << endl;
-				status = false;
-				break;
-			}
-		}
-	}
-
-	return status;
+  bool status = true;
+  T *Walker = NULL;
+  int AtomNo;
+
+  if (LookupTable != NULL) {
+    *out << "Pointer for Lookup table is not NULL! Aborting ..." <<endl;
+    return false;
+  }
+
+  // count them
+  if (count == 0) {
+    Walker = start;
+    while (Walker->next != end) { // create a lookup table (Atom::nr -> atom) used as a marker table lateron
+      Walker = Walker->next;
+      count = (count < Walker->GetTrueFather()->nr) ? Walker->GetTrueFather()->nr : count;
+    }
+  }
+  if (count <= 0) {
+    *out << "Count of lookup list is 0 or less." << endl;
+    return false;
+  }
+
+  // allocat and fill
+  LookupTable = (T **) Malloc(sizeof(T *)*count, "CreateFatherLookupTable - **LookupTable");
+  if (LookupTable == NULL) {
+    cerr << "LookupTable memory allocation failed!" << endl;
+    status = false;
+  } else {
+    for (int i=0;i<count;i++)
+      LookupTable[i] = NULL;
+    Walker = start;
+    while (Walker->next != end) { // create a lookup table (Atom::nr -> atom) used as a marker table lateron
+      Walker = Walker->next;
+      AtomNo = Walker->GetTrueFather()->nr;
+      if ((AtomNo >= 0) && (AtomNo < count)) {
+        //*out << "Setting LookupTable[" << AtomNo << "] to " << *Walker << endl;
+        LookupTable[AtomNo] = Walker;
+      } else {
+        *out << "Walker " << *Walker << " exceeded range of nuclear ids [0, " << count << ")." << endl;
+        status = false;
+        break;
+      }
+    }
+  }
+
+  return status;
 };
 
@@ -129,10 +129,10 @@
 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;
+  X *vorher = end->previous;
+  if (vorher != NULL)
+    vorher->next = walker;
+  end->previous = walker;
+  walker->previous = vorher;
+  walker->next = end;
 };
 
@@ -143,40 +143,40 @@
 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;
+  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
+ * \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;
+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
+ * \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;
+  X *walker = start;
+  while (walker->next != end) { // go through list
+    walker = walker->next; // step onward beforehand
+    if (*walker->sort == *suche) return (walker);
+  }
+  return NULL;
 };
 
@@ -187,31 +187,31 @@
 template <typename X> void removewithoutcheck(X *walker)
 {
-	if (walker != NULL) {
-		unlink(walker);
-		delete(walker);
-		walker = NULL;
-	}
+  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
+ * \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;
+  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;
 };
 
@@ -223,15 +223,15 @@
 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;
+  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;
 };
 
@@ -242,8 +242,8 @@
 template <typename X> X *GetFirst(X *me)
 {
-	X *Binder = me;
-	while(Binder->previous != NULL)
-		Binder = Binder->previous;
-	return Binder;
+  X *Binder = me;
+  while(Binder->previous != NULL)
+    Binder = Binder->previous;
+  return Binder;
 };
 
@@ -254,8 +254,8 @@
 template <typename X> X *GetLast(X *me)
 {
-	X *Binder = me;
-	while(Binder->next != NULL)
-		Binder = Binder->next;
-	return Binder;
+  X *Binder = me;
+  while(Binder->next != NULL)
+    Binder = Binder->next;
+  return Binder;
 };
 
@@ -266,11 +266,11 @@
 template <typename X> void Free2DArray(X **ptr, int dim)
 {
-	int i;
-	if (ptr != NULL) {
-		for(i=dim;i--;)
-			if (ptr[i] != NULL)
-				free(ptr[i]);
-		free(ptr);
-	}
+  int i;
+  if (ptr != NULL) {
+    for(i=dim;i--;)
+      if (ptr[i] != NULL)
+        free(ptr[i]);
+    free(ptr);
+  }
 };
 
@@ -281,10 +281,10 @@
 class Verbose
 {
-	public:
-		Verbose(int value) : Verbosity(value) { }
-
-		ostream& print (ostream &ost) const;
-	private:
-		int Verbosity;
+  public:
+    Verbose(int value) : Verbosity(value) { }
+
+    ostream& print (ostream &ost) const;
+  private:
+    int Verbosity;
 };
 
@@ -295,10 +295,10 @@
 class Binary
 {
-	public:
-		Binary(int value) : BinaryNumber(value) { }
-
-		ostream& print (ostream &ost) const;
-	private:
-		int BinaryNumber;
+  public:
+    Binary(int value) : BinaryNumber(value) { }
+
+    ostream& print (ostream &ost) const;
+  private:
+    int BinaryNumber;
 };
 
Index: src/joiner.cpp
===================================================================
--- src/joiner.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/joiner.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -17,163 +17,230 @@
 int main(int argc, char **argv)
 {
-	periodentafel *periode = NULL; // and a period table of all elements
-	EnergyMatrix Energy;
-	EnergyMatrix Hcorrection;
-	ForceMatrix Force;
-	EnergyMatrix EnergyFragments;
-	EnergyMatrix HcorrectionFragments;
-	ForceMatrix ForceFragments;
-	ForceMatrix Shielding;
-	ForceMatrix ShieldingPAS;
-	ForceMatrix ShieldingFragments;
-	ForceMatrix ShieldingPASFragments;
-	KeySetsContainer KeySet;
-	stringstream prefix;
-	char *dir = NULL;
-	bool Hcorrected = true;
-
-	cout << "Joiner" << endl;
-	cout << "======" << endl;
-
-	// Get the command line options
-	if (argc < 3) {
-		cout << "Usage: " << argv[0] << " <inputdir> <prefix> [elementsdb]" << 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 << "[elementsdb]\tpath to elements database, needed for shieldings." << endl;
-		return 1;
-	} else {
-		dir = (char *) Malloc(sizeof(char)*(strlen(argv[2])+2), "main: *dir");
-		strcpy(dir, "/");
-		strcat(dir, argv[2]);
-	}
-	if (argc > 3) {
-		periode = new periodentafel;
-		periode->LoadPeriodentafel(argv[3]);
-	}
-
-	// Test the given directory
-	if (!TestParams(argc, argv))
-		return 1;
-
-	// +++++++++++++++++ PARSING +++++++++++++++++++++++++++++++
-
-	// ------------- Parse through all Fragment subdirs --------
-	if (!Energy.ParseFragmentMatrix(argv[1], dir, EnergySuffix, 0,0)) return 1;
-	Hcorrected = Hcorrection.ParseFragmentMatrix(argv[1], "", HCORRECTIONSUFFIX, 0,0);
-	if (!Force.ParseFragmentMatrix(argv[1], dir, ForcesSuffix, 0,0)) return 1;
-	if (periode != NULL) { // also look for PAS values
-		if (!Shielding.ParseFragmentMatrix(argv[1], dir, ShieldingSuffix, 1, 0)) return 1;
-		if (!ShieldingPAS.ParseFragmentMatrix(argv[1], dir, ShieldingPASSuffix, 1, 0)) return 1;
-	}
-
-	// ---------- Parse the TE Factors into an array -----------------
-	if (!Energy.ParseIndices()) return 1;
-	if (Hcorrected) Hcorrection.ParseIndices();
-
-	// ---------- Parse the Force indices into an array ---------------
-	if (!Force.ParseIndices(argv[1])) return 1;
-
-	// ---------- Parse the shielding indices into an array ---------------
-	if (periode != NULL) { // also look for PAS values
-		if(!Shielding.ParseIndices(argv[1])) return 1;
-		if(!ShieldingPAS.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.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return 1;
-	if (Hcorrected)	HcorrectionFragments.AllocateMatrix(Hcorrection.Header, Hcorrection.MatrixCounter, Hcorrection.RowCounter, Hcorrection.ColumnCounter);
-	if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return 1;
-	if (periode != NULL) { // also look for PAS values
-		if (!ShieldingFragments.AllocateMatrix(Shielding.Header, Shielding.MatrixCounter, Shielding.RowCounter, Shielding.ColumnCounter)) return 1;
-		if (!ShieldingPASFragments.AllocateMatrix(ShieldingPAS.Header, ShieldingPAS.MatrixCounter, ShieldingPAS.RowCounter, ShieldingPAS.ColumnCounter)) 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;
-	if (periode != NULL) { // also look for PAS values
-		if(!Shielding.SetLastMatrix(0., 2)) return 1;
-		if(!ShieldingPAS.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 (Hcorrected) {
-			HcorrectionFragments.SumSubManyBodyTerms(Hcorrection, KeySet, BondOrder);
-			if (!Energy.SumSubEnergy(EnergyFragments, &HcorrectionFragments, KeySet, BondOrder, 1.)) return 1;
-			if (Hcorrected) Hcorrection.SumSubEnergy(HcorrectionFragments, NULL, KeySet, BondOrder, 1.);
-		} else
-			if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) 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, 1.)) return 1;
-		if (periode != NULL) { // also look for PAS values
-			cout << "Summing shieldings of order " << BondOrder+1 << " ..." << endl;
-			if (!ShieldingFragments.SumSubManyBodyTerms(Shielding, KeySet, BondOrder)) return 1;
-			if (!Shielding.SumSubForces(ShieldingFragments, KeySet, BondOrder, 1.)) return 1;
-			if (!ShieldingPASFragments.SumSubManyBodyTerms(ShieldingPAS, KeySet, BondOrder)) return 1;
-			if (!ShieldingPAS.SumSubForces(ShieldingPASFragments, KeySet, BondOrder, 1.)) return 1;
-		}
-
-		// --------- write the energy and forces file --------------------
-		prefix.str(" ");
-		prefix << dir << 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;
-		// shieldings
-		if (periode != NULL) { // also look for PAS values
-			if (!Shielding.WriteLastMatrix(argv[1], (prefix.str()).c_str(), ShieldingSuffix)) return 1;
-			if (!ShieldingPAS.WriteLastMatrix(argv[1], (prefix.str()).c_str(), ShieldingPASSuffix)) return 1;
-		}
-	}
-	// fragments
-	prefix.str(" ");
-	prefix << dir << EnergyFragmentSuffix;
-	if (!EnergyFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
-	if (Hcorrected) {
-		prefix.str(" ");
-		prefix << dir << HcorrectionFragmentSuffix;
-		if (!HcorrectionFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
-	}
-	prefix.str(" ");
-	prefix << dir << ForceFragmentSuffix;
-	if (!ForceFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
-	if (!CreateDataFragment(EnergyFragments, KeySet, argv[1], FRAGMENTPREFIX ENERGYPERFRAGMENT, "fragment energy versus the Fragment No", "today", CreateEnergy)) return 1;
-	if (periode != NULL) { // also look for PAS values
-		prefix.str(" ");
-		prefix << dir << ShieldingFragmentSuffix;
-		if (!ShieldingFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
-		prefix.str(" ");
-		prefix << dir << ShieldingPASFragmentSuffix;
-		if (!ShieldingPASFragments.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], dir, EnergyFragmentSuffix)) return 1;
-	if (Hcorrected) Hcorrection.WriteLastMatrix(argv[1], dir, HcorrectionFragmentSuffix);
-	if (!Force.WriteLastMatrix(argv[1], dir, ForceFragmentSuffix)) return 1;
-	if (periode != NULL) { // also look for PAS values
-		if (!Shielding.WriteLastMatrix(argv[1], dir, ShieldingFragmentSuffix)) return 1;
-		if (!ShieldingPAS.WriteLastMatrix(argv[1], dir, ShieldingPASFragmentSuffix)) return 1;
-	}
-
-	// exit
-	delete(periode);
-	Free((void **)&dir, "main: *dir");
-	cout << "done." << endl;
-	return 0;
+  periodentafel *periode = NULL; // and a period table of all elements
+  EnergyMatrix Energy;
+  EnergyMatrix EnergyFragments;
+  
+  EnergyMatrix Hcorrection;
+  EnergyMatrix HcorrectionFragments;
+  
+  ForceMatrix Force;
+  ForceMatrix ForceFragments;
+
+  HessianMatrix Hessian;
+  HessianMatrix HessianFragments;
+  
+  ForceMatrix Shielding;
+  ForceMatrix ShieldingPAS;
+  ForceMatrix ShieldingFragments;
+  ForceMatrix ShieldingPASFragments;
+  ForceMatrix Chi;
+  ForceMatrix ChiPAS;
+  ForceMatrix ChiFragments;
+  ForceMatrix ChiPASFragments;
+  KeySetsContainer KeySet;  
+  stringstream prefix;
+  char *dir = NULL;
+  bool NoHCorrection = false;
+  bool NoHessian = false;
+
+  cout << "Joiner" << endl;
+  cout << "======" << endl;
+
+  // Get the command line options
+  if (argc < 3) {
+    cout << "Usage: " << argv[0] << " <inputdir> <prefix> [elementsdb]" << 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 << "[elementsdb]\tpath to elements database, needed for shieldings." << endl;
+    return 1;
+  } else {
+    dir = (char *) Malloc(sizeof(char)*(strlen(argv[2])+2), "main: *dir");
+    strcpy(dir, "/");
+    strcat(dir, argv[2]);
+  }
+  if (argc > 3) {
+    periode = new periodentafel;
+    periode->LoadPeriodentafel(argv[3]);
+  }
+
+  // Test the given directory
+  if (!TestParams(argc, argv))
+    return 1;
+
+  // +++++++++++++++++ PARSING +++++++++++++++++++++++++++++++
+
+  // ------------- Parse through all Fragment subdirs --------
+  if (!Energy.ParseFragmentMatrix(argv[1], dir, EnergySuffix, 0,0)) return 1;
+  if (!Hcorrection.ParseFragmentMatrix(argv[1], "", HCORRECTIONSUFFIX, 0,0)) {
+    NoHCorrection = true;
+    cout << "No HCorrection matrices found, skipping these." << endl;
+  }
+  if (!Force.ParseFragmentMatrix(argv[1], dir, ForcesSuffix, 0,0)) return 1;
+  if (!Hessian.ParseFragmentMatrix(argv[1], dir, HessianSuffix, 0,0)) {
+    NoHessian = true;
+    cout << "No hessian matrices found, skipping these." << endl;
+  }
+  if (periode != NULL) { // also look for PAS values
+    if (!Shielding.ParseFragmentMatrix(argv[1], dir, ShieldingSuffix, 1, 0)) return 1;
+    if (!ShieldingPAS.ParseFragmentMatrix(argv[1], dir, ShieldingPASSuffix, 1, 0)) return 1;
+    if (!Chi.ParseFragmentMatrix(argv[1], dir, ChiSuffix, 1, 0)) return 1;
+    if (!ChiPAS.ParseFragmentMatrix(argv[1], dir, ChiPASSuffix, 1, 0)) return 1;
+  }
+
+  // ---------- Parse the TE Factors into an array -----------------
+  if (!Energy.InitialiseIndices()) return 1;
+  if (!NoHCorrection) 
+    Hcorrection.InitialiseIndices();
+  
+  // ---------- Parse the Force indices into an array ---------------
+  if (!Force.ParseIndices(argv[1])) return 1;
+
+  // ---------- Parse the Hessian (=force) indices into an array ---------------
+  if (!NoHessian)
+    if (!Hessian.InitialiseIndices((class MatrixContainer *)&Force)) return 1;
+
+  // ---------- Parse the shielding indices into an array ---------------
+  if (periode != NULL) { // also look for PAS values
+    if(!Shielding.ParseIndices(argv[1])) return 1;
+    if(!ShieldingPAS.ParseIndices(argv[1])) return 1;
+    if(!Chi.ParseIndices(argv[1])) return 1;
+    if(!ChiPAS.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.AllocateMatrix(Energy.Header, Energy.MatrixCounter, Energy.RowCounter, Energy.ColumnCounter)) return 1;
+  if (!NoHCorrection)  
+    HcorrectionFragments.AllocateMatrix(Hcorrection.Header, Hcorrection.MatrixCounter, Hcorrection.RowCounter, Hcorrection.ColumnCounter);
+  if (!ForceFragments.AllocateMatrix(Force.Header, Force.MatrixCounter, Force.RowCounter, Force.ColumnCounter)) return 1;
+  if (!NoHessian)
+    if (!HessianFragments.AllocateMatrix(Hessian.Header, Hessian.MatrixCounter, Hessian.RowCounter, Hessian.ColumnCounter)) return 1;
+  if (periode != NULL) { // also look for PAS values
+    if (!ShieldingFragments.AllocateMatrix(Shielding.Header, Shielding.MatrixCounter, Shielding.RowCounter, Shielding.ColumnCounter)) return 1;
+    if (!ShieldingPASFragments.AllocateMatrix(ShieldingPAS.Header, ShieldingPAS.MatrixCounter, ShieldingPAS.RowCounter, ShieldingPAS.ColumnCounter)) return 1;
+    if (!ChiFragments.AllocateMatrix(Chi.Header, Chi.MatrixCounter, Chi.RowCounter, Chi.ColumnCounter)) return 1;
+    if (!ChiPASFragments.AllocateMatrix(ChiPAS.Header, ChiPAS.MatrixCounter, ChiPAS.RowCounter, ChiPAS.ColumnCounter)) 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;
+  if (!NoHessian)
+    if (!Hessian.SetLastMatrix(0., 0)) return 1;
+  if (periode != NULL) { // also look for PAS values
+    if(!Shielding.SetLastMatrix(0., 2)) return 1;
+    if(!ShieldingPAS.SetLastMatrix(0., 2)) return 1;
+    if(!Chi.SetLastMatrix(0., 2)) return 1;
+    if(!ChiPAS.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 (!NoHCorrection) { 
+      HcorrectionFragments.SumSubManyBodyTerms(Hcorrection, KeySet, BondOrder);
+      if (!Energy.SumSubEnergy(EnergyFragments, &HcorrectionFragments, KeySet, BondOrder, 1.)) return 1;
+      Hcorrection.SumSubEnergy(HcorrectionFragments, NULL, KeySet, BondOrder, 1.);
+    } else 
+      if (!Energy.SumSubEnergy(EnergyFragments, NULL, KeySet, BondOrder, 1.)) 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, 1.)) return 1;
+    // --------- sum up Hessian --------------------
+    if (!NoHessian) {
+      cout << "Summing Hessian of order " << BondOrder+1 << " ..." << endl;
+      if (!HessianFragments.SumSubManyBodyTerms(Hessian, KeySet, BondOrder)) return 1;
+      if (!Hessian.SumSubHessians(HessianFragments, KeySet, BondOrder, 1.)) return 1;
+    }
+    if (periode != NULL) { // also look for PAS values
+      cout << "Summing shieldings and susceptibilities of order " << BondOrder+1 << " ..." << endl;
+      if (!ShieldingFragments.SumSubManyBodyTerms(Shielding, KeySet, BondOrder)) return 1;
+      if (!Shielding.SumSubForces(ShieldingFragments, KeySet, BondOrder, 1.)) return 1;
+      if (!ShieldingPASFragments.SumSubManyBodyTerms(ShieldingPAS, KeySet, BondOrder)) return 1;
+      if (!ShieldingPAS.SumSubForces(ShieldingPASFragments, KeySet, BondOrder, 1.)) return 1;
+      if (!ChiFragments.SumSubManyBodyTerms(Chi, KeySet, BondOrder)) return 1;
+      if (!Chi.SumSubForces(ChiFragments, KeySet, BondOrder, 1.)) return 1;
+      if (!ChiPASFragments.SumSubManyBodyTerms(ChiPAS, KeySet, BondOrder)) return 1;
+      if (!ChiPAS.SumSubForces(ChiPASFragments, KeySet, BondOrder, 1.)) return 1;
+    }
+
+    // --------- write the energy and forces file --------------------
+    prefix.str(" ");
+    prefix << dir << 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;
+    // hessian
+    if (!NoHessian)
+      if (!Hessian.WriteLastMatrix(argv[1], (prefix.str()).c_str(), HessianSuffix)) return 1;
+    // shieldings
+    if (periode != NULL) { // also look for PAS values
+      if (!Shielding.WriteLastMatrix(argv[1], (prefix.str()).c_str(), ShieldingSuffix)) return 1;
+      if (!ShieldingPAS.WriteLastMatrix(argv[1], (prefix.str()).c_str(), ShieldingPASSuffix)) return 1;
+      if (!Chi.WriteLastMatrix(argv[1], (prefix.str()).c_str(), ChiSuffix)) return 1;
+      if (!ChiPAS.WriteLastMatrix(argv[1], (prefix.str()).c_str(), ChiPASSuffix)) return 1;
+    }
+  }
+  // fragments
+  prefix.str(" ");
+  prefix << dir << EnergyFragmentSuffix;
+  if (!EnergyFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+  if (!NoHCorrection) {
+    prefix.str(" ");
+    prefix << dir << HcorrectionFragmentSuffix;
+    if (!HcorrectionFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+  }
+  prefix.str(" ");
+  prefix << dir << ForceFragmentSuffix;
+  if (!ForceFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+  if (!CreateDataFragment(EnergyFragments, KeySet, argv[1], FRAGMENTPREFIX ENERGYPERFRAGMENT, "fragment energy versus the Fragment No", "today", CreateEnergy)) return 1;
+  if (!NoHessian) {
+    prefix.str(" ");
+    prefix << dir << HessianFragmentSuffix;
+    if (!HessianFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+  }
+  if (periode != NULL) { // also look for PAS values
+    prefix.str(" ");
+    prefix << dir << ShieldingFragmentSuffix;
+    if (!ShieldingFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+    prefix.str(" ");
+    prefix << dir << ShieldingPASFragmentSuffix;
+    if (!ShieldingPASFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+    prefix.str(" ");
+    prefix << dir << ChiFragmentSuffix;
+    if (!ChiFragments.WriteTotalFragments(argv[1], (prefix.str()).c_str())) return 1;
+    prefix.str(" ");
+    prefix << dir << ChiPASFragmentSuffix;
+    if (!ChiPASFragments.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], dir, EnergyFragmentSuffix)) return 1;
+  if (!NoHCorrection) Hcorrection.WriteLastMatrix(argv[1], dir, HcorrectionFragmentSuffix);
+  if (!Force.WriteLastMatrix(argv[1], dir, ForceFragmentSuffix)) return 1;
+  if (!NoHessian)
+    if (!Hessian.WriteLastMatrix(argv[1], dir, HessianFragmentSuffix)) return 1;
+  if (periode != NULL) { // also look for PAS values
+    if (!Shielding.WriteLastMatrix(argv[1], dir, ShieldingFragmentSuffix)) return 1;
+    if (!ShieldingPAS.WriteLastMatrix(argv[1], dir, ShieldingPASFragmentSuffix)) return 1;
+    if (!Chi.WriteLastMatrix(argv[1], dir, ChiFragmentSuffix)) return 1;
+    if (!ChiPAS.WriteLastMatrix(argv[1], dir, ChiPASFragmentSuffix)) return 1;
+  }
+
+  // exit
+  delete(periode);
+  Free((void **)&dir, "main: *dir");
+  cout << "done." << endl;
+  return 0;
 };
 
Index: src/linkedcell.cpp
===================================================================
--- src/linkedcell.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/linkedcell.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -6,11 +6,11 @@
 LinkedCell::LinkedCell()
 {
-	LC = NULL;
-	for(int i=0;i<NDIM;i++)
-		N[i] = 0;
-	index = -1;
-	RADIUS = 0.;
-	max.Zero();
-	min.Zero();
+  LC = NULL;
+  for(int i=0;i<NDIM;i++)
+    N[i] = 0;
+  index = -1;
+  RADIUS = 0.;
+  max.Zero();
+  min.Zero();
 };
 
@@ -21,67 +21,67 @@
 LinkedCell::LinkedCell(molecule *mol, double radius)
 {
-	atom *Walker = NULL;
+  atom *Walker = NULL;
 
-	RADIUS = radius;
-	LC = NULL;
-	for(int i=0;i<NDIM;i++)
-		N[i] = 0;
-	index = -1;
-	max.Zero();
-	min.Zero();
-	cout << Verbose(1) << "Begin of LinkedCell" << endl;
-	if (mol->start->next == mol->end) {
-		cerr << "ERROR: molecule contains no atoms!" << endl;
-		return;
-	}
-	// 1. find max and min per axis of atoms
-	Walker = mol->start->next;
-	for (int i=0;i<NDIM;i++) {
-		max.x[i] = Walker->x.x[i];
-		min.x[i] = Walker->x.x[i];
-	}
-	while (Walker != mol->end) {
-		for (int i=0;i<NDIM;i++) {
-			if (max.x[i] < Walker->x.x[i])
-				max.x[i] = Walker->x.x[i];
-			if (min.x[i] > Walker->x.x[i])
-				min.x[i] = Walker->x.x[i];
-		}
-		Walker = Walker->next;
-	}
-	cout << Verbose(2) << "Bounding box is " << min << " and " << max << "." << endl;
+  RADIUS = radius;
+  LC = NULL;
+  for(int i=0;i<NDIM;i++)
+    N[i] = 0;
+  index = -1;
+  max.Zero();
+  min.Zero();
+  cout << Verbose(1) << "Begin of LinkedCell" << endl;
+  if (mol->start->next == mol->end) {
+    cerr << "ERROR: molecule contains no atoms!" << endl;
+    return;
+  }
+  // 1. find max and min per axis of atoms
+  Walker = mol->start->next;
+  for (int i=0;i<NDIM;i++) {
+    max.x[i] = Walker->x.x[i];
+    min.x[i] = Walker->x.x[i];
+  }
+  while (Walker != mol->end) {
+    for (int i=0;i<NDIM;i++) {
+      if (max.x[i] < Walker->x.x[i])
+        max.x[i] = Walker->x.x[i];
+      if (min.x[i] > Walker->x.x[i])
+        min.x[i] = Walker->x.x[i];
+    }
+    Walker = Walker->next;
+  }
+  cout << Verbose(2) << "Bounding box is " << min << " and " << max << "." << endl;
 
-	// 2. find then umber of cells per axis
-	for (int i=0;i<NDIM;i++) {
-		N[i] = (int)floor((max.x[i] - min.x[i])/RADIUS)+1;
-	}
-	cout << Verbose(2) << "Number of cells per axis are " << N[0] << ", " << N[1] << " and " << N[2] << "." << endl;
+  // 2. find then umber of cells per axis
+  for (int i=0;i<NDIM;i++) {
+    N[i] = (int)floor((max.x[i] - min.x[i])/RADIUS)+1;
+  }
+  cout << Verbose(2) << "Number of cells per axis are " << N[0] << ", " << N[1] << " and " << N[2] << "." << endl;
 
-	// 3. allocate the lists
-	cout << Verbose(2) << "Allocating cells ... ";
-	if (LC != NULL) {
-		cout << Verbose(1) << "ERROR: Linked Cell list is already allocated, I do nothing." << endl;
-		return;
-	}
-	LC = new LinkedAtoms[N[0]*N[1]*N[2]];
-	for (index=0;index<N[0]*N[1]*N[2];index++) {
-		LC [index].clear();
-	}
-	cout << "done."  << endl;
+  // 3. allocate the lists
+  cout << Verbose(2) << "Allocating cells ... ";
+  if (LC != NULL) {
+    cout << Verbose(1) << "ERROR: Linked Cell list is already allocated, I do nothing." << endl;
+    return;
+  }
+  LC = new LinkedAtoms[N[0]*N[1]*N[2]];
+  for (index=0;index<N[0]*N[1]*N[2];index++) {
+    LC [index].clear();
+  }
+  cout << "done."  << endl;
 
-	// 4. put each atom into its respective cell
+  // 4. put each atom into its respective cell
   cout << Verbose(2) << "Filling cells ... ";
-	Walker = mol->start;
-	while (Walker->next != mol->end) {
-		Walker = Walker->next;
-		for (int i=0;i<NDIM;i++) {
-			n[i] = (int)floor((Walker->x.x[i] - min.x[i])/RADIUS);
-		}
-		index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
-		LC[index].push_back(Walker);
-		//cout << Verbose(2) << *Walker << " goes into cell " << n[0] << ", " << n[1] << ", " << n[2] << " with No. " << index << "." << endl;
-	}
+  Walker = mol->start;
+  while (Walker->next != mol->end) {
+    Walker = Walker->next;
+    for (int i=0;i<NDIM;i++) {
+      n[i] = (int)floor((Walker->x.x[i] - min.x[i])/RADIUS);
+    }
+    index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
+    LC[index].push_back(Walker);
+    //cout << Verbose(2) << *Walker << " goes into cell " << n[0] << ", " << n[1] << ", " << n[2] << " with No. " << index << "." << endl;
+  }
   cout << "done."  << endl;
-	cout << Verbose(1) << "End of LinkedCell" << endl;
+  cout << Verbose(1) << "End of LinkedCell" << endl;
 };
 
@@ -90,13 +90,13 @@
 LinkedCell::~LinkedCell()
 {
-	if (LC != NULL)
-	for (index=0;index<N[0]*N[1]*N[2];index++)
-		LC[index].clear();
-	delete[](LC);
-	for(int i=0;i<NDIM;i++)
-		N[i] = 0;
-	index = -1;
-	max.Zero();
-	min.Zero();
+  if (LC != NULL)
+  for (index=0;index<N[0]*N[1]*N[2];index++)
+    LC[index].clear();
+  delete[](LC);
+  for(int i=0;i<NDIM;i++)
+    N[i] = 0;
+  index = -1;
+  max.Zero();
+  min.Zero();
 };
 
@@ -106,10 +106,10 @@
 bool LinkedCell::CheckBounds()
 {
-	bool status = true;
-	for(int i=0;i<NDIM;i++)
-		status = status && ((n[i] >=0) && (n[i] < N[i]));
-	if (!status)
-	cerr << "ERROR: indices are out of bounds!" << endl;
-	return status;
+  bool status = true;
+  for(int i=0;i<NDIM;i++)
+    status = status && ((n[i] >=0) && (n[i] < N[i]));
+  if (!status)
+  cerr << "ERROR: indices are out of bounds!" << endl;
+  return status;
 };
 
@@ -120,10 +120,10 @@
 LinkedAtoms* LinkedCell::GetCurrentCell()
 {
-	if (CheckBounds()) {
-		index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
-		return (&(LC[index]));
-	} else {
-		return NULL;
-	}
+  if (CheckBounds()) {
+    index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
+    return (&(LC[index]));
+  } else {
+    return NULL;
+  }
 };
 
@@ -134,18 +134,17 @@
 bool LinkedCell::SetIndexToAtom(const atom &Walker)
 {
-	bool status = false;
-	for (int i=0;i<NDIM;i++) {
-		n[i] = (int)floor((Walker.x.x[i] - min.x[i])/RADIUS);
-	}
-
-	index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
-	if (CheckBounds()) {
-		for (LinkedAtoms::iterator Runner = LC[index].begin(); Runner != LC[index].end(); Runner++)
-			status = status || ((*Runner) == &Walker);
-		return status;
-	} else {
-		cerr << Verbose(1) << "WARN: Atom "<< Walker << " at " << Walker.x << " is out of bounds." << endl;
-		return false;
-	}
+  bool status = false;
+  for (int i=0;i<NDIM;i++) {
+    n[i] = (int)floor((Walker.x.x[i] - min.x[i])/RADIUS);
+  }
+  index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
+  if (CheckBounds()) {
+    for (LinkedAtoms::iterator Runner = LC[index].begin(); Runner != LC[index].end(); Runner++)
+      status = status || ((*Runner) == &Walker);
+    return status;
+  } else {
+    cerr << Verbose(1) << "ERROR: Atom "<< Walker << " at " << Walker.x << " is out of bounds." << endl;
+    return false;
+  }
 };
 
@@ -176,13 +175,13 @@
 bool LinkedCell::SetIndexToVector(const Vector *x)
 {
-	bool status = true;
-	for (int i=0;i<NDIM;i++) {
-		n[i] = (int)floor((x->x[i] - min.x[i])/RADIUS);
-		if (max.x[i] < x->x[i])
-			status = false;
-		if (min.x[i] > x->x[i])
-			status = false;
-	}
-	return status;
+  bool status = true;
+  for (int i=0;i<NDIM;i++) {
+    n[i] = (int)floor((x->x[i] - min.x[i])/RADIUS);
+    if (max.x[i] < x->x[i])
+      status = false;
+    if (min.x[i] > x->x[i])
+      status = false;
+  }
+  return status;
 };
 
Index: src/linkedcell.hpp
===================================================================
--- src/linkedcell.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/linkedcell.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -11,27 +11,27 @@
 #define LinkedAtoms list <atom *>
 
-class LinkedCell {
-	public:
-		Vector max;			 // upper boundary
-		Vector min;			 // lower boundary
-		LinkedAtoms *LC;	// linked cell list
-		double RADIUS;		// cell edge length
-		int N[NDIM];			// number of cells per axis
-		int n[NDIM];			// temporary variable for current cell per axis
-		int index;				// temporary index variable , access by index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
+class LinkedCell{
+  public:
+    Vector max;       // upper boundary
+    Vector min;       // lower boundary
+    LinkedAtoms *LC;  // linked cell list
+    double RADIUS;    // cell edge length
+    int N[NDIM];      // number of cells per axis
+    int n[NDIM];      // temporary variable for current cell per axis
+    int index;        // temporary index variable , access by index = n[0] * N[1] * N[2] + n[1] * N[2] + n[2];
 
-		LinkedCell();
-		LinkedCell(molecule *mol, double RADIUS);
-		~LinkedCell();
-		LinkedAtoms* GetCurrentCell();
-		bool SetIndexToAtom(const atom &Walker);
-		bool SetIndexToVector(const Vector *x);
+    LinkedCell();
+    LinkedCell(molecule *mol, double RADIUS);
+    ~LinkedCell();
+    LinkedAtoms* GetCurrentCell();
+    bool SetIndexToAtom(const atom &Walker);
+    bool SetIndexToVector(const Vector *x);
+    bool CheckBounds();
     void GetNeighbourBounds(int lower[NDIM], int upper[NDIM]);
-		bool CheckBounds();
 
-		// not implemented yet
-		bool AddAtom(atom *Walker);
-		bool DeleteAtom(atom *Walker);
-		bool MoveAtom(atom *Walker);
+    // not implemented yet
+    bool AddAtom(atom *Walker);
+    bool DeleteAtom(atom *Walker);
+    bool MoveAtom(atom *Walker);
 };
 
Index: src/moleculelist.cpp
===================================================================
--- src/moleculelist.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/moleculelist.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -35,9 +35,8 @@
  * \return true - add successful
  */
-bool MoleculeListClass::insert(molecule *mol)
+void MoleculeListClass::insert(molecule *mol)
 {
   mol->IndexNr = MaxIndex++;
   ListOfMolecules.push_back(mol);
-  return true;
 };
 
@@ -128,30 +127,37 @@
   atom *Walker = NULL;
   int Counts[MAX_ELEMENTS];
+  double size=0;
+  Vector Origin;
 
   // header
-  *out << "Index\tName\tNo.Atoms\tformula" << endl;
+  *out << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl;
   cout << Verbose(0) << "-----------------------------------------------" << endl;
   if (ListOfMolecules.size() == 0)
     *out << "\tNone" << endl;
   else {
+    Origin.Zero();
     for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
       // reset element counts
       for (int j = 0; j<MAX_ELEMENTS;j++)
         Counts[j] = 0;
-      // count atoms per element
+      // count atoms per element and determine size of bounding sphere
+      size=0.;
       Walker = (*ListRunner)->start;
       while (Walker->next != (*ListRunner)->end) {
         Walker = Walker->next;
         Counts[Walker->type->Z]++;
+        if (Walker->x.DistanceSquared(&Origin) > size)
+          size = Walker->x.DistanceSquared(&Origin);
       }
       // output Index, Name, number of atoms, chemical formula
       *out << ((*ListRunner)->ActiveFlag ? "*" : " ") << (*ListRunner)->IndexNr << "\t" << (*ListRunner)->name << "\t\t" << (*ListRunner)->AtomCount << "\t";
       Elemental = (*ListRunner)->elemente->end;
-      while(Elemental != (*ListRunner)->elemente->start) {
+      while(Elemental->previous != (*ListRunner)->elemente->start) {
         Elemental = Elemental->previous;
         if (Counts[Elemental->Z] != 0)
           *out << Elemental->symbol << Counts[Elemental->Z];
       }
-      *out << endl;
+      // Center and size
+      *out << "\t" << (*ListRunner)->Center << "\t" << sqrt(size) << endl;
     }
   }
@@ -164,11 +170,8 @@
 molecule * MoleculeListClass::ReturnIndex(int index)
 {
-  int count = 1;
-  MoleculeList::iterator ListRunner = ListOfMolecules.begin();
-  for(; ((ListRunner != ListOfMolecules.end()) && (count < index)); ListRunner++);
-  if (count == index)
-    return (*ListRunner);
-  else
-    return NULL;
+  for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
+    if ((*ListRunner)->IndexNr == index)
+      return (*ListRunner);
+  return NULL;
 };
 
@@ -523,5 +526,5 @@
 
   // open file for the force factors
-  *out << Verbose(1) << "Saving	force factors ... ";
+  *out << Verbose(1) << "Saving  force factors ... ";
   line << path << "/" << FRAGMENTPREFIX << FORCESFILE;
   ForcesFile.open(line.str().c_str(), ios::out);
@@ -565,8 +568,9 @@
  * \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
+ * \param DoPeriodic true - call ScanForPeriodicCorrection, false - don't
+ * \param DoCentering true - call molecule::CenterEdge(), false - don't
  * \return true - success (each file was written), false - something went wrong.
  */
-bool MoleculeListClass::OutputConfigForListOfFragments(ofstream *out,
-    config *configuration, int *SortIndex)
+bool MoleculeListClass::OutputConfigForListOfFragments(ofstream *out, config *configuration, int *SortIndex)
 {
   ofstream outputFragment;
@@ -691,9 +695,9 @@
 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;
+  //  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;
@@ -711,14 +715,14 @@
 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
-  //	}
+  //  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) {
@@ -729,11 +733,11 @@
   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;
+  //  } 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;
Index: src/molecules.cpp
===================================================================
--- src/molecules.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/molecules.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -16,15 +16,15 @@
 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=num;i--;) {
-		for(int j=NDIM;j--;)
-			sum += (gsl_vector_get(x,j) - (vectors[i])->x[j])*(gsl_vector_get(x,j) - (vectors[i])->x[j]);
-	}
-
-	return sum;
+  double sum = 0.;
+  struct LSQ_params *par = (struct LSQ_params *)params;
+  Vector **vectors = par->vectors;
+  int num = par->num;
+
+  for (int i=num;i--;) {
+    for(int j=NDIM;j--;)
+      sum += (gsl_vector_get(x,j) - (vectors[i])->x[j])*(gsl_vector_get(x,j) - (vectors[i])->x[j]);
+  }
+
+  return sum;
 };
 
@@ -36,31 +36,33 @@
 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
-	MDSteps = 0;
-	last_atom = 0;
-	elemente = teil;
-	AtomCount = 0;
-	BondCount = 0;
-	NoNonBonds = 0;
-	NoNonHydrogen = 0;
-	NoCyclicBonds = 0;
-	ListOfBondsPerAtom = NULL;
-	NumberOfBondsPerAtom = NULL;
-	ElementCount = 0;
-	for(int i=MAX_ELEMENTS;i--;)
-		ElementsInMolecule[i] = 0;
-	cell_size[0] = cell_size[2] = cell_size[5]= 20.;
-	cell_size[1] = cell_size[3] = cell_size[4]= 0.;
-	strcpy(name,"none");
+  // 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
+  MDSteps = 0;
+  last_atom = 0;
+  elemente = teil;
+  AtomCount = 0;
+  BondCount = 0;
+  NoNonBonds = 0;
+  NoNonHydrogen = 0;
+  NoCyclicBonds = 0;
+  ListOfBondsPerAtom = NULL;
+  NumberOfBondsPerAtom = NULL;
+  ElementCount = 0;
+  for(int i=MAX_ELEMENTS;i--;)
+    ElementsInMolecule[i] = 0;
+  cell_size[0] = cell_size[2] = cell_size[5]= 20.;
+  cell_size[1] = cell_size[3] = cell_size[4]= 0.;
+  strcpy(name,"none");
+  IndexNr  = -1;
+  ActiveFlag = false;
 };
 
@@ -70,14 +72,14 @@
 molecule::~molecule()
 {
-	if (ListOfBondsPerAtom != NULL)
-		for(int 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);
+  if (ListOfBondsPerAtom != NULL)
+    for(int 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);
 };
 
@@ -89,23 +91,23 @@
 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;
+  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;
 };
 
@@ -117,22 +119,16 @@
 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->v.CopyVector(&pointer->v); // copy velocity
-		walker->FixedIon = pointer->FixedIon;
-		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;
+  if (pointer != NULL) {
+    atom *walker = new atom(pointer);
+    walker->Name = (char *) Malloc(sizeof(char)*strlen(pointer->Name)+1, "atom::atom: *Name");
+    strcpy (walker->Name, pointer->Name);
+    walker->nr = last_atom++;  // increase number within molecule
+    add(walker, end);
+    if ((pointer->type != NULL) && (pointer->type->Z != 1))
+      NoNonHydrogen++;
+    AtomCount++;
+    return walker;
+  } else
+    return NULL;
 };
 
@@ -142,23 +138,23 @@
  * -# 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.
+ *    *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$.
+ *    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
@@ -168,5 +164,5 @@
  * \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 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
@@ -175,259 +171,259 @@
 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
-	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=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) << "ERROR: There is no typical hydrogen bond distance in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
-		return false;
-		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
-			FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
-			FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
-			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 (int 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->v.CopyVector(&TopReplacement->v); // copy velocity
-			FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
-			SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
-			SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
-			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) << "ERROR: There is no typical hydrogen bond angle in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
-				return false;
-				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(int i=NDIM;i--;) { // rotate by half the bond angle in both directions (InBondvector is bondangle = 0 direction)
-				FirstOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (sin(bondangle));
-				SecondOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (-sin(bondangle));
-			}
-			FirstOtherAtom->x.Scale(&BondRescale);	// rescale by correct BondDistance
-			SecondOtherAtom->x.Scale(&BondRescale);
-			//*out << Verbose(3) << "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << "." << endl;
-			for(int i=NDIM;i--;) { // and make relative to origin atom
-				FirstOtherAtom->x.x[i] += TopOrigin->x.x[i];
-				SecondOtherAtom->x.x[i] += TopOrigin->x.x[i];
-			}
-			// ... 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->v.CopyVector(&TopReplacement->v); // copy velocity
-			FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
-			SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
-			SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
-			ThirdOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
-			ThirdOtherAtom->FixedIon = TopReplacement->FixedIon;
-			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;
+  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
+  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=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) << "ERROR: There is no typical hydrogen bond distance in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
+    return false;
+    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
+      FirstOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
+      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 (int 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->v.CopyVector(&TopReplacement->v); // copy velocity
+      FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
+      SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
+      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) << "ERROR: There is no typical hydrogen bond angle in replacing bond (" << TopOrigin->Name << "<->" << TopReplacement->Name << ") of degree " << TopBond->BondDegree << "!" << endl;
+        return false;
+        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(int i=NDIM;i--;) { // rotate by half the bond angle in both directions (InBondvector is bondangle = 0 direction)
+        FirstOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (sin(bondangle));
+        SecondOtherAtom->x.x[i] = InBondvector.x[i] * cos(bondangle) + Orthovector1.x[i] * (-sin(bondangle));
+      }
+      FirstOtherAtom->x.Scale(&BondRescale);  // rescale by correct BondDistance
+      SecondOtherAtom->x.Scale(&BondRescale);
+      //*out << Verbose(3) << "ReScaleCheck: " << FirstOtherAtom->x.Norm() << " and " << SecondOtherAtom->x.Norm() << "." << endl;
+      for(int i=NDIM;i--;) { // and make relative to origin atom
+        FirstOtherAtom->x.x[i] += TopOrigin->x.x[i];
+        SecondOtherAtom->x.x[i] += TopOrigin->x.x[i];
+      }
+      // ... 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->v.CopyVector(&TopReplacement->v); // copy velocity
+      FirstOtherAtom->FixedIon = TopReplacement->FixedIon;
+      SecondOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      SecondOtherAtom->FixedIon = TopReplacement->FixedIon;
+      ThirdOtherAtom->v.CopyVector(&TopReplacement->v); // copy velocity
+      ThirdOtherAtom->FixedIon = TopReplacement->FixedIon;
+      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;
 };
 
@@ -439,58 +435,58 @@
 bool molecule::AddXYZFile(string filename)
 {
-	istringstream *input = NULL;
-	int NumberOfAtoms = 0; // atom number in xyz read
-	int i, j; // loop variables
-	atom *Walker = 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;
-
-	if (MDSteps == 0) // no atoms yet present
-		MDSteps++;
-	for(i=0;i<NumberOfAtoms;i++){
-		Walker = 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];
-		Walker->type = elemente->FindElement(shorthand);
-		if (Walker->type == NULL) {
-			cerr << "Could not parse the element at line: '" << line << "', setting to H.";
-			Walker->type = elemente->FindElement(1);
-		}
-		if (Trajectories[Walker].R.size() <= (unsigned int)MDSteps) {
-			Trajectories[Walker].R.resize(MDSteps+10);
-			Trajectories[Walker].U.resize(MDSteps+10);
-			Trajectories[Walker].F.resize(MDSteps+10);
-		}
-		for(j=NDIM;j--;) {
-			Walker->x.x[j] = x[j];
-			Trajectories[Walker].R.at(MDSteps-1).x[j] = x[j];
-			Trajectories[Walker].U.at(MDSteps-1).x[j] = 0;
-			Trajectories[Walker].F.at(MDSteps-1).x[j] = 0;
-		}
-		AddAtom(Walker);	// add to molecule
-		delete(item);
-	}
-	xyzfile.close();
-	delete(input);
-	return true;
+  istringstream *input = NULL;
+  int NumberOfAtoms = 0; // atom number in xyz read
+  int i, j; // loop variables
+  atom *Walker = 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;
+
+  if (MDSteps == 0) // no atoms yet present
+    MDSteps++;
+  for(i=0;i<NumberOfAtoms;i++){
+    Walker = 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];
+    Walker->type = elemente->FindElement(shorthand);
+    if (Walker->type == NULL) {
+      cerr << "Could not parse the element at line: '" << line << "', setting to H.";
+      Walker->type = elemente->FindElement(1);
+    }
+    if (Trajectories[Walker].R.size() <= (unsigned int)MDSteps) {
+      Trajectories[Walker].R.resize(MDSteps+10);
+      Trajectories[Walker].U.resize(MDSteps+10);
+      Trajectories[Walker].F.resize(MDSteps+10);
+    }
+    for(j=NDIM;j--;) {
+      Walker->x.x[j] = x[j];
+      Trajectories[Walker].R.at(MDSteps-1).x[j] = x[j];
+      Trajectories[Walker].U.at(MDSteps-1).x[j] = 0;
+      Trajectories[Walker].F.at(MDSteps-1).x[j] = 0;
+    }
+    AddAtom(Walker);  // add to molecule
+    delete(item);
+  }
+  xyzfile.close();
+  delete(input);
+  return true;
 };
 
@@ -500,58 +496,58 @@
 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;
+  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;
 };
 
@@ -564,14 +560,14 @@
 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;
+  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;
 };
 
@@ -583,7 +579,7 @@
 bool molecule::RemoveBond(bond *pointer)
 {
-	//cerr << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
-	removewithoutcheck(pointer);
-	return true;
+  //cerr << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
+  removewithoutcheck(pointer);
+  return true;
 };
 
@@ -595,6 +591,6 @@
 bool molecule::RemoveBonds(atom *BondPartner)
 {
-	cerr << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
-	return false;
+  cerr << Verbose(1) << "molecule::RemoveBond: Function not implemented yet." << endl;
+  return false;
 };
 
@@ -602,9 +598,9 @@
  * \param *filename filename
  */
-void molecule::SetNameFromFilename(char *filename)
+void molecule::SetNameFromFilename(const char *filename)
 {
   int length = 0;
   char *molname = strrchr(filename, '/')+sizeof(char);  // search for filename without dirs
-  char *endname = strrchr(filename, '.');
+  char *endname = strchr(molname, '.');
   if ((endname == NULL) || (endname < molname))
     length = strlen(molname);
@@ -612,4 +608,5 @@
     length = strlen(molname) - strlen(endname);
   strncpy(name, molname, length);
+  name[length]='\0';
 };
 
@@ -619,59 +616,59 @@
 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];
+  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 molecule in the box whose lengths are defined by vector \a *BoxLengths.
  * \param *out output stream for debugging
- * \param *BoxLengths box lengths
- */
-bool molecule::CenterInBox(ofstream *out, Vector *BoxLengths)
-{
-	bool status = true;
-	atom *ptr = NULL;
-	Vector *min = new Vector;
-	Vector *max = new Vector;
-
-	// gather min and max for each axis
-	ptr = start->next;	// start at first in list
-	if (ptr != end) {	 //list not empty?
-		for (int i=NDIM;i--;) {
-			max->x[i] = ptr->x.x[i];
-			min->x[i] = ptr->x.x[i];
-		}
-		while (ptr->next != end) {	// continue with second if present
-			ptr = ptr->next;
-			//ptr->Output(1,1,out);
-			for (int i=NDIM;i--;) {
-				max->x[i] = (max->x[i] < ptr->x.x[i]) ? ptr->x.x[i] : max->x[i];
-				min->x[i] = (min->x[i] > ptr->x.x[i]) ? ptr->x.x[i] : min->x[i];
-			}
-		}
-	}
-	// sanity check
-	for(int i=NDIM;i--;) {
-		if (max->x[i] - min->x[i] > BoxLengths->x[i])
-			status = false;
-	}
-	// warn if check failed
-	if (!status)
-		*out << "WARNING: molecule is bigger than defined box!" << endl;
-	else {	// else center in box
-		max->AddVector(min);
-		max->Scale(-1.);
-		max->AddVector(BoxLengths);
-		max->Scale(0.5);
-		Translate(max);
-	}
-
-	// free and exit
-	delete(min);
-	delete(max);
-	return status;
+ */
+bool molecule::CenterInBox(ofstream *out)
+{
+  bool status = true;
+  atom *ptr = NULL;
+  Vector x;
+  double *M = ReturnFullMatrixforSymmetric(cell_size);
+  double *Minv = x.InverseMatrix(M);
+  double value;
+
+//  cout << "The box matrix is :" << endl;
+//  for (int i=0;i<NDIM;++i) {
+//    for (int j=0;j<NDIM;++j)
+//      cout << M[i*NDIM+j] << "\t";
+//    cout << endl;
+//  }
+//  cout << "And its inverse is :" << endl;
+//  for (int i=0;i<NDIM;++i) {
+//    for (int j=0;j<NDIM;++j)
+//      cout << Minv[i*NDIM+j] << "\t";
+//    cout << endl;
+//  }
+  // go through all atoms
+  ptr = start->next;  // start at first in list
+  if (ptr != end) {  //list not empty?
+    while (ptr->next != end) {  // continue with second if present
+      ptr = ptr->next;
+      //ptr->Output(1,1,out);
+      // multiply its vector with matrix inverse
+      x.CopyVector(&ptr->x);
+      x.MatrixMultiplication(Minv);
+      // truncate to [0,1] for each axis
+      for (int i=0;i<NDIM;i++) {
+        value = floor(x.x[i]);  // next lower integer
+        if (x.x[i] >=0) {
+          x.x[i] -= value;
+        } else {
+          x.x[i] += value+1;
+        }
+      }
+    }
+  }
+  delete(M);
+  delete(Minv);
+  return status;
 };
 
@@ -682,32 +679,33 @@
 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=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=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;
-		min->Scale(-1.);
-		max->AddVector(min);
-		Translate(min);
-	}
-	delete(min);
-//	*out << Verbose(3) << "End of CenterEdge." << endl;
+  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=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=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;
+    min->Scale(-1.);
+    max->AddVector(min);
+    Translate(min);
+    Center.Zero();
+  }
+  delete(min);
+//  *out << Verbose(3) << "End of CenterEdge." << endl;
 };
 
@@ -716,21 +714,49 @@
  * \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=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);
-	}
+void molecule::CenterOrigin(ofstream *out)
+{
+  int Num = 0;
+  atom *ptr = start->next;  // start at first in list
+
+  Center.Zero();
+
+  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);
+    Center.Zero();
+  }
+};
+
+/** Returns vector pointing to center of all atoms.
+ * \param *out output stream for debugging
+ * \return pointer to center of all vector
+ */
+Vector * molecule::DetermineCenterOfAll(ofstream *out)
+{
+  atom *ptr = start->next;  // start at first in list
+  Vector *a = new Vector();
+  Vector tmp;
+  double Num = 0;
+
+  a->Zero();
+
+  if (ptr != end) {   //list not empty?
+    while (ptr->next != end) {  // continue with second if present
+      ptr = ptr->next;
+      Num += 1.;
+      tmp.CopyVector(&ptr->x);
+      a->AddVector(&tmp);
+    }
+    a->Scale(1./Num); // divide through total mass (and sign for direction)
+  }
+  //cout << Verbose(1) << "Resulting center of gravity: ";
+  //a->Output(out);
+  //cout << endl;
+  return a;
 };
 
@@ -739,55 +765,27 @@
  * \return pointer to center of gravity vector
  */
-Vector * molecule::DetermineCenterOfAll(ofstream *out)
-{
-	atom *ptr = start->next;	// start at first in list
-	Vector *a = new Vector();
-	Vector tmp;
-	double Num = 0;
-
-	a->Zero();
-
-	if (ptr != end) {	 //list not empty?
-		while (ptr->next != end) {	// continue with second if present
-			ptr = ptr->next;
-			Num += 1.;
-			tmp.CopyVector(&ptr->x);
-			a->AddVector(&tmp);
-		}
-		a->Scale(-1./Num); // divide through total mass (and sign for direction)
-	}
-	//cout << Verbose(1) << "Resulting center of gravity: ";
-	//a->Output(out);
-	//cout << endl;
-	return a;
-};
-
-/** Returns vector pointing to center of gravity.
- * \param *out output stream for debugging
- * \return pointer to center of gravity vector
- */
 Vector * molecule::DetermineCenterOfGravity(ofstream *out)
 {
-	atom *ptr = start->next;	// start at first in list
-	Vector *a = new Vector();
-	Vector tmp;
-	double Num = 0;
-
-	a->Zero();
-
-	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
-			a->AddVector(&tmp);
-		}
-		a->Scale(-1./Num); // divide through total mass (and sign for direction)
-	}
-//	*out << Verbose(1) << "Resulting center of gravity: ";
-//	a->Output(out);
-//	*out << endl;
-	return a;
+  atom *ptr = start->next;  // start at first in list
+  Vector *a = new Vector();
+  Vector tmp;
+  double Num = 0;
+
+  a->Zero();
+
+  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
+      a->AddVector(&tmp);
+    }
+    a->Scale(-1./Num); // divide through total mass (and sign for direction)
+  }
+//  *out << Verbose(1) << "Resulting center of gravity: ";
+//  a->Output(out);
+//  *out << endl;
+  return a;
 };
 
@@ -796,14 +794,19 @@
  * \param *center return vector for translation vector
  */
-void molecule::CenterGravity(ofstream *out, Vector *center)
-{
-	if (center == NULL) {
-		DetermineCenter(*center);
-		Translate(center);
-		delete(center);
-	} else {
-		Translate(center);
-	}
-};
+void molecule::CenterPeriodic(ofstream *out)
+{
+  DeterminePeriodicCenter(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::CenterAtVector(ofstream *out, Vector *newcenter)
+{
+  Center.CopyVector(newcenter);
+};
+
 
 /** Scales all atoms by \a *factor.
@@ -812,12 +815,12 @@
 void molecule::Scale(double **factor)
 {
-	atom *ptr = start;
-
-	while (ptr->next != end) {
-		ptr = ptr->next;
-		for (int j=0;j<MDSteps;j++)
-			Trajectories[ptr].R.at(j).Scale(factor);
-		ptr->x.Scale(factor);
-	}
+  atom *ptr = start;
+
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    for (int j=0;j<MDSteps;j++)
+      Trajectories[ptr].R.at(j).Scale(factor);
+    ptr->x.Scale(factor);
+  }
 };
 
@@ -827,13 +830,68 @@
 void molecule::Translate(const Vector *trans)
 {
-	atom *ptr = start;
-
-	while (ptr->next != end) {
-		ptr = ptr->next;
-		for (int j=0;j<MDSteps;j++)
-			Trajectories[ptr].R.at(j).Translate(trans);
-		ptr->x.Translate(trans);
-	}
-};
+  atom *ptr = start;
+
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    for (int j=0;j<MDSteps;j++)
+      Trajectories[ptr].R.at(j).Translate(trans);
+    ptr->x.Translate(trans);
+  }
+};
+
+/** Translate the molecule periodically in the box.
+ * \param trans[] translation vector.
+ */
+void molecule::TranslatePeriodically(const Vector *trans)
+{
+  atom *ptr = NULL;
+  Vector x;
+  double *M = ReturnFullMatrixforSymmetric(cell_size);
+  double *Minv = x.InverseMatrix(M);
+  double value;
+
+  // go through all atoms
+  ptr = start->next;  // start at first in list
+  while (ptr != end) {  // continue with second if present
+    //ptr->Output(1,1,out);
+    // multiply its vector with matrix inverse
+    x.CopyVector(&ptr->x);
+    x.Translate(trans);
+    x.MatrixMultiplication(Minv);
+    // truncate to [0,1] for each axis
+    for (int i=0;i<NDIM;i++) {
+      value = floor(fabs(x.x[i]));  // next lower integer
+      if (x.x[i] >=0) {
+        x.x[i] -= value;
+      } else {
+        x.x[i] += value+1;
+      }
+    }
+    // matrix multiply
+    x.MatrixMultiplication(M);
+    ptr->x.CopyVector(&x);
+    for (int j=0;j<MDSteps;j++) {
+      x.CopyVector(&Trajectories[ptr].R.at(j));
+      x.Translate(trans);
+      x.MatrixMultiplication(Minv);
+      // truncate to [0,1] for each axis
+      for (int i=0;i<NDIM;i++) {
+        value = floor(x.x[i]);  // next lower integer
+        if (x.x[i] >=0) {
+          x.x[i] -= value;
+        } else {
+          x.x[i] += value+1;
+        }
+      }
+      // matrix multiply
+      x.MatrixMultiplication(M);
+      Trajectories[ptr].R.at(j).CopyVector(&x);
+    }
+    ptr = ptr->next;
+  }
+  delete(M);
+  delete(Minv);
+};
+
 
 /** Mirrors all atoms against a given plane.
@@ -842,79 +900,79 @@
 void molecule::Mirror(const Vector *n)
 {
-	atom *ptr = start;
-
-	while (ptr->next != end) {
-		ptr = ptr->next;
-		for (int j=0;j<MDSteps;j++)
-			Trajectories[ptr].R.at(j).Mirror(n);
-		ptr->x.Mirror(n);
-	}
+  atom *ptr = start;
+
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    for (int j=0;j<MDSteps;j++)
+      Trajectories[ptr].R.at(j).Mirror(n);
+    ptr->x.Mirror(n);
+  }
 };
 
 /** Determines center of molecule (yet not considering atom masses).
- * \param Center reference to return vector
- */
-void molecule::DetermineCenter(Vector &Center)
-{
-	atom *Walker = start;
-	bond *Binder = NULL;
-	double *matrix = ReturnFullMatrixforSymmetric(cell_size);
-	double tmp;
-	bool flag;
-	Vector Testvector, Translationvector;
-
-	do {
-		Center.Zero();
-		flag = true;
-		while (Walker->next != end) {
-			Walker = Walker->next;
+ * \param center reference to return vector
+ */
+void molecule::DeterminePeriodicCenter(Vector &center)
+{
+  atom *Walker = start;
+  bond *Binder = NULL;
+  double *matrix = ReturnFullMatrixforSymmetric(cell_size);
+  double tmp;
+  bool flag;
+  Vector Testvector, Translationvector;
+
+  do {
+    Center.Zero();
+    flag = true;
+    while (Walker->next != end) {
+      Walker = Walker->next;
 #ifdef ADDHYDROGEN
-			if (Walker->type->Z != 1) {
+      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);
-				Center.AddVector(&Testvector);
-				cout << Verbose(1) << "vector is: ";
-				Testvector.Output((ofstream *)&cout);
-				cout << endl;
+        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);
+        Center.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);
-						Center.AddVector(&Testvector);
-						cout << Verbose(1) << "Hydrogen vector is: ";
-						Testvector.Output((ofstream *)&cout);
-						cout << endl;
-					}
-				}
-			}
+        // 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);
+            Center.AddVector(&Testvector);
+            cout << Verbose(1) << "Hydrogen vector is: ";
+            Testvector.Output((ofstream *)&cout);
+            cout << endl;
+          }
+        }
+      }
 #endif
-		}
-	} while (!flag);
-	Free((void **)&matrix, "molecule::DetermineCenter: *matrix");
-	Center.Scale(1./(double)AtomCount);
+    }
+  } while (!flag);
+  Free((void **)&matrix, "molecule::DetermineCenter: *matrix");
+  Center.Scale(1./(double)AtomCount);
 };
 
@@ -925,102 +983,570 @@
 void molecule::PrincipalAxisSystem(ofstream *out, bool DoRotate)
 {
-	atom *ptr = start;	// start at first in list
-	double InertiaTensor[NDIM*NDIM];
-	Vector *CenterOfGravity = DetermineCenterOfGravity(out);
-
-	CenterGravity(out, CenterOfGravity);
-
-	// reset inertia tensor
-	for(int i=0;i<NDIM*NDIM;i++)
-		InertiaTensor[i] = 0.;
-
-	// sum up inertia tensor
-	while (ptr->next != end) {
-		ptr = ptr->next;
-		Vector x;
-		x.CopyVector(&ptr->x);
-		//x.SubtractVector(CenterOfGravity);
-		InertiaTensor[0] += ptr->type->mass*(x.x[1]*x.x[1] + x.x[2]*x.x[2]);
-		InertiaTensor[1] += ptr->type->mass*(-x.x[0]*x.x[1]);
-		InertiaTensor[2] += ptr->type->mass*(-x.x[0]*x.x[2]);
-		InertiaTensor[3] += ptr->type->mass*(-x.x[1]*x.x[0]);
-		InertiaTensor[4] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[2]*x.x[2]);
-		InertiaTensor[5] += ptr->type->mass*(-x.x[1]*x.x[2]);
-		InertiaTensor[6] += ptr->type->mass*(-x.x[2]*x.x[0]);
-		InertiaTensor[7] += ptr->type->mass*(-x.x[2]*x.x[1]);
-		InertiaTensor[8] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[1]*x.x[1]);
-	}
-	// print InertiaTensor for debugging
-	*out << "The inertia tensor is:" << endl;
-	for(int i=0;i<NDIM;i++) {
-		for(int j=0;j<NDIM;j++)
-			*out << InertiaTensor[i*NDIM+j] << " ";
-		*out << endl;
-	}
-	*out << endl;
-
-	// diagonalize to determine principal axis system
-	gsl_eigen_symmv_workspace *T = gsl_eigen_symmv_alloc(NDIM);
-	gsl_matrix_view m = gsl_matrix_view_array(InertiaTensor, NDIM, NDIM);
-	gsl_vector *eval = gsl_vector_alloc(NDIM);
-	gsl_matrix *evec = gsl_matrix_alloc(NDIM, NDIM);
-	gsl_eigen_symmv(&m.matrix, eval, evec, T);
-	gsl_eigen_symmv_free(T);
-	gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_ABS_DESC);
-
-	for(int i=0;i<NDIM;i++) {
-		*out << Verbose(1) << "eigenvalue = " << gsl_vector_get(eval, i);
-		*out << ", eigenvector = (" << evec->data[i * evec->tda + 0] << "," << evec->data[i * evec->tda + 1] << "," << evec->data[i * evec->tda + 2] << ")" << endl;
-	}
-
-	// check whether we rotate or not
-	if (DoRotate) {
-		*out << Verbose(1) << "Transforming molecule into PAS ... ";
-		// the eigenvectors specify the transformation matrix
-		ptr = start;
-		while (ptr->next != end) {
-			ptr = ptr->next;
-			for (int j=0;j<MDSteps;j++)
-				Trajectories[ptr].R.at(j).MatrixMultiplication(evec->data);
-			ptr->x.MatrixMultiplication(evec->data);
-		}
-		*out << "done." << endl;
-
-		// summing anew for debugging (resulting matrix has to be diagonal!)
-		// reset inertia tensor
-		for(int i=0;i<NDIM*NDIM;i++)
-			InertiaTensor[i] = 0.;
-
-		// sum up inertia tensor
-		ptr = start;
-		while (ptr->next != end) {
-			ptr = ptr->next;
-			Vector x;
-			x.CopyVector(&ptr->x);
-			//x.SubtractVector(CenterOfGravity);
-			InertiaTensor[0] += ptr->type->mass*(x.x[1]*x.x[1] + x.x[2]*x.x[2]);
-			InertiaTensor[1] += ptr->type->mass*(-x.x[0]*x.x[1]);
-			InertiaTensor[2] += ptr->type->mass*(-x.x[0]*x.x[2]);
-			InertiaTensor[3] += ptr->type->mass*(-x.x[1]*x.x[0]);
-			InertiaTensor[4] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[2]*x.x[2]);
-			InertiaTensor[5] += ptr->type->mass*(-x.x[1]*x.x[2]);
-			InertiaTensor[6] += ptr->type->mass*(-x.x[2]*x.x[0]);
-			InertiaTensor[7] += ptr->type->mass*(-x.x[2]*x.x[1]);
-			InertiaTensor[8] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[1]*x.x[1]);
-		}
-		// print InertiaTensor for debugging
-		*out << "The inertia tensor is:" << endl;
-		for(int i=0;i<NDIM;i++) {
-			for(int j=0;j<NDIM;j++)
-				*out << InertiaTensor[i*NDIM+j] << " ";
-			*out << endl;
-		}
-		*out << endl;
-	}
-
-	// free everything
-	delete(CenterOfGravity);
-	gsl_vector_free(eval);
-	gsl_matrix_free(evec);
+  atom *ptr = start;  // start at first in list
+  double InertiaTensor[NDIM*NDIM];
+  Vector *CenterOfGravity = DetermineCenterOfGravity(out);
+
+  CenterPeriodic(out);
+
+  // reset inertia tensor
+  for(int i=0;i<NDIM*NDIM;i++)
+    InertiaTensor[i] = 0.;
+
+  // sum up inertia tensor
+  while (ptr->next != end) {
+    ptr = ptr->next;
+    Vector x;
+    x.CopyVector(&ptr->x);
+    //x.SubtractVector(CenterOfGravity);
+    InertiaTensor[0] += ptr->type->mass*(x.x[1]*x.x[1] + x.x[2]*x.x[2]);
+    InertiaTensor[1] += ptr->type->mass*(-x.x[0]*x.x[1]);
+    InertiaTensor[2] += ptr->type->mass*(-x.x[0]*x.x[2]);
+    InertiaTensor[3] += ptr->type->mass*(-x.x[1]*x.x[0]);
+    InertiaTensor[4] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[2]*x.x[2]);
+    InertiaTensor[5] += ptr->type->mass*(-x.x[1]*x.x[2]);
+    InertiaTensor[6] += ptr->type->mass*(-x.x[2]*x.x[0]);
+    InertiaTensor[7] += ptr->type->mass*(-x.x[2]*x.x[1]);
+    InertiaTensor[8] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[1]*x.x[1]);
+  }
+  // print InertiaTensor for debugging
+  *out << "The inertia tensor is:" << endl;
+  for(int i=0;i<NDIM;i++) {
+    for(int j=0;j<NDIM;j++)
+      *out << InertiaTensor[i*NDIM+j] << " ";
+    *out << endl;
+  }
+  *out << endl;
+
+  // diagonalize to determine principal axis system
+  gsl_eigen_symmv_workspace *T = gsl_eigen_symmv_alloc(NDIM);
+  gsl_matrix_view m = gsl_matrix_view_array(InertiaTensor, NDIM, NDIM);
+  gsl_vector *eval = gsl_vector_alloc(NDIM);
+  gsl_matrix *evec = gsl_matrix_alloc(NDIM, NDIM);
+  gsl_eigen_symmv(&m.matrix, eval, evec, T);
+  gsl_eigen_symmv_free(T);
+  gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_ABS_DESC);
+
+  for(int i=0;i<NDIM;i++) {
+    *out << Verbose(1) << "eigenvalue = " << gsl_vector_get(eval, i);
+    *out << ", eigenvector = (" << evec->data[i * evec->tda + 0] << "," << evec->data[i * evec->tda + 1] << "," << evec->data[i * evec->tda + 2] << ")" << endl;
+  }
+
+  // check whether we rotate or not
+  if (DoRotate) {
+    *out << Verbose(1) << "Transforming molecule into PAS ... ";
+    // the eigenvectors specify the transformation matrix
+    ptr = start;
+    while (ptr->next != end) {
+      ptr = ptr->next;
+      for (int j=0;j<MDSteps;j++)
+        Trajectories[ptr].R.at(j).MatrixMultiplication(evec->data);
+      ptr->x.MatrixMultiplication(evec->data);
+    }
+    *out << "done." << endl;
+
+    // summing anew for debugging (resulting matrix has to be diagonal!)
+    // reset inertia tensor
+    for(int i=0;i<NDIM*NDIM;i++)
+      InertiaTensor[i] = 0.;
+
+    // sum up inertia tensor
+    ptr = start;
+    while (ptr->next != end) {
+      ptr = ptr->next;
+      Vector x;
+      x.CopyVector(&ptr->x);
+      //x.SubtractVector(CenterOfGravity);
+      InertiaTensor[0] += ptr->type->mass*(x.x[1]*x.x[1] + x.x[2]*x.x[2]);
+      InertiaTensor[1] += ptr->type->mass*(-x.x[0]*x.x[1]);
+      InertiaTensor[2] += ptr->type->mass*(-x.x[0]*x.x[2]);
+      InertiaTensor[3] += ptr->type->mass*(-x.x[1]*x.x[0]);
+      InertiaTensor[4] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[2]*x.x[2]);
+      InertiaTensor[5] += ptr->type->mass*(-x.x[1]*x.x[2]);
+      InertiaTensor[6] += ptr->type->mass*(-x.x[2]*x.x[0]);
+      InertiaTensor[7] += ptr->type->mass*(-x.x[2]*x.x[1]);
+      InertiaTensor[8] += ptr->type->mass*(x.x[0]*x.x[0] + x.x[1]*x.x[1]);
+    }
+    // print InertiaTensor for debugging
+    *out << "The inertia tensor is:" << endl;
+    for(int i=0;i<NDIM;i++) {
+      for(int j=0;j<NDIM;j++)
+        *out << InertiaTensor[i*NDIM+j] << " ";
+      *out << endl;
+    }
+    *out << endl;
+  }
+
+  // free everything
+  delete(CenterOfGravity);
+  gsl_vector_free(eval);
+  gsl_matrix_free(evec);
+};
+
+/** Evaluates the potential energy used for constrained molecular dynamics.
+ * \f$V_i^{con} = c^{bond} \cdot | r_{P(i)} - R_i | + sum_{i \neq j} C^{min} \cdot \frac{1}{C_{ij}} + C^{inj} \Bigl (1 - \theta \bigl (\prod_{i \neq j} (P(i) - P(j)) \bigr ) \Bigr )\f$
+ *     where the first term points to the target in minimum distance, the second is a penalty for trajectories lying too close to each other (\f$C_{ij}$ is minimum distance between 
+ *     trajectories i and j) and the third term is a penalty for two atoms trying to each the same target point.
+ * Note that for the second term we have to solve the following linear system:
+ * \f$-c_1 \cdot n_1 + c_2 \cdot n_2 + C \cdot n_3 = - p_2 + p_1\f$, where \f$c_1\f$, \f$c_2\f$ and \f$C\f$ are constants, 
+ * offset vector \f$p_1\f$ in direction \f$n_1\f$, offset vector \f$p_2\f$ in direction \f$n_2\f$,
+ * \f$n_3\f$ is the normal vector to both directions. \f$C\f$ would be the minimum distance between the two lines.
+ * \sa molecule::MinimiseConstrainedPotential(), molecule::VerletForceIntegration()
+ * \param *out output stream for debugging
+ * \param *PermutationMap gives target ptr for each atom, array of size molecule::AtomCount (this is "x" in \f$ V^{con}(x) \f$ )
+ * \param startstep start configuration (MDStep in molecule::trajectories)
+ * \param endstep end configuration (MDStep in molecule::trajectories)
+ * \param *constants constant in front of each term
+ * \param IsAngstroem whether coordinates are in angstroem (true) or bohrradius (false)
+ * \return potential energy
+ * \note This routine is scaling quadratically which is not optimal.
+ * \todo There's a bit double counting going on for the first time, bu nothing to worry really about.
+ */
+double molecule::ConstrainedPotential(ofstream *out, atom **PermutationMap, int startstep, int endstep, double *constants, bool IsAngstroem)
+{
+  double result = 0., tmp, Norm1, Norm2;
+  atom *Walker = NULL, *Runner = NULL, *Sprinter = NULL;
+  Vector trajectory1, trajectory2, normal, TestVector;
+  gsl_matrix *A = gsl_matrix_alloc(NDIM,NDIM);
+  gsl_vector *x = gsl_vector_alloc(NDIM);
+
+  // go through every atom
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    // first term: distance to target
+    Runner = PermutationMap[Walker->nr];   // find target point
+    tmp = (Trajectories[Walker].R.at(startstep).Distance(&Trajectories[Runner].R.at(endstep)));
+    tmp *= IsAngstroem ? 1. : 1./AtomicLengthToAngstroem;
+    result += constants[0] * tmp;
+    //*out << Verbose(4) << "Adding " << tmp*constants[0] << "." << endl;
+    
+    // second term: sum of distances to other trajectories
+    Runner = start;
+    while (Runner->next != end) {
+      Runner = Runner->next;
+      if (Runner == Walker) // hence, we only go up to the Walker, not beyond (similar to i=0; i<j; i++)
+        break;
+      // determine normalized trajectories direction vector (n1, n2)
+      Sprinter = PermutationMap[Walker->nr];   // find first target point
+      trajectory1.CopyVector(&Trajectories[Sprinter].R.at(endstep));
+      trajectory1.SubtractVector(&Trajectories[Walker].R.at(startstep));
+      trajectory1.Normalize();
+      Norm1 = trajectory1.Norm();
+      Sprinter = PermutationMap[Runner->nr];   // find second target point
+      trajectory2.CopyVector(&Trajectories[Sprinter].R.at(endstep));
+      trajectory2.SubtractVector(&Trajectories[Runner].R.at(startstep));
+      trajectory2.Normalize();
+      Norm2 = trajectory1.Norm();
+      // check whether either is zero()
+      if ((Norm1 < MYEPSILON) && (Norm2 < MYEPSILON)) {
+        tmp = Trajectories[Walker].R.at(startstep).Distance(&Trajectories[Runner].R.at(startstep));
+      } else if (Norm1 < MYEPSILON) {
+        Sprinter = PermutationMap[Walker->nr];   // find first target point
+        trajectory1.CopyVector(&Trajectories[Sprinter].R.at(endstep));  // copy first offset
+        trajectory1.SubtractVector(&Trajectories[Runner].R.at(startstep));  // subtract second offset
+        trajectory2.Scale( trajectory1.ScalarProduct(&trajectory2) ); // trajectory2 is scaled to unity, hence we don't need to divide by anything 
+        trajectory1.SubtractVector(&trajectory2);   // project the part in norm direction away
+        tmp = trajectory1.Norm();  // remaining norm is distance
+      } else if (Norm2 < MYEPSILON) {
+        Sprinter = PermutationMap[Runner->nr];   // find second target point
+        trajectory2.CopyVector(&Trajectories[Sprinter].R.at(endstep));  // copy second offset
+        trajectory2.SubtractVector(&Trajectories[Walker].R.at(startstep));  // subtract first offset
+        trajectory1.Scale( trajectory2.ScalarProduct(&trajectory1) ); // trajectory1 is scaled to unity, hence we don't need to divide by anything 
+        trajectory2.SubtractVector(&trajectory1);   // project the part in norm direction away
+        tmp = trajectory2.Norm();  // remaining norm is distance
+      } else if ((fabs(trajectory1.ScalarProduct(&trajectory2)/Norm1/Norm2) - 1.) < MYEPSILON) { // check whether they're linear dependent
+//        *out << Verbose(3) << "Both trajectories of " << *Walker << " and " << *Runner << " are linear dependent: ";
+//        *out << trajectory1;
+//        *out << " and ";
+//        *out << trajectory2;
+        tmp = Trajectories[Walker].R.at(startstep).Distance(&Trajectories[Runner].R.at(startstep));
+//        *out << " with distance " << tmp << "." << endl;
+      } else { // determine distance by finding minimum distance
+//        *out << Verbose(3) << "Both trajectories of " << *Walker << " and " << *Runner << " are linear independent ";
+//        *out << endl;
+//        *out << "First Trajectory: ";
+//        *out << trajectory1 << endl;
+//        *out << "Second Trajectory: ";
+//        *out << trajectory2 << endl;
+        // determine normal vector for both
+        normal.MakeNormalVector(&trajectory1, &trajectory2);
+        // print all vectors for debugging
+//        *out << "Normal vector in between: ";
+//        *out << normal << endl;
+        // setup matrix
+        for (int i=NDIM;i--;) {
+          gsl_matrix_set(A, 0, i, trajectory1.x[i]);
+          gsl_matrix_set(A, 1, i, trajectory2.x[i]);
+          gsl_matrix_set(A, 2, i, normal.x[i]);
+          gsl_vector_set(x,i, (Trajectories[Walker].R.at(startstep).x[i] - Trajectories[Runner].R.at(startstep).x[i]));
+        }
+        // solve the linear system by Householder transformations
+        gsl_linalg_HH_svx(A, x);
+        // distance from last component
+        tmp = gsl_vector_get(x,2);
+//        *out << " with distance " << tmp << "." << endl;
+        // test whether we really have the intersection (by checking on c_1 and c_2)
+        TestVector.CopyVector(&Trajectories[Runner].R.at(startstep));
+        trajectory2.Scale(gsl_vector_get(x,1));
+        TestVector.AddVector(&trajectory2);
+        normal.Scale(gsl_vector_get(x,2));
+        TestVector.AddVector(&normal);
+        TestVector.SubtractVector(&Trajectories[Walker].R.at(startstep));
+        trajectory1.Scale(gsl_vector_get(x,0));
+        TestVector.SubtractVector(&trajectory1);
+        if (TestVector.Norm() < MYEPSILON) {
+//          *out << Verbose(2) << "Test: ok.\tDistance of " << tmp << " is correct." << endl;  
+        } else {
+//          *out << Verbose(2) << "Test: failed.\tIntersection is off by ";
+//          *out << TestVector;
+//          *out << "." << endl;  
+        }
+      }
+      // add up
+      tmp *= IsAngstroem ? 1. : 1./AtomicLengthToAngstroem;
+      if (fabs(tmp) > MYEPSILON) {
+        result += constants[1] * 1./tmp;
+        //*out << Verbose(4) << "Adding " << 1./tmp*constants[1] << "." << endl;
+      }
+    }
+      
+    // third term: penalty for equal targets
+    Runner = start;
+    while (Runner->next != end) {
+      Runner = Runner->next;
+      if ((PermutationMap[Walker->nr] == PermutationMap[Runner->nr]) && (Walker->nr < Runner->nr)) {
+        Sprinter = PermutationMap[Walker->nr];
+//        *out << *Walker << " and " << *Runner << " are heading to the same target at ";
+//        *out << Trajectories[Sprinter].R.at(endstep);
+//        *out << ", penalting." << endl;
+        result += constants[2];
+        //*out << Verbose(4) << "Adding " << constants[2] << "." << endl;
+      }
+    }
+  }
+  
+  return result;
+};
+
+void PrintPermutationMap(ofstream *out, atom **PermutationMap, int Nr) 
+{
+  stringstream zeile1, zeile2;
+  int *DoubleList = (int *) Malloc(Nr*sizeof(int), "PrintPermutationMap: *DoubleList");
+  int doubles = 0;
+  for (int i=0;i<Nr;i++)
+    DoubleList[i] = 0;
+  zeile1 << "PermutationMap: ";
+  zeile2 << "                ";
+  for (int i=0;i<Nr;i++) {
+    DoubleList[PermutationMap[i]->nr]++;
+    zeile1 << i << " ";
+    zeile2 << PermutationMap[i]->nr << " ";
+  }
+  for (int i=0;i<Nr;i++)
+    if (DoubleList[i] > 1)
+    doubles++;
+ // *out << "Found " << doubles << " Doubles." << endl;
+  Free((void **)&DoubleList, "PrintPermutationMap: *DoubleList");
+//  *out << zeile1.str() << endl << zeile2.str() << endl;
+};
+
+/** Minimises the extra potential for constrained molecular dynamics and gives forces and the constrained potential energy.
+ * We do the following:
+ *  -# Generate a distance list from all source to all target points
+ *  -# Sort this per source point
+ *  -# Take for each source point the target point with minimum distance, use this as initial permutation
+ *  -# check whether molecule::ConstrainedPotential() is greater than injective penalty
+ *     -# If so, we go through each source point, stepping down in the sorted target point distance list and re-checking potential.
+ *  -# Next, we only apply transformations that keep the injectivity of the permutations list.
+ *  -# Hence, for one source point we step down the ladder and seek the corresponding owner of this new target 
+ *     point and try to change it for one with lesser distance, or for the next one with greater distance, but only
+ *     if this decreases the conditional potential.
+ *  -# finished. 
+ *  -# Then, we calculate the forces by taking the spatial derivative, where we scale the potential to such a degree,
+ *     that the total force is always pointing in direction of the constraint force (ensuring that we move in the
+ *     right direction).
+ *  -# Finally, we calculate the potential energy and return.
+ * \param *out output stream for debugging
+ * \param **PermutationMap on return: mapping between the atom label of the initial and the final configuration
+ * \param startstep current MD step giving initial position between which and \a endstep we perform the constrained MD (as further steps are always concatenated)
+ * \param endstep step giving final position in constrained MD 
+ * \param IsAngstroem whether coordinates are in angstroem (true) or bohrradius (false)
+ * \sa molecule::VerletForceIntegration()
+ * \return potential energy (and allocated **PermutationMap (array of molecule::AtomCount ^2)
+ * \todo The constrained potential's constants are set to fixed values right now, but they should scale based on checks of the system in order
+ *       to ensure they're properties (e.g. constants[2] always greater than the energy of the system).
+ * \bug this all is not O(N log N) but O(N^2)
+ */
+double molecule::MinimiseConstrainedPotential(ofstream *out, atom **&PermutationMap, int startstep, int endstep, bool IsAngstroem)
+{
+  double Potential, OldPotential, OlderPotential;
+  PermutationMap = (atom **) Malloc(AtomCount*sizeof(atom *), "molecule::MinimiseConstrainedPotential: **PermutationMap");
+  DistanceMap **DistanceList = (DistanceMap **) Malloc(AtomCount*sizeof(DistanceMap *), "molecule::MinimiseConstrainedPotential: **DistanceList");
+  DistanceMap::iterator *DistanceIterators = (DistanceMap::iterator *) Malloc(AtomCount*sizeof(DistanceMap::iterator), "molecule::MinimiseConstrainedPotential: *DistanceIterators");
+  int *DoubleList = (int *) Malloc(AtomCount*sizeof(int), "molecule::MinimiseConstrainedPotential: *DoubleList");
+  DistanceMap::iterator *StepList = (DistanceMap::iterator *) Malloc(AtomCount*sizeof(DistanceMap::iterator), "molecule::MinimiseConstrainedPotential: *StepList");
+  double constants[3];
+  int round;
+  atom *Walker = NULL, *Runner = NULL, *Sprinter = NULL;
+  DistanceMap::iterator Rider, Strider;
+  
+  /// Minimise the potential
+  // set Lagrange multiplier constants
+  constants[0] = 10.;
+  constants[1] = 1.;
+  constants[2] = 1e+7;    // just a huge penalty
+  // generate the distance list
+  *out << Verbose(1) << "Creating the distance list ... " << endl;
+  for (int i=AtomCount; i--;) {
+    DoubleList[i] = 0;  // stores for how many atoms in startstep this atom is a target in endstep
+    DistanceList[i] = new DistanceMap;    // is the distance sorted target list per atom
+    DistanceList[i]->clear();
+  }
+  *out << Verbose(1) << "Filling the distance list ... " << endl;
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    Runner = start;
+    while(Runner->next != end) {
+      Runner = Runner->next;
+      DistanceList[Walker->nr]->insert( DistancePair(Trajectories[Walker].R.at(startstep).Distance(&Trajectories[Runner].R.at(endstep)), Runner) );
+    }
+  }
+  // create the initial PermutationMap (source -> target)
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    StepList[Walker->nr] = DistanceList[Walker->nr]->begin();    // stores the step to the next iterator that could be a possible next target
+    PermutationMap[Walker->nr] = DistanceList[Walker->nr]->begin()->second;   // always pick target with the smallest distance
+    DoubleList[DistanceList[Walker->nr]->begin()->second->nr]++;            // increase this target's source count (>1? not injective)
+    DistanceIterators[Walker->nr] = DistanceList[Walker->nr]->begin();    // and remember which one we picked
+    *out << *Walker << " starts with distance " << DistanceList[Walker->nr]->begin()->first << "." << endl;
+  }
+  *out << Verbose(1) << "done." << endl;
+  // make the PermutationMap injective by checking whether we have a non-zero constants[2] term in it
+  *out << Verbose(1) << "Making the PermutationMap injective ... " << endl;
+  Walker = start;
+  DistanceMap::iterator NewBase;
+  OldPotential = fabs(ConstrainedPotential(out, PermutationMap, startstep, endstep, constants, IsAngstroem));
+  while ((OldPotential) > constants[2]) {
+    PrintPermutationMap(out, PermutationMap, AtomCount);
+    Walker = Walker->next;
+    if (Walker == end) // round-robin at the end
+      Walker = start->next;
+    if (DoubleList[DistanceIterators[Walker->nr]->second->nr] <= 1)  // no need to make those injective that aren't
+      continue;
+    // now, try finding a new one
+    NewBase = DistanceIterators[Walker->nr];  // store old base
+    do {
+      NewBase++;  // take next further distance in distance to targets list that's a target of no one
+    } while ((DoubleList[NewBase->second->nr] != 0) && (NewBase != DistanceList[Walker->nr]->end()));
+    if (NewBase != DistanceList[Walker->nr]->end()) {
+      PermutationMap[Walker->nr] = NewBase->second;
+      Potential = fabs(ConstrainedPotential(out, PermutationMap, startstep, endstep, constants, IsAngstroem));
+      if (Potential > OldPotential) { // undo
+        PermutationMap[Walker->nr] = DistanceIterators[Walker->nr]->second;
+      } else {  // do
+        DoubleList[DistanceIterators[Walker->nr]->second->nr]--;  // decrease the old entry in the doubles list
+        DoubleList[NewBase->second->nr]++;    // increase the old entry in the doubles list
+        DistanceIterators[Walker->nr] = NewBase;
+        OldPotential = Potential;
+        *out << Verbose(3) << "Found a new permutation, new potential is " << OldPotential << "." << endl;
+      }
+    }
+  } 
+  for (int i=AtomCount; i--;) // now each single entry in the DoubleList should be <=1
+    if (DoubleList[i] > 1) { 
+      cerr << "Failed to create an injective PermutationMap!" << endl;
+      exit(1);
+    }
+  *out << Verbose(1) << "done." << endl;
+  Free((void **)&DoubleList, "molecule::MinimiseConstrainedPotential: *DoubleList");
+  // argument minimise the constrained potential in this injective PermutationMap
+  *out << Verbose(1) << "Argument minimising the PermutationMap, at current potential " << OldPotential << " ... " << endl;
+  OldPotential = 1e+10;
+  round = 0;
+  do {
+    *out << "Starting round " << ++round << " ... " << endl;
+    OlderPotential = OldPotential;
+    do {
+      Walker = start;
+      while (Walker->next != end) { // pick one
+        Walker = Walker->next;
+        PrintPermutationMap(out, PermutationMap, AtomCount);
+        Sprinter = DistanceIterators[Walker->nr]->second;   // store initial partner
+        Strider = DistanceIterators[Walker->nr];  //remember old iterator
+        DistanceIterators[Walker->nr] = StepList[Walker->nr];  
+        if (DistanceIterators[Walker->nr] == DistanceList[Walker->nr]->end()) {// stop, before we run through the list and still on
+          DistanceIterators[Walker->nr] == DistanceList[Walker->nr]->begin();
+          break;
+        }
+        //*out << Verbose(2) << "Current Walker: " << *Walker << " with old/next candidate " << *Sprinter << "/" << *DistanceIterators[Walker->nr]->second << "." << endl;
+        // find source of the new target
+        Runner = start->next;
+        while(Runner != end) { // find the source whose toes we might be stepping on (Walker's new target should be in use by another already)
+          if (PermutationMap[Runner->nr] == DistanceIterators[Walker->nr]->second) {
+            //*out << Verbose(2) << "Found the corresponding owner " << *Runner << " to " << *PermutationMap[Runner->nr] << "." << endl;
+            break;
+          }
+          Runner = Runner->next;
+        }
+        if (Runner != end) { // we found the other source
+          // then look in its distance list for Sprinter
+          Rider = DistanceList[Runner->nr]->begin();
+          for (; Rider != DistanceList[Runner->nr]->end(); Rider++)
+            if (Rider->second == Sprinter)
+              break;
+          if (Rider != DistanceList[Runner->nr]->end()) { // if we have found one
+            //*out << Verbose(2) << "Current Other: " << *Runner << " with old/next candidate " << *PermutationMap[Runner->nr] << "/" << *Rider->second << "." << endl; 
+            // exchange both 
+            PermutationMap[Walker->nr] = DistanceIterators[Walker->nr]->second; // put next farther distance into PermutationMap 
+            PermutationMap[Runner->nr] = Sprinter;  // and hand the old target to its respective owner
+            PrintPermutationMap(out, PermutationMap, AtomCount);
+            // calculate the new potential
+            //*out << Verbose(2) << "Checking new potential ..." << endl;
+            Potential = ConstrainedPotential(out, PermutationMap, startstep, endstep, constants, IsAngstroem);
+            if (Potential > OldPotential) { // we made everything worse! Undo ...
+              //*out << Verbose(3) << "Nay, made the potential worse: " << Potential << " vs. " << OldPotential << "!" << endl;
+              //*out << Verbose(3) << "Setting " << *Runner << "'s source to " << *DistanceIterators[Runner->nr]->second << "." << endl; 
+              // Undo for Runner (note, we haven't moved the iteration yet, we may use this)
+              PermutationMap[Runner->nr] = DistanceIterators[Runner->nr]->second;
+              // Undo for Walker
+              DistanceIterators[Walker->nr] = Strider;  // take next farther distance target
+              //*out << Verbose(3) << "Setting " << *Walker << "'s source to " << *DistanceIterators[Walker->nr]->second << "." << endl; 
+              PermutationMap[Walker->nr] = DistanceIterators[Walker->nr]->second;
+            } else {
+              DistanceIterators[Runner->nr] = Rider;  // if successful also move the pointer in the iterator list
+              *out << Verbose(3) << "Found a better permutation, new potential is " << Potential << " vs." << OldPotential << "." << endl;
+              OldPotential = Potential;
+            }
+            if (Potential > constants[2]) {
+              cerr << "ERROR: The two-step permutation procedure did not maintain injectivity!" << endl;
+              exit(255);
+            }
+            //*out << endl;
+          } else {
+            cerr << "ERROR: " << *Runner << " was not the owner of " << *Sprinter << "!" << endl;
+            exit(255);
+          }
+        } else {
+          PermutationMap[Walker->nr] = DistanceIterators[Walker->nr]->second; // new target has no source!
+        }
+        StepList[Walker->nr]++; // take next farther distance target
+      }
+    } while (Walker->next != end);
+  } while ((OlderPotential - OldPotential) > 1e-3);
+  *out << Verbose(1) << "done." << endl;
+
+  
+  /// free memory and return with evaluated potential 
+  for (int i=AtomCount; i--;)
+    DistanceList[i]->clear();
+  Free((void **)&DistanceList, "molecule::MinimiseConstrainedPotential: **DistanceList");
+  Free((void **)&DistanceIterators, "molecule::MinimiseConstrainedPotential: *DistanceIterators");
+  return ConstrainedPotential(out, PermutationMap, startstep, endstep, constants, IsAngstroem);
+};
+
+/** Evaluates the (distance-related part) of the constrained potential for the constrained forces.
+ * \param *out output stream for debugging
+ * \param startstep current MD step giving initial position between which and \a endstep we perform the constrained MD (as further steps are always concatenated)
+ * \param endstep step giving final position in constrained MD 
+ * \param **PermutationMap mapping between the atom label of the initial and the final configuration
+ * \param *Force ForceMatrix containing force vectors from the external energy functional minimisation.
+ * \todo the constant for the constrained potential distance part is hard-coded independently of the hard-coded value in MinimiseConstrainedPotential()
+ */
+void molecule::EvaluateConstrainedForces(ofstream *out, int startstep, int endstep, atom **PermutationMap, ForceMatrix *Force)
+{
+  double constant = 10.;
+  atom *Walker = NULL, *Sprinter = NULL; 
+  
+  /// evaluate forces (only the distance to target dependent part) with the final PermutationMap
+  *out << Verbose(1) << "Calculating forces and adding onto ForceMatrix ... " << endl;
+  Walker = start;
+  while (Walker->next != NULL) {
+    Walker = Walker->next;
+    Sprinter = PermutationMap[Walker->nr];
+    // set forces
+    for (int i=NDIM;i++;)
+      Force->Matrix[0][Walker->nr][5+i] += 2.*constant*sqrt(Trajectories[Walker].R.at(startstep).Distance(&Trajectories[Sprinter].R.at(endstep)));
+  }  
+  *out << Verbose(1) << "done." << endl;
+};
+
+/** Performs a linear interpolation between two desired atomic configurations with a given number of steps.
+ * Note, step number is config::MaxOuterStep
+ * \param *out output stream for debugging
+ * \param startstep stating initial configuration in molecule::Trajectories
+ * \param endstep stating final configuration in molecule::Trajectories
+ * \param &config configuration structure
+ * \return true - success in writing step files, false - error writing files or only one step in molecule::Trajectories
+ */
+bool molecule::LinearInterpolationBetweenConfiguration(ofstream *out, int startstep, int endstep, const char *prefix, config &configuration) 
+{
+  molecule *mol = NULL;
+  bool status = true;
+  int MaxSteps = configuration.MaxOuterStep; 
+  MoleculeListClass *MoleculePerStep = new MoleculeListClass();
+  // Get the Permutation Map by MinimiseConstrainedPotential
+  atom **PermutationMap = NULL;
+  atom *Walker = NULL, *Sprinter = NULL;
+  MinimiseConstrainedPotential(out, PermutationMap, startstep, endstep, configuration.GetIsAngstroem());
+
+  // check whether we have sufficient space in Trajectories for each atom
+  Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    if (Trajectories[Walker].R.size() <= (unsigned int)(MaxSteps)) {
+      //cout << "Increasing size for trajectory array of " << keyword << " to " << (MaxSteps+1) << "." << endl;
+      Trajectories[Walker].R.resize(MaxSteps+1);
+      Trajectories[Walker].U.resize(MaxSteps+1);
+      Trajectories[Walker].F.resize(MaxSteps+1);
+    }
+  }
+  // push endstep to last one
+  Walker = start;
+  while (Walker->next != end) { // remove the endstep (is now the very last one)
+    Walker = Walker->next;
+    for (int n=NDIM;n--;) {
+      Trajectories[Walker].R.at(MaxSteps).x[n] = Trajectories[Walker].R.at(endstep).x[n];
+      Trajectories[Walker].U.at(MaxSteps).x[n] = Trajectories[Walker].U.at(endstep).x[n];
+      Trajectories[Walker].F.at(MaxSteps).x[n] = Trajectories[Walker].F.at(endstep).x[n];
+    }
+  }
+  endstep = MaxSteps;
+  
+  // go through all steps and add the molecular configuration to the list and to the Trajectories of \a this molecule
+  *out << Verbose(1) << "Filling intermediate " << MaxSteps << " steps with MDSteps of " << MDSteps << "." << endl;
+  for (int step = 0; step <= MaxSteps; step++) {
+    mol = new molecule(elemente);
+    MoleculePerStep->insert(mol);
+    Walker = start;
+    while (Walker->next != end) {
+      Walker = Walker->next;
+      // add to molecule list
+      Sprinter = mol->AddCopyAtom(Walker);
+      for (int n=NDIM;n--;) {
+        Sprinter->x.x[n] = Trajectories[Walker].R.at(startstep).x[n] + (Trajectories[PermutationMap[Walker->nr]].R.at(endstep).x[n] - Trajectories[Walker].R.at(startstep).x[n])*((double)step/(double)MaxSteps);
+        // add to Trajectories
+        //*out << Verbose(3) << step << ">=" << MDSteps-1 << endl;
+        if (step < MaxSteps) {
+          Trajectories[Walker].R.at(step).x[n] = Trajectories[Walker].R.at(startstep).x[n] + (Trajectories[PermutationMap[Walker->nr]].R.at(endstep).x[n] - Trajectories[Walker].R.at(startstep).x[n])*((double)step/(double)MaxSteps);
+          Trajectories[Walker].U.at(step).x[n] = 0.;
+          Trajectories[Walker].F.at(step).x[n] = 0.;
+        }
+      }
+    }
+  }
+  MDSteps = MaxSteps+1;   // otherwise new Trajectories' points aren't stored on save&exit
+  
+  // store the list to single step files
+  int *SortIndex = (int *) Malloc(AtomCount*sizeof(int), "molecule::LinearInterpolationBetweenConfiguration: *SortIndex");
+  for (int i=AtomCount; i--; )
+    SortIndex[i] = i;
+  status = MoleculePerStep->OutputConfigForListOfFragments(out, &configuration, SortIndex);
+  
+  // free and return
+  Free((void **)&PermutationMap, "molecule::MinimiseConstrainedPotential: *PermutationMap");
+  delete(MoleculePerStep);
+  return status;
 };
 
@@ -1029,176 +1555,351 @@
  * have to transform them).
  * This adds a new MD step to the config file.
+ * \param *out output stream for debugging
  * \param *file filename
+ * \param config structure with config::Deltat, config::IsAngstroem, config::DoConstrained
  * \param delta_t time step width in atomic units
  * \param IsAngstroem whether coordinates are in angstroem (true) or bohrradius (false)
+ * \param DoConstrained whether we perform a constrained (>0, target step in molecule::trajectories) or unconstrained (0) molecular dynamics, \sa molecule::MinimiseConstrainedPotential() 
  * \return true - file found and parsed, false - file not found or imparsable
- */
-bool molecule::VerletForceIntegration(char *file, double delta_t, bool IsAngstroem)
-{
-	element *runner = elemente->start;
-	atom *walker = NULL;
-	int AtomNo;
-	ifstream input(file);
-	string token;
-	stringstream item;
-	double a, IonMass;
-	ForceMatrix Force;
-	Vector tmpvector;
-
-	CountElements();	// make sure ElementsInMolecule is up to date
-
-	// check file
-	if (input == NULL) {
-		return false;
-	} else {
-		// parse file into ForceMatrix
-		if (!Force.ParseMatrix(file, 0,0,0)) {
-			cerr << "Could not parse Force Matrix file " << file << "." << endl;
-			return false;
-		}
-		if (Force.RowCounter[0] != AtomCount) {
-			cerr << "Mismatch between number of atoms in file " << Force.RowCounter[0] << " and in molecule " << AtomCount << "." << endl;
-			return false;
-		}
-		// correct Forces
-//		for(int d=0;d<NDIM;d++)
-//			tmpvector.x[d] = 0.;
-//		for(int i=0;i<AtomCount;i++)
-//			for(int d=0;d<NDIM;d++) {
-//				tmpvector.x[d] += Force.Matrix[0][i][d+5];
-//			}
-//		for(int i=0;i<AtomCount;i++)
-//			for(int d=0;d<NDIM;d++) {
-//				Force.Matrix[0][i][d+5] -= tmpvector.x[d]/(double)AtomCount;
-//			}
-		// and perform Verlet integration for each atom with position, velocity and force vector
-		runner = elemente->start;
-		while (runner->next != elemente->end) { // go through every element
-			runner = runner->next;
-			IonMass = runner->mass;
-			a = delta_t*0.5/IonMass;				// (F+F_old)/2m = a and thus: v = (F+F_old)/2m * t = (F + F_old) * a
-			if (ElementsInMolecule[runner->Z]) { // if this element got atoms
-				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
-						// check size of vectors
-						if (Trajectories[walker].R.size() <= (unsigned int)(MDSteps)) {
-							//cout << "Increasing size for trajectory array of " << *walker << " to " << (size+10) << "." << endl;
-							Trajectories[walker].R.resize(MDSteps+10);
-							Trajectories[walker].U.resize(MDSteps+10);
-							Trajectories[walker].F.resize(MDSteps+10);
-						}
-						// 1. calculate x(t+\delta t)
-						for (int d=0; d<NDIM; d++) {
-							Trajectories[walker].F.at(MDSteps).x[d] = -Force.Matrix[0][AtomNo][d+5];
-							Trajectories[walker].R.at(MDSteps).x[d] = Trajectories[walker].R.at(MDSteps-1).x[d];
-							Trajectories[walker].R.at(MDSteps).x[d] += delta_t*(Trajectories[walker].U.at(MDSteps-1).x[d]);
-							Trajectories[walker].R.at(MDSteps).x[d] += 0.5*delta_t*delta_t*(Trajectories[walker].F.at(MDSteps-1).x[d])/IonMass;		// F = m * a and s = 0.5 * F/m * t^2 = F * a * t
-						}
-						// 2. Calculate v(t+\delta t)
-						for (int d=0; d<NDIM; d++) {
-							Trajectories[walker].U.at(MDSteps).x[d] = Trajectories[walker].U.at(MDSteps-1).x[d];
-							Trajectories[walker].U.at(MDSteps).x[d] += 0.5*delta_t*(Trajectories[walker].F.at(MDSteps-1).x[d]+Trajectories[walker].F.at(MDSteps).x[d])/IonMass;
-						}
-//						cout << "Integrated position&velocity of step " << (MDSteps) << ": (";
-//						for (int d=0;d<NDIM;d++)
-//							cout << Trajectories[walker].R.at(MDSteps).x[d] << " ";					// next step
-//						cout << ")\t(";
-//						for (int d=0;d<NDIM;d++)
-//							cout << Trajectories[walker].U.at(MDSteps).x[d] << " ";					// next step
-//						cout << ")" << endl;
-						// next atom
-						AtomNo++;
-					}
-				}
-			}
-		}
-	}
-//	// correct velocities (rather momenta) so that center of mass remains motionless
-//	tmpvector.zero()
-//	IonMass = 0.;
-//	walker = start;
-//	while (walker->next != end) { // go through every atom
-//		walker = walker->next;
-//		IonMass += walker->type->mass;	// sum up total mass
-//		for(int d=0;d<NDIM;d++) {
-//			tmpvector.x[d] += Trajectories[walker].U.at(MDSteps).x[d]*walker->type->mass;
-//		}
-//	}
-//	walker = start;
-//	while (walker->next != end) { // go through every atom of this element
-//		walker = walker->next;
-//		for(int d=0;d<NDIM;d++) {
-//			Trajectories[walker].U.at(MDSteps).x[d] -= tmpvector.x[d]*walker->type->mass/IonMass;
-//		}
-//	}
-	MDSteps++;
-
-
-	// exit
-	return true;
-};
-
-/** Align all atoms in such a manner that given vector \a *n is along z axis.
+ * \todo This is not yet checked if it is correctly working with DoConstrained set to true.
+ */
+bool molecule::VerletForceIntegration(ofstream *out, char *file, config &configuration)
+{
+  atom *walker = NULL;
+  ifstream input(file);
+  string token;
+  stringstream item;
+  double IonMass, Vector[NDIM], ConstrainedPotentialEnergy, ActualTemp;
+  ForceMatrix Force;
+
+  CountElements();  // make sure ElementsInMolecule is up to date
+
+  // check file
+  if (input == NULL) {
+    return false;
+  } else {
+    // parse file into ForceMatrix
+    if (!Force.ParseMatrix(file, 0,0,0)) {
+      cerr << "Could not parse Force Matrix file " << file << "." << endl;
+      return false;
+    }
+    if (Force.RowCounter[0] != AtomCount) {
+      cerr << "Mismatch between number of atoms in file " << Force.RowCounter[0] << " and in molecule " << AtomCount << "." << endl;
+      return false;
+    }
+    // correct Forces
+    for(int d=0;d<NDIM;d++)
+      Vector[d] = 0.;
+    for(int i=0;i<AtomCount;i++)
+      for(int d=0;d<NDIM;d++) {
+        Vector[d] += Force.Matrix[0][i][d+5];
+      }
+    for(int i=0;i<AtomCount;i++)
+      for(int d=0;d<NDIM;d++) {
+        Force.Matrix[0][i][d+5] -= Vector[d]/(double)AtomCount;
+      }
+    // solve a constrained potential if we are meant to
+    if (configuration.DoConstrainedMD) {
+      // calculate forces and potential
+      atom **PermutationMap = NULL;
+      ConstrainedPotentialEnergy = MinimiseConstrainedPotential(out, PermutationMap,configuration.DoConstrainedMD, 0, configuration.GetIsAngstroem());
+      EvaluateConstrainedForces(out, configuration.DoConstrainedMD, 0, PermutationMap, &Force);
+      Free((void **)&PermutationMap, "molecule::MinimiseConstrainedPotential: *PermutationMap");
+    }
+    
+    // and perform Verlet integration for each atom with position, velocity and force vector
+    walker = start;
+    while (walker->next != end) { // go through every atom of this element
+      walker = walker->next;
+      //a = configuration.Deltat*0.5/walker->type->mass;        // (F+F_old)/2m = a and thus: v = (F+F_old)/2m * t = (F + F_old) * a
+      // check size of vectors
+      if (Trajectories[walker].R.size() <= (unsigned int)(MDSteps)) {
+        //out << "Increasing size for trajectory array of " << *walker << " to " << (size+10) << "." << endl;
+        Trajectories[walker].R.resize(MDSteps+10);
+        Trajectories[walker].U.resize(MDSteps+10);
+        Trajectories[walker].F.resize(MDSteps+10);
+      }
+      
+      // Update R (and F)
+      for (int d=0; d<NDIM; d++) {
+        Trajectories[walker].F.at(MDSteps).x[d] = -Force.Matrix[0][walker->nr][d+5]*(configuration.GetIsAngstroem() ? AtomicLengthToAngstroem : 1.);
+        Trajectories[walker].R.at(MDSteps).x[d] = Trajectories[walker].R.at(MDSteps-1).x[d];
+        Trajectories[walker].R.at(MDSteps).x[d] += configuration.Deltat*(Trajectories[walker].U.at(MDSteps-1).x[d]);     // s(t) = s(0) + v * deltat + 1/2 a * deltat^2 
+        Trajectories[walker].R.at(MDSteps).x[d] += 0.5*configuration.Deltat*configuration.Deltat*(Trajectories[walker].F.at(MDSteps).x[d]/walker->type->mass);     // F = m * a and s = 0.5 * F/m * t^2 = F * a * t
+      }
+      // Update U
+      for (int d=0; d<NDIM; d++) {
+        Trajectories[walker].U.at(MDSteps).x[d] = Trajectories[walker].U.at(MDSteps-1).x[d]; 
+        Trajectories[walker].U.at(MDSteps).x[d] += configuration.Deltat * (Trajectories[walker].F.at(MDSteps).x[d]+Trajectories[walker].F.at(MDSteps-1).x[d]/walker->type->mass); // v = F/m * t
+      }
+//      out << "Integrated position&velocity of step " << (MDSteps) << ": ("; 
+//      for (int d=0;d<NDIM;d++)
+//        out << Trajectories[walker].R.at(MDSteps).x[d] << " ";          // next step
+//      out << ")\t(";
+//      for (int d=0;d<NDIM;d++)
+//        cout << Trajectories[walker].U.at(MDSteps).x[d] << " ";          // next step
+//      out << ")" << endl;
+            // next atom
+    }
+  }
+  // correct velocities (rather momenta) so that center of mass remains motionless
+  for(int d=0;d<NDIM;d++)
+    Vector[d] = 0.;
+  IonMass = 0.;
+  walker = start;
+  while (walker->next != end) { // go through every atom
+    walker = walker->next;
+    IonMass += walker->type->mass;  // sum up total mass
+    for(int d=0;d<NDIM;d++) {
+      Vector[d] += Trajectories[walker].U.at(MDSteps).x[d]*walker->type->mass;
+    }
+  }
+  // correct velocities (rather momenta) so that center of mass remains motionless
+  for(int d=0;d<NDIM;d++)
+    Vector[d] /= IonMass;
+  ActualTemp = 0.;
+  walker = start;
+  while (walker->next != end) { // go through every atom of this element
+    walker = walker->next;
+    for(int d=0;d<NDIM;d++) {
+      Trajectories[walker].U.at(MDSteps).x[d] -= Vector[d];
+      ActualTemp += 0.5 * walker->type->mass * Trajectories[walker].U.at(MDSteps).x[d] * Trajectories[walker].U.at(MDSteps).x[d];
+    }
+  }
+  Thermostats(configuration, ActualTemp, Berendsen);
+  MDSteps++;
+
+
+  // exit
+  return true;
+};
+
+/** Implementation of various thermostats.
+ * All these thermostats apply an additional force which has the following forms:
+ * -# Woodcock
+ *  \f$p_i \rightarrow \sqrt{\frac{T_0}{T}} \cdot p_i\f$
+ * -# Gaussian
+ *  \f$ \frac{ \sum_i \frac{p_i}{m_i} \frac{\partial V}{\partial q_i}} {\sum_i \frac{p^2_i}{m_i}} \cdot p_i\f$
+ * -# Langevin
+ *  \f$p_{i,n} \rightarrow \sqrt{1-\alpha^2} p_{i,0} + \alpha p_r\f$  
+ * -# Berendsen
+ *  \f$p_i \rightarrow \left [ 1+ \frac{\delta t}{\tau_T} \left ( \frac{T_0}{T} \right ) \right ]^{\frac{1}{2}} \cdot p_i\f$
+ * -# Nose-Hoover
+ *  \f$\zeta p_i \f$ with \f$\frac{\partial \zeta}{\partial t} = \frac{1}{M_s} \left ( \sum^N_{i=1} \frac{p_i^2}{m_i} - g k_B T \right )\f$
+ * These Thermostats either simply rescale the velocities, thus this function should be called after ion velocities have been updated, and/or
+ * have a constraint force acting additionally on the ions. In the latter case, the ion speeds have to be modified
+ * belatedly and the constraint force set.
+ * \param *P Problem at hand
+ * \param i which of the thermostats to take: 0 - none, 1 - Woodcock, 2 - Gaussian, 3 - Langevin, 4 - Berendsen, 5 - Nose-Hoover
+ * \sa InitThermostat()
+ */
+void molecule::Thermostats(config &configuration, double ActualTemp, int Thermostat)
+{
+  double ekin = 0.;
+  double E = 0., G = 0.;
+  double delta_alpha = 0.;
+  double ScaleTempFactor;
+  double sigma;
+  double IonMass;
+  int d;
+  gsl_rng * r;
+  const gsl_rng_type * T;
+  double *U = NULL, *F = NULL, FConstraint[NDIM];
+  atom *walker = NULL;
+  
+  // calculate scale configuration
+  ScaleTempFactor = configuration.TargetTemp/ActualTemp;
+    
+  // differentating between the various thermostats
+  switch(Thermostat) {
+     case None:
+      cout << Verbose(2) <<  "Applying no thermostat..." << endl;
+      break;
+     case Woodcock:
+      if ((configuration.ScaleTempStep > 0) && ((MDSteps-1) % configuration.ScaleTempStep == 0)) {
+        cout << Verbose(2) <<  "Applying Woodcock thermostat..." << endl;
+        walker = start;
+        while (walker->next != end) { // go through every atom of this element
+          walker = walker->next;
+          IonMass = walker->type->mass;
+          U = Trajectories[walker].U.at(MDSteps).x;
+          if (walker->FixedIon == 0) // even FixedIon moves, only not by other's forces
+            for (d=0; d<NDIM; d++) {
+              U[d] *= sqrt(ScaleTempFactor);
+              ekin += 0.5*IonMass * U[d]*U[d];
+            }
+        }
+      }
+      break;
+     case Gaussian:
+      cout << Verbose(2) <<  "Applying Gaussian thermostat..." << endl;
+      walker = start;
+      while (walker->next != end) { // go through every atom of this element
+        walker = walker->next;
+        IonMass = walker->type->mass;
+        U = Trajectories[walker].U.at(MDSteps).x;
+        F = Trajectories[walker].F.at(MDSteps).x;
+        if (walker->FixedIon == 0) // even FixedIon moves, only not by other's forces
+          for (d=0; d<NDIM; d++) {
+            G += U[d] * F[d]; 
+            E += U[d]*U[d]*IonMass;
+          }
+      }
+      cout << Verbose(1) << "Gaussian Least Constraint constant is " << G/E << "." << endl;
+      walker = start;
+      while (walker->next != end) { // go through every atom of this element
+        walker = walker->next;
+        IonMass = walker->type->mass;
+        U = Trajectories[walker].U.at(MDSteps).x;
+        F = Trajectories[walker].F.at(MDSteps).x;
+        if (walker->FixedIon == 0) // even FixedIon moves, only not by other's forces
+          for (d=0; d<NDIM; d++) {
+            FConstraint[d] = (G/E) * (U[d]*IonMass);
+            U[d] += configuration.Deltat/IonMass * (FConstraint[d]);
+            ekin += IonMass * U[d]*U[d];
+          }
+      }
+      break;
+     case Langevin:
+      cout << Verbose(2) <<  "Applying Langevin thermostat..." << endl;
+      // init random number generator
+      gsl_rng_env_setup();
+      T = gsl_rng_default;
+      r = gsl_rng_alloc (T);
+      // Go through each ion
+      walker = start;
+      while (walker->next != end) { // go through every atom of this element
+        walker = walker->next;
+        IonMass = walker->type->mass;
+        sigma  = sqrt(configuration.TargetTemp/IonMass); // sigma = (k_b T)/m (Hartree/atomicmass = atomiclength/atomictime)
+        U = Trajectories[walker].U.at(MDSteps).x;
+        F = Trajectories[walker].F.at(MDSteps).x;
+        if (walker->FixedIon == 0) { // even FixedIon moves, only not by other's forces
+          // throw a dice to determine whether it gets hit by a heat bath particle
+          if (((((rand()/(double)RAND_MAX))*configuration.TempFrequency) < 1.)) {  
+            cout << Verbose(3) << "Particle " << *walker << " was hit (sigma " << sigma << "): " << sqrt(U[0]*U[0]+U[1]*U[1]+U[2]*U[2]) << " -> ";
+            // pick three random numbers from a Boltzmann distribution around the desired temperature T for each momenta axis
+            for (d=0; d<NDIM; d++) {
+              U[d] = gsl_ran_gaussian (r, sigma);
+            }
+            cout << sqrt(U[0]*U[0]+U[1]*U[1]+U[2]*U[2]) << endl;
+          }
+          for (d=0; d<NDIM; d++)
+            ekin += 0.5*IonMass * U[d]*U[d];
+        }
+      }
+      break;
+     case Berendsen:
+      cout << Verbose(2) <<  "Applying Berendsen-VanGunsteren thermostat..." << endl;
+      walker = start;
+      while (walker->next != end) { // go through every atom of this element
+        walker = walker->next;
+        IonMass = walker->type->mass;
+        U = Trajectories[walker].U.at(MDSteps).x;
+        F = Trajectories[walker].F.at(MDSteps).x;
+        if (walker->FixedIon == 0) { // even FixedIon moves, only not by other's forces
+          for (d=0; d<NDIM; d++) {
+            U[d] *= sqrt(1+(configuration.Deltat/configuration.TempFrequency)*(ScaleTempFactor-1));
+            ekin += 0.5*IonMass * U[d]*U[d];
+          }
+        }
+      }
+      break;
+     case NoseHoover:
+      cout << Verbose(2) <<  "Applying Nose-Hoover thermostat..." << endl;
+      // dynamically evolve alpha (the additional degree of freedom)
+      delta_alpha = 0.;
+      walker = start;
+      while (walker->next != end) { // go through every atom of this element
+        walker = walker->next;
+        IonMass = walker->type->mass;
+        U = Trajectories[walker].U.at(MDSteps).x;
+        if (walker->FixedIon == 0) { // even FixedIon moves, only not by other's forces
+          for (d=0; d<NDIM; d++) {
+            delta_alpha += U[d]*U[d]*IonMass;
+          }
+        }
+      }
+      delta_alpha = (delta_alpha - (3.*AtomCount+1.) * configuration.TargetTemp)/(configuration.HooverMass*Units2Electronmass);
+      configuration.alpha += delta_alpha*configuration.Deltat;
+      cout << Verbose(3) << "alpha = " << delta_alpha << " * " << configuration.Deltat << " = " << configuration.alpha << "." << endl;
+      // apply updated alpha as additional force
+      walker = start;
+      while (walker->next != end) { // go through every atom of this element
+        walker = walker->next;
+        IonMass = walker->type->mass;
+        U = Trajectories[walker].U.at(MDSteps).x;
+        if (walker->FixedIon == 0) { // even FixedIon moves, only not by other's forces
+          for (d=0; d<NDIM; d++) {
+              FConstraint[d] = - configuration.alpha * (U[d] * IonMass);
+              U[d] += configuration.Deltat/IonMass * (FConstraint[d]);
+              ekin += (0.5*IonMass) * U[d]*U[d];
+            }
+        }
+      }
+      break;
+  }    
+  cout << Verbose(1) << "Kinetic energy is " << ekin << "." << endl;
+};
+
+/** 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];
-		for (int j=0;j<MDSteps;j++) {
-			tmp = Trajectories[ptr].R.at(j).x[0];
-			Trajectories[ptr].R.at(j).x[0] =	cos(alpha) * tmp + sin(alpha) * Trajectories[ptr].R.at(j).x[2];
-			Trajectories[ptr].R.at(j).x[2] = -sin(alpha) * tmp + cos(alpha) * Trajectories[ptr].R.at(j).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];
-		for (int j=0;j<MDSteps;j++) {
-			tmp = Trajectories[ptr].R.at(j).x[1];
-			Trajectories[ptr].R.at(j).x[1] =	cos(alpha) * tmp + sin(alpha) * Trajectories[ptr].R.at(j).x[2];
-			Trajectories[ptr].R.at(j).x[2] = -sin(alpha) * tmp + cos(alpha) * Trajectories[ptr].R.at(j).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;
+  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];
+    for (int j=0;j<MDSteps;j++) {
+      tmp = Trajectories[ptr].R.at(j).x[0];
+      Trajectories[ptr].R.at(j).x[0] =  cos(alpha) * tmp + sin(alpha) * Trajectories[ptr].R.at(j).x[2];
+      Trajectories[ptr].R.at(j).x[2] = -sin(alpha) * tmp + cos(alpha) * Trajectories[ptr].R.at(j).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];
+    for (int j=0;j<MDSteps;j++) {
+      tmp = Trajectories[ptr].R.at(j).x[1];
+      Trajectories[ptr].R.at(j).x[1] =  cos(alpha) * tmp + sin(alpha) * Trajectories[ptr].R.at(j).x[2];
+      Trajectories[ptr].R.at(j).x[2] = -sin(alpha) * tmp + cos(alpha) * Trajectories[ptr].R.at(j).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;
 };
 
@@ -1209,12 +1910,13 @@
 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--;
-	Trajectories.erase(pointer);
-	return remove(pointer, start, end);
+  if (ElementsInMolecule[pointer->type->Z] != 0)  { // this would indicate an error
+    ElementsInMolecule[pointer->type->Z]--;  // decrease number of atom of this element
+    AtomCount--;
+  } 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--;
+  Trajectories.erase(pointer);
+  return remove(pointer, start, end);
 };
 
@@ -1243,5 +1945,5 @@
 bool molecule::CleanupMolecule()
 {
-	return (cleanup(start,end) && cleanup(first,last));
+  return (cleanup(start,end) && cleanup(first,last));
 };
 
@@ -1250,13 +1952,13 @@
  * \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;
-	}
+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;
+  }
 };
 
@@ -1266,15 +1968,15 @@
 atom * molecule::AskAtom(string 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;
+  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;
 };
 
@@ -1285,12 +1987,12 @@
 bool molecule::CheckBounds(const Vector *x) const
 {
-	bool result = true;
-	int j =-1;
-	for (int i=0;i<NDIM;i++) {
-		j += i+1;
-		result = result && ((x->x[i] >= 0) && (x->x[i] < cell_size[j]));
-	}
-	//return result;
-	return true; /// probably not gonna use the check no more
+  bool result = true;
+  int j =-1;
+  for (int i=0;i<NDIM;i++) {
+    j += i+1;
+    result = result && ((x->x[i] >= 0) && (x->x[i] < cell_size[j]));
+  }
+  //return result;
+  return true; /// probably not gonna use the check no more
 };
 
@@ -1302,30 +2004,30 @@
 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;
+  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;
 };
 
@@ -1335,71 +2037,71 @@
 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);
+    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);
 };
 
@@ -1409,32 +2111,34 @@
 bool molecule::Output(ofstream *out)
 {
-	element *runner;
-	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;
-		runner = elemente->start;
-		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); // removed due to trajectories
-					}
-				}
-			}
-		}
-		return true;
-	}
+  atom *walker = NULL;
+  int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
+  CountElements();
+
+  for (int i=0;i<MAX_ELEMENTS;++i) {
+    AtomNo[i] = 0;
+    ElementNo[i] = 0;
+  }
+  if (out == NULL) {
+    return false;
+  } else {
+    *out << "#Ion_TypeNr._Nr.R[0]    R[1]    R[2]    MoveType (0 MoveIon, 1 FixedIon)" << endl;
+    walker = start;
+    while (walker->next != end) { // go through every atom of this element
+      walker = walker->next;
+      ElementNo[walker->type->Z] = 1;
+    }
+    int current=1;
+    for (int i=0;i<MAX_ELEMENTS;++i) {
+      if (ElementNo[i] == 1)
+        ElementNo[i] = current++;
+    }
+    walker = start;
+    while (walker->next != end) { // go through every atom of this element
+      walker = walker->next;
+      AtomNo[walker->type->Z]++;
+      walker->Output(ElementNo[walker->type->Z], AtomNo[walker->type->Z], out); // removed due to trajectories
+    }
+    return true;
+  }
 };
 
@@ -1444,45 +2148,47 @@
 bool molecule::OutputTrajectories(ofstream *out)
 {
-	element *runner = NULL;
-	atom *walker = NULL;
-	int ElementNo, AtomNo;
-	CountElements();
-
-	if (out == NULL) {
-		return false;
-	} else {
-		for (int step = 0; step < MDSteps; step++) {
-			if (step == 0) {
-				*out << "#Ion_TypeNr._Nr.R[0]		R[1]		R[2]		MoveType (0 MoveIon, 1 FixedIon)" << endl;
-			} else {
-				*out << "# ====== MD step " << step << " =========" << endl;
-			}
-			ElementNo = 0;
-			runner = elemente->start;
-			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++;
-							*out << "Ion_Type" << ElementNo << "_" << AtomNo << "\t"	<< fixed << setprecision(9) << showpoint;
-							*out << Trajectories[walker].R.at(step).x[0] << "\t" << Trajectories[walker].R.at(step).x[1] << "\t" << Trajectories[walker].R.at(step).x[2];
-							*out << "\t" << walker->FixedIon;
-							if (Trajectories[walker].U.at(step).Norm() > MYEPSILON)
-								*out << "\t" << scientific << setprecision(6) << Trajectories[walker].U.at(step).x[0] << "\t" << Trajectories[walker].U.at(step).x[1] << "\t" << Trajectories[walker].U.at(step).x[2] << "\t";
-							if (Trajectories[walker].F.at(step).Norm() > MYEPSILON)
-								*out << "\t" << scientific << setprecision(6) << Trajectories[walker].F.at(step).x[0] << "\t" << Trajectories[walker].F.at(step).x[1] << "\t" << Trajectories[walker].F.at(step).x[2] << "\t";
-							*out << "\t# Number in molecule " << walker->nr << endl;
-						}
-					}
-				}
-			}
-		}
-		return true;
-	}
+  atom *walker = NULL;
+  int ElementNo[MAX_ELEMENTS], AtomNo[MAX_ELEMENTS];
+  CountElements();
+
+  if (out == NULL) {
+    return false;
+  } else {
+    for (int step = 0; step < MDSteps; step++) {
+      if (step == 0) {
+        *out << "#Ion_TypeNr._Nr.R[0]    R[1]    R[2]    MoveType (0 MoveIon, 1 FixedIon)" << endl;
+      } else {
+        *out << "# ====== MD step " << step << " =========" << endl;
+      }
+      for (int i=0;i<MAX_ELEMENTS;++i) {
+        AtomNo[i] = 0;
+        ElementNo[i] = 0;
+      }
+    walker = start;
+    while (walker->next != end) { // go through every atom of this element
+      walker = walker->next;
+      ElementNo[walker->type->Z] = 1;
+    }
+    int current=1;
+    for (int i=0;i<MAX_ELEMENTS;++i) {
+      if (ElementNo[i] == 1)
+        ElementNo[i] = current++;
+    }
+    walker = start;
+      while (walker->next != end) { // go through every atom of this element
+        walker = walker->next;
+        AtomNo[walker->type->Z]++;
+        *out << "Ion_Type" << ElementNo[walker->type->Z] << "_" << AtomNo[walker->type->Z] << "\t"  << fixed << setprecision(9) << showpoint;
+        *out << Trajectories[walker].R.at(step).x[0] << "\t" << Trajectories[walker].R.at(step).x[1] << "\t" << Trajectories[walker].R.at(step).x[2];
+        *out << "\t" << walker->FixedIon;
+        if (Trajectories[walker].U.at(step).Norm() > MYEPSILON)
+          *out << "\t" << scientific << setprecision(6) << Trajectories[walker].U.at(step).x[0] << "\t" << Trajectories[walker].U.at(step).x[1] << "\t" << Trajectories[walker].U.at(step).x[2] << "\t";
+        if (Trajectories[walker].F.at(step).Norm() > MYEPSILON)
+          *out << "\t" << scientific << setprecision(6) << Trajectories[walker].F.at(step).x[0] << "\t" << Trajectories[walker].F.at(step).x[1] << "\t" << Trajectories[walker].F.at(step).x[2] << "\t";
+        *out << "\t# Number in molecule " << walker->nr << endl;
+      }
+    }
+    return true;
+  }
 };
 
@@ -1492,20 +2198,20 @@
 void molecule::OutputListOfBonds(ofstream *out) const
 {
-	*out << Verbose(2) << endl << "From Contents of ListOfBondsPerAtom, all non-hydrogen atoms:" << endl;
-	atom *Walker = start;
-	while (Walker->next != end) {
-		Walker = Walker->next;
+  *out << Verbose(2) << endl << "From Contents of ListOfBondsPerAtom, all non-hydrogen atoms:" << endl;
+  atom *Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
 #ifdef ADDHYDROGEN
-		if (Walker->type->Z != 1) {	 // regard only non-hydrogen
+    if (Walker->type->Z != 1) {   // regard only non-hydrogen
 #endif
-			*out << Verbose(2) << "Atom " << Walker->Name << " has Bonds: "<<endl;
-			for(int j=0;j<NumberOfBondsPerAtom[Walker->nr];j++) {
-				*out << Verbose(3) << *(ListOfBondsPerAtom)[Walker->nr][j] << endl;
-			}
+      *out << Verbose(2) << "Atom " << Walker->Name << " has Bonds: "<<endl;
+      for(int j=0;j<NumberOfBondsPerAtom[Walker->nr];j++) {
+        *out << Verbose(3) << *(ListOfBondsPerAtom)[Walker->nr][j] << endl;
+      }
 #ifdef ADDHYDROGEN
-		}
+    }
 #endif
-	}
-	*out << endl;
+  }
+  *out << endl;
 };
 
@@ -1513,7 +2219,7 @@
  * \param *out stream pointer
  */
-bool molecule::Checkout(ofstream *out)	const
-{
-	return elemente->Checkout(out, ElementsInMolecule);
+bool molecule::Checkout(ofstream *out)  const
+{
+  return elemente->Checkout(out, ElementsInMolecule);
 };
 
@@ -1523,26 +2229,26 @@
 bool molecule::OutputTrajectoriesXYZ(ofstream *out)
 {
-	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) {
-		for (int step=0;step<MDSteps;step++) {
-			*out << No << "\n\tCreated by molecuilder, step " << step << ", on " << ctime(&now);
-			walker = start;
-			while (walker->next != end) { // go through every atom of this element
-				walker = walker->next;
-				*out << walker->type->symbol << "\t" << Trajectories[walker].R.at(step).x[0] << "\t" << Trajectories[walker].R.at(step).x[1] << "\t" << Trajectories[walker].R.at(step).x[2] << endl;
-			}
-		}
-		return true;
-	} else
-		return false;
+  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) {
+    for (int step=0;step<MDSteps;step++) {
+      *out << No << "\n\tCreated by molecuilder, step " << step << ", on " << ctime(&now);
+      walker = start;
+      while (walker->next != end) { // go through every atom of this element
+        walker = walker->next;
+        *out << walker->type->symbol << "\t" << Trajectories[walker].R.at(step).x[0] << "\t" << Trajectories[walker].R.at(step).x[1] << "\t" << Trajectories[walker].R.at(step).x[2] << endl;
+      }
+    }
+    return true;
+  } else
+    return false;
 };
 
@@ -1552,35 +2258,24 @@
 bool molecule::OutputXYZ(ofstream *out) const
 {
-	atom *walker = NULL;
-	int AtomNo = 0, ElementNo;
-	time_t now;
-	element *runner = NULL;
-
-	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;
-		AtomNo++;
-	}
-	if (out != NULL) {
-		*out << AtomNo << "\n\tCreated by molecuilder on " << ctime(&now);
-		ElementNo = 0;
-		runner = elemente->start;
-		while (runner->next != elemente->end) { // go through every element
-			runner = runner->next;
-			if (ElementsInMolecule[runner->Z]) { // if this element got atoms
-				ElementNo++;
-				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
-						walker->OutputXYZLine(out);
-					}
-				}
-			}
-		}
-		return true;
-	} else
-		return false;
+  atom *walker = NULL;
+  int AtomNo = 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;
+    AtomNo++;
+  }
+  if (out != NULL) {
+    *out << AtomNo << "\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;
 };
 
@@ -1590,33 +2285,33 @@
 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;
-	}
+  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;
+  }
 };
 
@@ -1625,17 +2320,17 @@
 void molecule::CountElements()
 {
-	int i = 0;
-	for(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=MAX_ELEMENTS;i--;)
-		ElementCount += (ElementsInMolecule[i] != 0 ? 1 : 0);
+  int i = 0;
+  for(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=MAX_ELEMENTS;i--;)
+    ElementCount += (ElementsInMolecule[i] != 0 ? 1 : 0);
 };
 
@@ -1647,26 +2342,26 @@
 int molecule::CountCyclicBonds(ofstream *out)
 {
-	int No = 0;
-	int *MinimumRingSize = NULL;
-	MoleculeLeafClass *Subgraphs = NULL;
-	class StackClass<bond *> *BackEdgeStack = 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, BackEdgeStack);
-		while (Subgraphs->next != NULL) {
-			Subgraphs = Subgraphs->next;
-			delete(Subgraphs->previous);
-		}
-		delete(Subgraphs);
-		delete[](MinimumRingSize);
-	}
-	while(Binder->next != last) {
-		Binder = Binder->next;
-		if (Binder->Cyclic)
-			No++;
-	}
-	delete(BackEdgeStack);
-	return No;
+  int No = 0;
+  int *MinimumRingSize = NULL;
+  MoleculeLeafClass *Subgraphs = NULL;
+  class StackClass<bond *> *BackEdgeStack = 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, BackEdgeStack);
+    while (Subgraphs->next != NULL) {
+      Subgraphs = Subgraphs->next;
+      delete(Subgraphs->previous);
+    }
+    delete(Subgraphs);
+    delete[](MinimumRingSize);
+  }
+  while(Binder->next != last) {
+    Binder = Binder->next;
+    if (Binder->Cyclic)
+      No++;
+  }
+  delete(BackEdgeStack);
+  return No;
 };
 /** Returns Shading as a char string.
@@ -1676,21 +2371,21 @@
 string 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;
-	};
+  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;
+  };
 };
 
@@ -1701,23 +2396,23 @@
 void molecule::CalculateOrbitals(class config &configuration)
 {
-	configuration.MaxPsiDouble = configuration.PsiMaxNoDown = configuration.PsiMaxNoUp = configuration.PsiType = 0;
-	for(int 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;
+  configuration.MaxPsiDouble = configuration.PsiMaxNoDown = configuration.PsiMaxNoUp = configuration.PsiType = 0;
+  for(int 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;
 };
 
@@ -1728,42 +2423,42 @@
 {
 
-	// 1 We will parse bonds out of the dbond file created by tremolo.
-			int atom1, atom2, temp;
-			atom *Walker, *OtherWalker;
-
-					if (!input)
-					{
-						cout << Verbose(1) << "Opening silica failed \n";
-					};
-
-			*input >> ws >> atom1;
-			*input >> ws >> atom2;
-					cout << Verbose(1) << "Scanning file\n";
-					while (!input->eof()) // Check whether we read everything already
-					{
-				*input >> ws >> atom1;
-				*input >> ws >> atom2;
-						if(atom2<atom1) //Sort indices of atoms in order
-						{
-							temp=atom1;
-							atom1=atom2;
-							atom2=temp;
-						};
-
-						Walker=start;
-						while(Walker-> nr != atom1) // Find atom corresponding to first index
-						{
-							Walker = Walker->next;
-						};
-						OtherWalker = Walker->next;
-						while(OtherWalker->nr != atom2) // Find atom corresponding to second index
-						{
-							OtherWalker= OtherWalker->next;
-						};
-						AddBond(Walker, OtherWalker); //Add the bond between the two atoms with respective indices.
-
-					}
-
-					CreateListOfBondsPerAtom(out);
+  // 1 We will parse bonds out of the dbond file created by tremolo.
+      int atom1, atom2, temp;
+      atom *Walker, *OtherWalker;
+
+          if (!input)
+          {
+            cout << Verbose(1) << "Opening silica failed \n";
+          };
+
+      *input >> ws >> atom1;
+      *input >> ws >> atom2;
+          cout << Verbose(1) << "Scanning file\n";
+          while (!input->eof()) // Check whether we read everything already
+          {
+        *input >> ws >> atom1;
+        *input >> ws >> atom2;
+            if(atom2<atom1) //Sort indices of atoms in order
+            {
+              temp=atom1;
+              atom1=atom2;
+              atom2=temp;
+            };
+
+            Walker=start;
+            while(Walker-> nr != atom1) // Find atom corresponding to first index
+            {
+              Walker = Walker->next;
+            };
+            OtherWalker = Walker->next;
+            while(OtherWalker->nr != atom2) // Find atom corresponding to second index
+            {
+              OtherWalker= OtherWalker->next;
+            };
+            AddBond(Walker, OtherWalker); //Add the bond between the two atoms with respective indices.
+
+          }
+
+          CreateListOfBondsPerAtom(out);
 
 };
@@ -1776,12 +2471,12 @@
  * 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
+ *  -# 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)
@@ -1791,183 +2486,183 @@
 {
 
-	atom *Walker = NULL, *OtherWalker = NULL, *Candidate = NULL;
-	int No, NoBonds, CandidateBondNo;
-	int NumberCells, divisor[NDIM], n[NDIM], N[NDIM], index, Index, j;
-	molecule **CellList;
-	double distance, MinDistance, MaxDistance;
-	double *matrix = ReturnFullMatrixforSymmetric(cell_size);
-	Vector x;
-	int FalseBondDegree = 0;
-
-	BondDistance = bonddistance; // * ((IsAngstroem) ? 1. : 1./AtomicLengthToAngstroem);
-	*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=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]=divisor[0];N[0]--;)
-			for (N[1]=divisor[1];N[1]--;)
-				for (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.PeriodicDistanceSquared(&(Walker->x), cell_size) << " against typical bond length of " << bonddistance*bonddistance << "." << endl;
-												MinDistance = OtherWalker->type->CovalentRadius + Walker->type->CovalentRadius;
-												MinDistance *= (IsAngstroem) ? 1. : 1./AtomicLengthToAngstroem;
-												MaxDistance = MinDistance + BONDTHRESHOLD;
-												MinDistance -= BONDTHRESHOLD;
-												distance = OtherWalker->x.PeriodicDistanceSquared(&(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(1) << "Adding Bond between " << *Walker << " and " << *OtherWalker << " in distance " << sqrt(distance) << "." << 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=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 both bond partners for a mismatch between valence and current sum of bond degrees,
-		// iteratively increase the one first where the other bond partner has the fewest number of bonds (i.e. in general bonds oxygene
-		// preferred over carbon bonds). Beforehand, we had picked the first mismatching partner, which lead to oxygenes with single instead of
-		// double bonds as was expected.
-		if (BondCount != 0) {
-			NoCyclicBonds = 0;
-			*out << Verbose(1) << "Correcting Bond degree of each bond ... ";
-			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;
-					// count valence of first partner
-					NoBonds = 0;
-					for(j=0;j<NumberOfBondsPerAtom[Walker->nr];j++)
-						NoBonds += ListOfBondsPerAtom[Walker->nr][j]->BondDegree;
-					*out << Verbose(3) << "Walker " << *Walker << ": " << (int)Walker->type->NoValenceOrbitals << " > " << NoBonds << "?" << endl;
-					if ((int)(Walker->type->NoValenceOrbitals) > NoBonds) { // we have a mismatch, check all bonding partners for mismatch
-						Candidate = NULL;
-						CandidateBondNo = -1;
-						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 second partner
-							NoBonds = 0;
-							for(j=0;j<NumberOfBondsPerAtom[OtherWalker->nr];j++)
-								NoBonds += ListOfBondsPerAtom[OtherWalker->nr][j]->BondDegree;
-							*out << Verbose(3) << "OtherWalker " << *OtherWalker << ": " << (int)OtherWalker->type->NoValenceOrbitals << " > " << NoBonds << "?" << endl;
-							if ((int)(OtherWalker->type->NoValenceOrbitals) > NoBonds) { // check if possible candidate
-								if ((Candidate == NULL) || (NumberOfBondsPerAtom[Candidate->nr] > NumberOfBondsPerAtom[OtherWalker->nr])) { // pick the one with fewer number of bonds first
-									Candidate = OtherWalker;
-									CandidateBondNo = i;
-									*out << Verbose(3) << "New candidate is " << *Candidate << "." << endl;
-								}
-							}
-						}
-						if ((Candidate != NULL) && (CandidateBondNo != -1)) {
-							ListOfBondsPerAtom[Walker->nr][CandidateBondNo]->BondDegree++;
-							*out << Verbose(2) << "Increased bond degree for bond " << *ListOfBondsPerAtom[Walker->nr][CandidateBondNo] << "." << endl;
-						} else
-							*out << Verbose(2) << "Could not find correct degree for atom " << *Walker << "." << endl;
-							FalseBondDegree++;
-					}
-				}
-			} while (No);
-		*out << " done." << endl;
-		} 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 << ", " << FalseBondDegree << " bonds could not be corrected." << endl;
-
-		// output bonds for debugging (if bond chain list was correctly installed)
-		*out << Verbose(1) << endl << "From contents of bond chain list:";
-		bond *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");
+  atom *Walker = NULL, *OtherWalker = NULL, *Candidate = NULL;
+  int No, NoBonds, CandidateBondNo;
+  int NumberCells, divisor[NDIM], n[NDIM], N[NDIM], index, Index, j;
+  molecule **CellList;
+  double distance, MinDistance, MaxDistance;
+  double *matrix = ReturnFullMatrixforSymmetric(cell_size);
+  Vector x;
+  int FalseBondDegree = 0;
+
+  BondDistance = bonddistance; // * ((IsAngstroem) ? 1. : 1./AtomicLengthToAngstroem);
+  *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=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]=divisor[0];N[0]--;)
+      for (N[1]=divisor[1];N[1]--;)
+        for (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.PeriodicDistanceSquared(&(Walker->x), cell_size) << " against typical bond length of " << bonddistance*bonddistance << "." << endl;
+                        MinDistance = OtherWalker->type->CovalentRadius + Walker->type->CovalentRadius;
+                        MinDistance *= (IsAngstroem) ? 1. : 1./AtomicLengthToAngstroem;
+                        MaxDistance = MinDistance + BONDTHRESHOLD;
+                        MinDistance -= BONDTHRESHOLD;
+                        distance = OtherWalker->x.PeriodicDistanceSquared(&(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(1) << "Adding Bond between " << *Walker << " and " << *OtherWalker << " in distance " << sqrt(distance) << "." << 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=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 both bond partners for a mismatch between valence and current sum of bond degrees,
+    // iteratively increase the one first where the other bond partner has the fewest number of bonds (i.e. in general bonds oxygene
+    // preferred over carbon bonds). Beforehand, we had picked the first mismatching partner, which lead to oxygenes with single instead of
+    // double bonds as was expected.
+    if (BondCount != 0) {
+      NoCyclicBonds = 0;
+      *out << Verbose(1) << "Correcting Bond degree of each bond ... ";
+      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;
+          // count valence of first partner
+          NoBonds = 0;
+          for(j=0;j<NumberOfBondsPerAtom[Walker->nr];j++)
+            NoBonds += ListOfBondsPerAtom[Walker->nr][j]->BondDegree;
+          *out << Verbose(3) << "Walker " << *Walker << ": " << (int)Walker->type->NoValenceOrbitals << " > " << NoBonds << "?" << endl;
+          if ((int)(Walker->type->NoValenceOrbitals) > NoBonds) { // we have a mismatch, check all bonding partners for mismatch
+            Candidate = NULL;
+            CandidateBondNo = -1;
+            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 second partner
+              NoBonds = 0;
+              for(j=0;j<NumberOfBondsPerAtom[OtherWalker->nr];j++)
+                NoBonds += ListOfBondsPerAtom[OtherWalker->nr][j]->BondDegree;
+              *out << Verbose(3) << "OtherWalker " << *OtherWalker << ": " << (int)OtherWalker->type->NoValenceOrbitals << " > " << NoBonds << "?" << endl;
+              if ((int)(OtherWalker->type->NoValenceOrbitals) > NoBonds) { // check if possible candidate
+                if ((Candidate == NULL) || (NumberOfBondsPerAtom[Candidate->nr] > NumberOfBondsPerAtom[OtherWalker->nr])) { // pick the one with fewer number of bonds first
+                  Candidate = OtherWalker;
+                  CandidateBondNo = i;
+                  *out << Verbose(3) << "New candidate is " << *Candidate << "." << endl;
+                }
+              }
+            }
+            if ((Candidate != NULL) && (CandidateBondNo != -1)) {
+              ListOfBondsPerAtom[Walker->nr][CandidateBondNo]->BondDegree++;
+              *out << Verbose(2) << "Increased bond degree for bond " << *ListOfBondsPerAtom[Walker->nr][CandidateBondNo] << "." << endl;
+            } else
+              *out << Verbose(2) << "Could not find correct degree for atom " << *Walker << "." << endl;
+              FalseBondDegree++;
+          }
+        }
+      } while (No);
+    *out << " done." << endl;
+    } 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 << ", " << FalseBondDegree << " bonds could not be corrected." << endl;
+
+    // output bonds for debugging (if bond chain list was correctly installed)
+    *out << Verbose(1) << endl << "From contents of bond chain list:";
+    bond *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");
 
 };
@@ -1985,184 +2680,184 @@
 MoleculeLeafClass * molecule::DepthFirstSearchAnalysis(ofstream *out, class StackClass<bond *> *&BackEdgeStack)
 {
-	class StackClass<atom *> *AtomStack = new StackClass<atom *>(AtomCount);
-	BackEdgeStack = new StackClass<bond *> (BondCount);
-	MoleculeLeafClass *SubGraphs = new MoleculeLeafClass(NULL);
-	MoleculeLeafClass *LeafWalker = SubGraphs;
-	int CurrentGraphNr = 0, OldGraphNr;
-	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();
-	BackEdgeStack->ClearStack();
-	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;
-						BackEdgeStack->Push(Binder);
-						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++;
-		}
-	}
-
-
-	*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;
-	}
-
-	// free all and exit
-	delete(AtomStack);
-	*out << Verbose(0) << "End of DepthFirstSearchAnalysis" << endl;
-	return SubGraphs;
+  class StackClass<atom *> *AtomStack = new StackClass<atom *>(AtomCount);
+  BackEdgeStack = new StackClass<bond *> (BondCount);
+  MoleculeLeafClass *SubGraphs = new MoleculeLeafClass(NULL);
+  MoleculeLeafClass *LeafWalker = SubGraphs;
+  int CurrentGraphNr = 0, OldGraphNr;
+  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();
+  BackEdgeStack->ClearStack();
+  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;
+            BackEdgeStack->Push(Binder);
+            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++;
+    }
+  }
+
+
+  *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;
+  }
+
+  // free all and exit
+  delete(AtomStack);
+  *out << Verbose(0) << "End of DepthFirstSearchAnalysis" << endl;
+  return SubGraphs;
 };
 
@@ -2177,203 +2872,203 @@
  * \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, class StackClass<bond *> *	BackEdgeStack, int *&MinimumRingSize)
-{
-	atom **PredecessorList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::CyclicStructureAnalysis: **PredecessorList");
-	int *ShortestPathList = (int *) Malloc(sizeof(int)*AtomCount, "molecule::CyclicStructureAnalysis: *ShortestPathList");
-	enum Shading *ColorList = (enum Shading *) Malloc(sizeof(enum Shading)*AtomCount, "molecule::CyclicStructureAnalysis: *ColorList");
-	class StackClass<atom *> *BFSStack = new StackClass<atom *> (AtomCount);	 // will hold the current ring
-	class StackClass<atom *> *TouchedStack = new StackClass<atom *> (AtomCount);	 // contains all "touched" atoms (that need to be reset after BFS loop)
-	atom *Walker = NULL, *OtherAtom = NULL, *Root = NULL;
-	bond *Binder = NULL, *BackEdge = NULL;
-	int RingSize, NumCycles, MinRingSize = -1;
-
-	// initialise each vertex as white with no predecessor, empty queue, color Root lightgray
-	for (int i=AtomCount;i--;) {
-		PredecessorList[i] = NULL;
-		ShortestPathList[i] = -1;
-		ColorList[i] = white;
-	}
-
-	*out << Verbose(1) << "Back edge list - ";
-	BackEdgeStack->Output(out);
-
-	*out << Verbose(1) << "Analysing cycles ... " << endl;
-	NumCycles = 0;
-	while (!BackEdgeStack->IsEmpty()) {
-		BackEdge = BackEdgeStack->PopFirst();
-		// this is the target
-		Root = BackEdge->leftatom;
-		// this is the source point
-		Walker = BackEdge->rightatom;
-		ShortestPathList[Walker->nr] = 0;
-		BFSStack->ClearStack();	// start with empty BFS stack
-		BFSStack->Push(Walker);
-		TouchedStack->Push(Walker);
-		*out << Verbose(1) << "---------------------------------------------------------------------------------------------------------" << endl;
-		OtherAtom = NULL;
-		do {	// look for Root
-			Walker = BFSStack->PopFirst();
-			*out << Verbose(2) << "Current Walker is " << *Walker << ", we look for SP to Root " << *Root << "." << endl;
-			for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {
-				Binder = ListOfBondsPerAtom[Walker->nr][i];
-				if (Binder != BackEdge) { // only walk along DFS spanning tree (otherwise we always find SP of one being backedge Binder)
-					OtherAtom = Binder->GetOtherAtom(Walker);
+void molecule::CyclicStructureAnalysis(ofstream *out, class StackClass<bond *> *  BackEdgeStack, int *&MinimumRingSize)
+{
+  atom **PredecessorList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::CyclicStructureAnalysis: **PredecessorList");
+  int *ShortestPathList = (int *) Malloc(sizeof(int)*AtomCount, "molecule::CyclicStructureAnalysis: *ShortestPathList");
+  enum Shading *ColorList = (enum Shading *) Malloc(sizeof(enum Shading)*AtomCount, "molecule::CyclicStructureAnalysis: *ColorList");
+  class StackClass<atom *> *BFSStack = new StackClass<atom *> (AtomCount);   // will hold the current ring
+  class StackClass<atom *> *TouchedStack = new StackClass<atom *> (AtomCount);   // contains all "touched" atoms (that need to be reset after BFS loop)
+  atom *Walker = NULL, *OtherAtom = NULL, *Root = NULL;
+  bond *Binder = NULL, *BackEdge = NULL;
+  int RingSize, NumCycles, MinRingSize = -1;
+
+  // initialise each vertex as white with no predecessor, empty queue, color Root lightgray
+  for (int i=AtomCount;i--;) {
+    PredecessorList[i] = NULL;
+    ShortestPathList[i] = -1;
+    ColorList[i] = white;
+  }
+
+  *out << Verbose(1) << "Back edge list - ";
+  BackEdgeStack->Output(out);
+
+  *out << Verbose(1) << "Analysing cycles ... " << endl;
+  NumCycles = 0;
+  while (!BackEdgeStack->IsEmpty()) {
+    BackEdge = BackEdgeStack->PopFirst();
+    // this is the target
+    Root = BackEdge->leftatom;
+    // this is the source point
+    Walker = BackEdge->rightatom;
+    ShortestPathList[Walker->nr] = 0;
+    BFSStack->ClearStack();  // start with empty BFS stack
+    BFSStack->Push(Walker);
+    TouchedStack->Push(Walker);
+    *out << Verbose(1) << "---------------------------------------------------------------------------------------------------------" << endl;
+    OtherAtom = NULL;
+    do {  // look for Root
+      Walker = BFSStack->PopFirst();
+      *out << Verbose(2) << "Current Walker is " << *Walker << ", we look for SP to Root " << *Root << "." << endl;
+      for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {
+        Binder = ListOfBondsPerAtom[Walker->nr][i];
+        if (Binder != BackEdge) { // only walk along DFS spanning tree (otherwise we always find SP of one being backedge Binder)
+          OtherAtom = Binder->GetOtherAtom(Walker);
 #ifdef ADDHYDROGEN
-					if (OtherAtom->type->Z != 1) {
+          if (OtherAtom->type->Z != 1) {
 #endif
-						*out << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *Binder << "." << endl;
-						if (ColorList[OtherAtom->nr] == white) {
-							TouchedStack->Push(OtherAtom);
-							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 << " lightgray, its predecessor is " << Walker->Name << " and its Shortest Path is " << ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl;
-							//if (ShortestPathList[OtherAtom->nr] < MinimumRingSize[Walker->GetTrueFather()->nr]) { // Check for maximum distance
-								*out << Verbose(3) << "Putting OtherAtom into queue." << endl;
-								BFSStack->Push(OtherAtom);
-							//}
-						} else {
-							*out << Verbose(3) << "Not Adding, has already been visited." << endl;
-						}
-						if (OtherAtom == Root)
-							break;
+            *out << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *Binder << "." << endl;
+            if (ColorList[OtherAtom->nr] == white) {
+              TouchedStack->Push(OtherAtom);
+              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 << " lightgray, its predecessor is " << Walker->Name << " and its Shortest Path is " << ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl;
+              //if (ShortestPathList[OtherAtom->nr] < MinimumRingSize[Walker->GetTrueFather()->nr]) { // Check for maximum distance
+                *out << Verbose(3) << "Putting OtherAtom into queue." << endl;
+                BFSStack->Push(OtherAtom);
+              //}
+            } else {
+              *out << Verbose(3) << "Not Adding, has already been visited." << endl;
+            }
+            if (OtherAtom == Root)
+              break;
 #ifdef ADDHYDROGEN
-					} else {
-						*out << Verbose(2) << "Skipping hydrogen atom " << *OtherAtom << "." << endl;
-						ColorList[OtherAtom->nr] = black;
-					}
+          } else {
+            *out << Verbose(2) << "Skipping hydrogen atom " << *OtherAtom << "." << endl;
+            ColorList[OtherAtom->nr] = black;
+          }
 #endif
-				} else {
-					*out << Verbose(2) << "Bond " << *Binder << " not Visiting, is the back edge." << endl;
-				}
-			}
-			ColorList[Walker->nr] = black;
-			*out << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl;
-			if (OtherAtom == Root) { // if we have found the root, check whether this cycle wasn't already found beforehand
-				// step through predecessor list
-				while (OtherAtom != BackEdge->rightatom) {
-					if (!OtherAtom->GetTrueFather()->IsCyclic)	// if one bond in the loop is not marked as cyclic, we haven't found this cycle yet
-						break;
-					else
-						OtherAtom = PredecessorList[OtherAtom->nr];
-				}
-				if (OtherAtom == BackEdge->rightatom) { // if each atom in found cycle is cyclic, loop's been found before already
-					*out << Verbose(3) << "This cycle was already found before, skipping and removing seeker from search." << endl;\
-					do {
-						OtherAtom = TouchedStack->PopLast();
-						if (PredecessorList[OtherAtom->nr] == Walker) {
-							*out << Verbose(4) << "Removing " << *OtherAtom << " from lists and stacks." << endl;
-							PredecessorList[OtherAtom->nr] = NULL;
-							ShortestPathList[OtherAtom->nr] = -1;
-							ColorList[OtherAtom->nr] = white;
-							BFSStack->RemoveItem(OtherAtom);
-						}
-					} while ((!TouchedStack->IsEmpty()) && (PredecessorList[OtherAtom->nr] == NULL));
-					TouchedStack->Push(OtherAtom);	// last was wrongly popped
-					OtherAtom = BackEdge->rightatom; // set to not Root
-				} else
-					OtherAtom = Root;
-			}
-		} while ((!BFSStack->IsEmpty()) && (OtherAtom != Root) && (OtherAtom != NULL)); // || (ShortestPathList[OtherAtom->nr] < MinimumRingSize[Walker->GetTrueFather()->nr])));
-
-		if (OtherAtom == Root) {
-			// now climb back the predecessor list and thus find the cycle members
-			NumCycles++;
-			RingSize = 1;
-			Root->GetTrueFather()->IsCyclic = true;
-			*out << Verbose(1) << "Found ring contains: ";
-			Walker = Root;
-			while (Walker != BackEdge->rightatom) {
-				*out << Walker->Name << " <-> ";
-				Walker = PredecessorList[Walker->nr];
-				Walker->GetTrueFather()->IsCyclic = true;
-				RingSize++;
-			}
-			*out << Walker->Name << "	with a length of " << RingSize << "." << endl << endl;
-			// walk through all and set MinimumRingSize
-			Walker = Root;
-			MinimumRingSize[Walker->GetTrueFather()->nr] = RingSize;
-			while (Walker != BackEdge->rightatom) {
-				Walker = PredecessorList[Walker->nr];
-				if (RingSize < MinimumRingSize[Walker->GetTrueFather()->nr])
-					MinimumRingSize[Walker->GetTrueFather()->nr] = RingSize;
-			}
-			if ((RingSize < MinRingSize) || (MinRingSize == -1))
-				MinRingSize = RingSize;
-		} else {
-			*out << Verbose(1) << "No ring containing " << *Root << " with length equal to or smaller than " << MinimumRingSize[Walker->GetTrueFather()->nr] << " found." << endl;
-		}
-
-		// now clean the lists
-		while (!TouchedStack->IsEmpty()){
-			Walker = TouchedStack->PopFirst();
-			PredecessorList[Walker->nr] = NULL;
-			ShortestPathList[Walker->nr] = -1;
-			ColorList[Walker->nr] = white;
-		}
-	}
-	if (MinRingSize != -1) {
-		// go over all atoms
-		Root = start;
-		while(Root->next != end) {
-			Root = Root->next;
-
-			if (MinimumRingSize[Root->GetTrueFather()->nr] == AtomCount) { // check whether MinimumRingSize is set, if not BFS to next where it is
-				Walker = Root;
-				ShortestPathList[Walker->nr] = 0;
-				BFSStack->ClearStack();	// start with empty BFS stack
-				BFSStack->Push(Walker);
-				TouchedStack->Push(Walker);
-				//*out << Verbose(1) << "---------------------------------------------------------------------------------------------------------" << endl;
-				OtherAtom = Walker;
-				while (OtherAtom != NULL) {	// look for Root
-					Walker = BFSStack->PopFirst();
-					//*out << Verbose(2) << "Current Walker is " << *Walker << ", we look for SP to Root " << *Root << "." << endl;
-					for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {
-						Binder = ListOfBondsPerAtom[Walker->nr][i];
-						if ((Binder != BackEdge) || (NumberOfBondsPerAtom[Walker->nr] == 1)) { // only walk along DFS spanning tree (otherwise we always find SP of 1 being backedge Binder), but terminal hydrogens may be connected via backedge, hence extra check
-							OtherAtom = Binder->GetOtherAtom(Walker);
-							//*out << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *Binder << "." << endl;
-							if (ColorList[OtherAtom->nr] == white) {
-								TouchedStack->Push(OtherAtom);
-								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 << " lightgray, its predecessor is " << Walker->Name << " and its Shortest Path is " << ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl;
-								if (OtherAtom->GetTrueFather()->IsCyclic) { // if the other atom is connected to a ring
-									MinimumRingSize[Root->GetTrueFather()->nr] = ShortestPathList[OtherAtom->nr]+MinimumRingSize[OtherAtom->GetTrueFather()->nr];
-									OtherAtom = NULL; //break;
-									break;
-								} else
-									BFSStack->Push(OtherAtom);
-							} else {
-								//*out << Verbose(3) << "Not Adding, has already been visited." << endl;
-							}
-						} else {
-							//*out << Verbose(3) << "Not Visiting, is a back edge." << endl;
-						}
-					}
-					ColorList[Walker->nr] = black;
-					//*out << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl;
-				}
-
-				// now clean the lists
-				while (!TouchedStack->IsEmpty()){
-					Walker = TouchedStack->PopFirst();
-					PredecessorList[Walker->nr] = NULL;
-					ShortestPathList[Walker->nr] = -1;
-					ColorList[Walker->nr] = white;
-				}
-			}
-			*out << Verbose(1) << "Minimum ring size of " << *Root << " is " << MinimumRingSize[Root->GetTrueFather()->nr] << "." << endl;
-		}
-		*out << Verbose(1) << "Minimum ring size is " << MinRingSize << ", over " << NumCycles << " cycles total." << endl;
-	} else
-		*out << Verbose(1) << "No rings were detected in the molecular structure." << endl;
-
-	Free((void **)&PredecessorList, "molecule::CyclicStructureAnalysis: **PredecessorList");
-	Free((void **)&ShortestPathList, "molecule::CyclicStructureAnalysis: **ShortestPathList");
-	Free((void **)&ColorList, "molecule::CyclicStructureAnalysis: **ColorList");
-	delete(BFSStack);
+        } else {
+          *out << Verbose(2) << "Bond " << *Binder << " not Visiting, is the back edge." << endl;
+        }
+      }
+      ColorList[Walker->nr] = black;
+      *out << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl;
+      if (OtherAtom == Root) { // if we have found the root, check whether this cycle wasn't already found beforehand
+        // step through predecessor list
+        while (OtherAtom != BackEdge->rightatom) {
+          if (!OtherAtom->GetTrueFather()->IsCyclic)  // if one bond in the loop is not marked as cyclic, we haven't found this cycle yet
+            break;
+          else
+            OtherAtom = PredecessorList[OtherAtom->nr];
+        }
+        if (OtherAtom == BackEdge->rightatom) { // if each atom in found cycle is cyclic, loop's been found before already
+          *out << Verbose(3) << "This cycle was already found before, skipping and removing seeker from search." << endl;\
+          do {
+            OtherAtom = TouchedStack->PopLast();
+            if (PredecessorList[OtherAtom->nr] == Walker) {
+              *out << Verbose(4) << "Removing " << *OtherAtom << " from lists and stacks." << endl;
+              PredecessorList[OtherAtom->nr] = NULL;
+              ShortestPathList[OtherAtom->nr] = -1;
+              ColorList[OtherAtom->nr] = white;
+              BFSStack->RemoveItem(OtherAtom);
+            }
+          } while ((!TouchedStack->IsEmpty()) && (PredecessorList[OtherAtom->nr] == NULL));
+          TouchedStack->Push(OtherAtom);  // last was wrongly popped
+          OtherAtom = BackEdge->rightatom; // set to not Root
+        } else
+          OtherAtom = Root;
+      }
+    } while ((!BFSStack->IsEmpty()) && (OtherAtom != Root) && (OtherAtom != NULL)); // || (ShortestPathList[OtherAtom->nr] < MinimumRingSize[Walker->GetTrueFather()->nr])));
+
+    if (OtherAtom == Root) {
+      // now climb back the predecessor list and thus find the cycle members
+      NumCycles++;
+      RingSize = 1;
+      Root->GetTrueFather()->IsCyclic = true;
+      *out << Verbose(1) << "Found ring contains: ";
+      Walker = Root;
+      while (Walker != BackEdge->rightatom) {
+        *out << Walker->Name << " <-> ";
+        Walker = PredecessorList[Walker->nr];
+        Walker->GetTrueFather()->IsCyclic = true;
+        RingSize++;
+      }
+      *out << Walker->Name << "  with a length of " << RingSize << "." << endl << endl;
+      // walk through all and set MinimumRingSize
+      Walker = Root;
+      MinimumRingSize[Walker->GetTrueFather()->nr] = RingSize;
+      while (Walker != BackEdge->rightatom) {
+        Walker = PredecessorList[Walker->nr];
+        if (RingSize < MinimumRingSize[Walker->GetTrueFather()->nr])
+          MinimumRingSize[Walker->GetTrueFather()->nr] = RingSize;
+      }
+      if ((RingSize < MinRingSize) || (MinRingSize == -1))
+        MinRingSize = RingSize;
+    } else {
+      *out << Verbose(1) << "No ring containing " << *Root << " with length equal to or smaller than " << MinimumRingSize[Walker->GetTrueFather()->nr] << " found." << endl;
+    }
+
+    // now clean the lists
+    while (!TouchedStack->IsEmpty()){
+      Walker = TouchedStack->PopFirst();
+      PredecessorList[Walker->nr] = NULL;
+      ShortestPathList[Walker->nr] = -1;
+      ColorList[Walker->nr] = white;
+    }
+  }
+  if (MinRingSize != -1) {
+    // go over all atoms
+    Root = start;
+    while(Root->next != end) {
+      Root = Root->next;
+
+      if (MinimumRingSize[Root->GetTrueFather()->nr] == AtomCount) { // check whether MinimumRingSize is set, if not BFS to next where it is
+        Walker = Root;
+        ShortestPathList[Walker->nr] = 0;
+        BFSStack->ClearStack();  // start with empty BFS stack
+        BFSStack->Push(Walker);
+        TouchedStack->Push(Walker);
+        //*out << Verbose(1) << "---------------------------------------------------------------------------------------------------------" << endl;
+        OtherAtom = Walker;
+        while (OtherAtom != NULL) {  // look for Root
+          Walker = BFSStack->PopFirst();
+          //*out << Verbose(2) << "Current Walker is " << *Walker << ", we look for SP to Root " << *Root << "." << endl;
+          for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {
+            Binder = ListOfBondsPerAtom[Walker->nr][i];
+            if ((Binder != BackEdge) || (NumberOfBondsPerAtom[Walker->nr] == 1)) { // only walk along DFS spanning tree (otherwise we always find SP of 1 being backedge Binder), but terminal hydrogens may be connected via backedge, hence extra check
+              OtherAtom = Binder->GetOtherAtom(Walker);
+              //*out << Verbose(2) << "Current OtherAtom is: " << OtherAtom->Name << " for bond " << *Binder << "." << endl;
+              if (ColorList[OtherAtom->nr] == white) {
+                TouchedStack->Push(OtherAtom);
+                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 << " lightgray, its predecessor is " << Walker->Name << " and its Shortest Path is " << ShortestPathList[OtherAtom->nr] << " egde(s) long." << endl;
+                if (OtherAtom->GetTrueFather()->IsCyclic) { // if the other atom is connected to a ring
+                  MinimumRingSize[Root->GetTrueFather()->nr] = ShortestPathList[OtherAtom->nr]+MinimumRingSize[OtherAtom->GetTrueFather()->nr];
+                  OtherAtom = NULL; //break;
+                  break;
+                } else
+                  BFSStack->Push(OtherAtom);
+              } else {
+                //*out << Verbose(3) << "Not Adding, has already been visited." << endl;
+              }
+            } else {
+              //*out << Verbose(3) << "Not Visiting, is a back edge." << endl;
+            }
+          }
+          ColorList[Walker->nr] = black;
+          //*out << Verbose(1) << "Coloring Walker " << Walker->Name << " black." << endl;
+        }
+
+        // now clean the lists
+        while (!TouchedStack->IsEmpty()){
+          Walker = TouchedStack->PopFirst();
+          PredecessorList[Walker->nr] = NULL;
+          ShortestPathList[Walker->nr] = -1;
+          ColorList[Walker->nr] = white;
+        }
+      }
+      *out << Verbose(1) << "Minimum ring size of " << *Root << " is " << MinimumRingSize[Root->GetTrueFather()->nr] << "." << endl;
+    }
+    *out << Verbose(1) << "Minimum ring size is " << MinRingSize << ", over " << NumCycles << " cycles total." << endl;
+  } else
+    *out << Verbose(1) << "No rings were detected in the molecular structure." << endl;
+
+  Free((void **)&PredecessorList, "molecule::CyclicStructureAnalysis: **PredecessorList");
+  Free((void **)&ShortestPathList, "molecule::CyclicStructureAnalysis: **ShortestPathList");
+  Free((void **)&ColorList, "molecule::CyclicStructureAnalysis: **ColorList");
+  delete(BFSStack);
 };
 
@@ -2385,18 +3080,18 @@
 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;
+  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;
 };
 
@@ -2406,6 +3101,6 @@
 void molecule::OutputComponentNumber(ofstream *out, atom *vertex)
 {
-	for(int i=0;i<NumberOfBondsPerAtom[vertex->nr];i++)
-		*out << vertex->ComponentNr[i] << "	";
+  for(int i=0;i<NumberOfBondsPerAtom[vertex->nr];i++)
+    *out << vertex->ComponentNr[i] << "  ";
 };
 
@@ -2414,13 +3109,13 @@
 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=NumberOfBondsPerAtom[Walker->nr];i--;)
-			Walker->ComponentNr[i] = -1;
-	}
+  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=NumberOfBondsPerAtom[Walker->nr];i--;)
+      Walker->ComponentNr[i] = -1;
+  }
 };
 
@@ -2431,8 +3126,8 @@
 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;
+  for(int i=0;i<NumberOfBondsPerAtom[vertex->nr];i++)
+    if (ListOfBondsPerAtom[vertex->nr][i]->IsUsed() == white)
+      return(ListOfBondsPerAtom[vertex->nr][i]);
+  return NULL;
 };
 
@@ -2442,9 +3137,9 @@
 void molecule::ResetAllBondsToUnused()
 {
-	bond *Binder = first;
-	while (Binder->next != last) {
-		Binder = Binder->next;
-		Binder->ResetUsed();
-	}
+  bond *Binder = first;
+  while (Binder->next != last) {
+    Binder = Binder->next;
+    Binder->ResetUsed();
+  }
 };
 
@@ -2453,9 +3148,9 @@
 void molecule::ResetAllAtomNumbers()
 {
-	atom *Walker = start;
-	while (Walker->next != end) {
-		Walker = Walker->next;
-		Walker->GraphNr	= -1;
-	}
+  atom *Walker = start;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    Walker->GraphNr  = -1;
+  }
 };
 
@@ -2466,7 +3161,7 @@
 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;
+  *out << Verbose(4) << "Already Visited Bonds:\t";
+  for(int i=1;i<=list[0];i++) *out << Verbose(0) << list[i] << "  ";
+  *out << endl;
 };
 
@@ -2474,5 +3169,5 @@
  * The upper limit is
  * \f[
- *	n = N \cdot C^k
+ *  n = N \cdot C^k
  * \f]
  * where \f$C=2^c\f$ and c is the maximum bond degree over N number of atoms.
@@ -2483,15 +3178,15 @@
 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;
+  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;
 };
 
@@ -2504,22 +3199,22 @@
 bool molecule::ScanBufferIntoKeySet(ofstream *out, char *buffer, KeySet &CurrentSet)
 {
-	stringstream line;
-	int AtomNr;
-	int status = 0;
-
-	line.str(buffer);
-	while (!line.eof()) {
-		line >> AtomNr;
-		if ((AtomNr >= 0) && (AtomNr < AtomCount)) {
-			CurrentSet.insert(AtomNr);	// insert at end, hence in same order as in file!
-			status++;
-		} // else it's "-1" or else and thus must not be added
-	}
-	*out << Verbose(1) << "The scanned KeySet is ";
-	for(KeySet::iterator runner = CurrentSet.begin(); runner != CurrentSet.end(); runner++) {
-		*out << (*runner) << "\t";
-	}
-	*out << endl;
-	return (status != 0);
+  stringstream line;
+  int AtomNr;
+  int status = 0;
+
+  line.str(buffer);
+  while (!line.eof()) {
+    line >> AtomNr;
+    if ((AtomNr >= 0) && (AtomNr < AtomCount)) {
+      CurrentSet.insert(AtomNr);  // insert at end, hence in same order as in file!
+      status++;
+    } // else it's "-1" or else and thus must not be added
+  }
+  *out << Verbose(1) << "The scanned KeySet is ";
+  for(KeySet::iterator runner = CurrentSet.begin(); runner != CurrentSet.end(); runner++) {
+    *out << (*runner) << "\t";
+  }
+  *out << endl;
+  return (status != 0);
 };
 
@@ -2536,73 +3231,73 @@
 bool molecule::ParseKeySetFile(ofstream *out, char *path, Graph *&FragmentList)
 {
-	bool status = true;
-	ifstream InputFile;
-	stringstream line;
-	GraphTestPair testGraphInsert;
-	int NumberOfFragments = 0;
-	double TEFactor;
-	char *filename = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "molecule::ParseKeySetFile - filename");
-
-	if (FragmentList == NULL) { // check list pointer
-		FragmentList = new Graph;
-	}
-
-	// 1st pass: open file and read
-	*out << Verbose(1) << "Parsing the KeySet file ... " << endl;
-	sprintf(filename, "%s/%s%s", path, FRAGMENTPREFIX, KEYSETFILE);
-	InputFile.open(filename);
-	if (InputFile != NULL) {
-		// each line represents a new fragment
-		char *buffer = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "molecule::ParseKeySetFile - *buffer");
-		// 1. parse keysets and insert into temp. graph
-		while (!InputFile.eof()) {
-			InputFile.getline(buffer, MAXSTRINGSIZE);
-			KeySet CurrentSet;
-			if ((strlen(buffer) > 0) && (ScanBufferIntoKeySet(out, buffer, CurrentSet))) {	// if at least one valid atom was added, write config
-				testGraphInsert = FragmentList->insert(GraphPair (CurrentSet,pair<int,double>(NumberOfFragments++,1)));	// store fragment number and current factor
-				if (!testGraphInsert.second) {
-					cerr << "KeySet file must be corrupt as there are two equal key sets therein!" << endl;
-				}
-			}
-		}
-		// 2. Free and done
-		InputFile.close();
-		InputFile.clear();
-		Free((void **)&buffer, "molecule::ParseKeySetFile - *buffer");
-		*out << Verbose(1) << "done." << endl;
-	} else {
-		*out << Verbose(1) << "File " << filename << " not found." << endl;
-		status = false;
-	}
-
-	// 2nd pass: open TEFactors file and read
-	*out << Verbose(1) << "Parsing the TEFactors file ... " << endl;
-	sprintf(filename, "%s/%s%s", path, FRAGMENTPREFIX, TEFACTORSFILE);
-	InputFile.open(filename);
-	if (InputFile != NULL) {
-		// 3. add found TEFactors to each keyset
-		NumberOfFragments = 0;
-		for(Graph::iterator runner = FragmentList->begin();runner != FragmentList->end(); runner++) {
-			if (!InputFile.eof()) {
-				InputFile >> TEFactor;
-				(*runner).second.second = TEFactor;
-				*out << Verbose(2) << "Setting " << ++NumberOfFragments << " fragment's TEFactor to " << (*runner).second.second << "." << endl;
-			} else {
-				status = false;
-				break;
-			}
-		}
-		// 4. Free and done
-		InputFile.close();
-		*out << Verbose(1) << "done." << endl;
-	} else {
-		*out << Verbose(1) << "File " << filename << " not found." << endl;
-		status = false;
-	}
-
-	// free memory
-	Free((void **)&filename, "molecule::ParseKeySetFile - filename");
-
-	return status;
+  bool status = true;
+  ifstream InputFile;
+  stringstream line;
+  GraphTestPair testGraphInsert;
+  int NumberOfFragments = 0;
+  double TEFactor;
+  char *filename = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "molecule::ParseKeySetFile - filename");
+
+  if (FragmentList == NULL) { // check list pointer
+    FragmentList = new Graph;
+  }
+
+  // 1st pass: open file and read
+  *out << Verbose(1) << "Parsing the KeySet file ... " << endl;
+  sprintf(filename, "%s/%s%s", path, FRAGMENTPREFIX, KEYSETFILE);
+  InputFile.open(filename);
+  if (InputFile != NULL) {
+    // each line represents a new fragment
+    char *buffer = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "molecule::ParseKeySetFile - *buffer");
+    // 1. parse keysets and insert into temp. graph
+    while (!InputFile.eof()) {
+      InputFile.getline(buffer, MAXSTRINGSIZE);
+      KeySet CurrentSet;
+      if ((strlen(buffer) > 0) && (ScanBufferIntoKeySet(out, buffer, CurrentSet))) {  // if at least one valid atom was added, write config
+        testGraphInsert = FragmentList->insert(GraphPair (CurrentSet,pair<int,double>(NumberOfFragments++,1)));  // store fragment number and current factor
+        if (!testGraphInsert.second) {
+          cerr << "KeySet file must be corrupt as there are two equal key sets therein!" << endl;
+        }
+      }
+    }
+    // 2. Free and done
+    InputFile.close();
+    InputFile.clear();
+    Free((void **)&buffer, "molecule::ParseKeySetFile - *buffer");
+    *out << Verbose(1) << "done." << endl;
+  } else {
+    *out << Verbose(1) << "File " << filename << " not found." << endl;
+    status = false;
+  }
+
+  // 2nd pass: open TEFactors file and read
+  *out << Verbose(1) << "Parsing the TEFactors file ... " << endl;
+  sprintf(filename, "%s/%s%s", path, FRAGMENTPREFIX, TEFACTORSFILE);
+  InputFile.open(filename);
+  if (InputFile != NULL) {
+    // 3. add found TEFactors to each keyset
+    NumberOfFragments = 0;
+    for(Graph::iterator runner = FragmentList->begin();runner != FragmentList->end(); runner++) {
+      if (!InputFile.eof()) {
+        InputFile >> TEFactor;
+        (*runner).second.second = TEFactor;
+        *out << Verbose(2) << "Setting " << ++NumberOfFragments << " fragment's TEFactor to " << (*runner).second.second << "." << endl;
+      } else {
+        status = false;
+        break;
+      }
+    }
+    // 4. Free and done
+    InputFile.close();
+    *out << Verbose(1) << "done." << endl;
+  } else {
+    *out << Verbose(1) << "File " << filename << " not found." << endl;
+    status = false;
+  }
+
+  // free memory
+  Free((void **)&filename, "molecule::ParseKeySetFile - filename");
+
+  return status;
 };
 
@@ -2615,50 +3310,50 @@
 bool molecule::StoreKeySetFile(ofstream *out, Graph &KeySetList, char *path)
 {
-	ofstream output;
-	bool status =	true;
-	string line;
-
-	// open KeySet file
-	line = path;
-	line.append("/");
-	line += FRAGMENTPREFIX;
-	line += KEYSETFILE;
-	output.open(line.c_str(), ios::out);
-	*out << Verbose(1) << "Saving key sets of the total graph ... ";
-	if(output != NULL) {
-		for(Graph::iterator runner = KeySetList.begin(); runner != KeySetList.end(); runner++) {
-			for (KeySet::iterator sprinter = (*runner).first.begin();sprinter != (*runner).first.end(); sprinter++) {
-				if (sprinter != (*runner).first.begin())
-					output << "\t";
-				output << *sprinter;
-			}
-			output << endl;
-		}
-		*out << "done." << endl;
-	} else {
-		cerr << "Unable to open " << line << " for writing keysets!" << endl;
-		status = false;
-	}
-	output.close();
-	output.clear();
-
-	// open TEFactors file
-	line = path;
-	line.append("/");
-	line += FRAGMENTPREFIX;
-	line += TEFACTORSFILE;
-	output.open(line.c_str(), ios::out);
-	*out << Verbose(1) << "Saving TEFactors of the total graph ... ";
-	if(output != NULL) {
-		for(Graph::iterator runner = KeySetList.begin(); runner != KeySetList.end(); runner++)
-			output << (*runner).second.second << endl;
-		*out << Verbose(1) << "done." << endl;
-	} else {
-		*out << Verbose(1) << "failed to open " << line << "." << endl;
-		status = false;
-	}
-	output.close();
-
-	return status;
+  ofstream output;
+  bool status =  true;
+  string line;
+
+  // open KeySet file
+  line = path;
+  line.append("/");
+  line += FRAGMENTPREFIX;
+  line += KEYSETFILE;
+  output.open(line.c_str(), ios::out);
+  *out << Verbose(1) << "Saving key sets of the total graph ... ";
+  if(output != NULL) {
+    for(Graph::iterator runner = KeySetList.begin(); runner != KeySetList.end(); runner++) {
+      for (KeySet::iterator sprinter = (*runner).first.begin();sprinter != (*runner).first.end(); sprinter++) {
+        if (sprinter != (*runner).first.begin())
+          output << "\t";
+        output << *sprinter;
+      }
+      output << endl;
+    }
+    *out << "done." << endl;
+  } else {
+    cerr << "Unable to open " << line << " for writing keysets!" << endl;
+    status = false;
+  }
+  output.close();
+  output.clear();
+
+  // open TEFactors file
+  line = path;
+  line.append("/");
+  line += FRAGMENTPREFIX;
+  line += TEFACTORSFILE;
+  output.open(line.c_str(), ios::out);
+  *out << Verbose(1) << "Saving TEFactors of the total graph ... ";
+  if(output != NULL) {
+    for(Graph::iterator runner = KeySetList.begin(); runner != KeySetList.end(); runner++)
+      output << (*runner).second.second << endl;
+    *out << Verbose(1) << "done." << endl;
+  } else {
+    *out << Verbose(1) << "failed to open " << line << "." << endl;
+    status = false;
+  }
+  output.close();
+
+  return status;
 };
 
@@ -2671,29 +3366,29 @@
 bool molecule::StoreAdjacencyToFile(ofstream *out, char *path)
 {
-	ofstream AdjacencyFile;
-	atom *Walker = NULL;
-	stringstream line;
-	bool status = true;
-
-	line << path << "/" << FRAGMENTPREFIX << ADJACENCYFILE;
-	AdjacencyFile.open(line.str().c_str(), ios::out);
-	*out << Verbose(1) << "Saving adjacency list ... ";
-	if (AdjacencyFile != NULL) {
-		Walker = start;
-		while(Walker->next != end) {
-			Walker = Walker->next;
-			AdjacencyFile << Walker->nr << "\t";
-			for (int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++)
-				AdjacencyFile << ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker)->nr << "\t";
-			AdjacencyFile << endl;
-		}
-		AdjacencyFile.close();
-		*out << Verbose(1) << "done." << endl;
-	} else {
-		*out << Verbose(1) << "failed to open file " << line.str() << "." << endl;
-		status = false;
-	}
-
-	return status;
+  ofstream AdjacencyFile;
+  atom *Walker = NULL;
+  stringstream line;
+  bool status = true;
+
+  line << path << "/" << FRAGMENTPREFIX << ADJACENCYFILE;
+  AdjacencyFile.open(line.str().c_str(), ios::out);
+  *out << Verbose(1) << "Saving adjacency list ... ";
+  if (AdjacencyFile != NULL) {
+    Walker = start;
+    while(Walker->next != end) {
+      Walker = Walker->next;
+      AdjacencyFile << Walker->nr << "\t";
+      for (int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++)
+        AdjacencyFile << ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker)->nr << "\t";
+      AdjacencyFile << endl;
+    }
+    AdjacencyFile.close();
+    *out << Verbose(1) << "done." << endl;
+  } else {
+    *out << Verbose(1) << "failed to open file " << line.str() << "." << endl;
+    status = false;
+  }
+
+  return status;
 };
 
@@ -2706,69 +3401,69 @@
 bool molecule::CheckAdjacencyFileAgainstMolecule(ofstream *out, char *path, atom **ListOfAtoms)
 {
-	ifstream File;
-	stringstream filename;
-	bool status = true;
-	char *buffer = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "molecule::CheckAdjacencyFileAgainstMolecule: *buffer");
-
-	filename << path << "/" << FRAGMENTPREFIX << ADJACENCYFILE;
-	File.open(filename.str().c_str(), ios::out);
-	*out << Verbose(1) << "Looking at bond structure stored in adjacency file and comparing to present one ... ";
-	if (File != NULL) {
-		// allocate storage structure
-		int NonMatchNumber = 0;	 // will number of atoms with differing bond structure
-		int *CurrentBonds = (int *) Malloc(sizeof(int)*8, "molecule::CheckAdjacencyFileAgainstMolecule - CurrentBonds"); // contains parsed bonds of current atom
-		int CurrentBondsOfAtom;
-
-		// Parse the file line by line and count the bonds
-		while (!File.eof()) {
-			File.getline(buffer, MAXSTRINGSIZE);
-			stringstream line;
-			line.str(buffer);
-			int AtomNr = -1;
-			line >> AtomNr;
-			CurrentBondsOfAtom = -1; // we count one too far due to line end
-			// parse into structure
-			if ((AtomNr >= 0) && (AtomNr < AtomCount)) {
-				while (!line.eof())
-					line >> CurrentBonds[ ++CurrentBondsOfAtom ];
-				// compare against present bonds
-				//cout << Verbose(2) << "Walker is " << *Walker << ", bond partners: ";
-				if (CurrentBondsOfAtom == NumberOfBondsPerAtom[AtomNr]) {
-					for(int i=0;i<NumberOfBondsPerAtom[AtomNr];i++) {
-						int id = ListOfBondsPerAtom[AtomNr][i]->GetOtherAtom(ListOfAtoms[AtomNr])->nr;
-						int j = 0;
-						for (;(j<CurrentBondsOfAtom) && (CurrentBonds[j++] != id);); // check against all parsed bonds
-						if (CurrentBonds[j-1] != id) { // no match ? Then mark in ListOfAtoms
-							ListOfAtoms[AtomNr] = NULL;
-							NonMatchNumber++;
-							status = false;
-							//out << "[" << id << "]\t";
-						} else {
-							//out << id << "\t";
-						}
-					}
-					//out << endl;
-				} else {
-					*out << "Number of bonds for Atom " << *ListOfAtoms[AtomNr] << " does not match, parsed " << CurrentBondsOfAtom << " against " << NumberOfBondsPerAtom[AtomNr] << "." << endl;
-					status = false;
-				}
-			}
-		}
-		File.close();
-		File.clear();
-		if (status) { // if equal we parse the KeySetFile
-			*out << Verbose(1) << "done: Equal." << endl;
-			status = true;
-		} else
-			*out << Verbose(1) << "done: Not equal by " << NonMatchNumber << " atoms." << endl;
-		Free((void **)&CurrentBonds, "molecule::CheckAdjacencyFileAgainstMolecule - **CurrentBonds");
-	} else {
-		*out << Verbose(1) << "Adjacency file not found." << endl;
-		status = false;
-	}
-	*out << endl;
-	Free((void **)&buffer, "molecule::CheckAdjacencyFileAgainstMolecule: *buffer");
-
-	return status;
+  ifstream File;
+  stringstream filename;
+  bool status = true;
+  char *buffer = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "molecule::CheckAdjacencyFileAgainstMolecule: *buffer");
+
+  filename << path << "/" << FRAGMENTPREFIX << ADJACENCYFILE;
+  File.open(filename.str().c_str(), ios::out);
+  *out << Verbose(1) << "Looking at bond structure stored in adjacency file and comparing to present one ... ";
+  if (File != NULL) {
+    // allocate storage structure
+    int NonMatchNumber = 0;   // will number of atoms with differing bond structure
+    int *CurrentBonds = (int *) Malloc(sizeof(int)*8, "molecule::CheckAdjacencyFileAgainstMolecule - CurrentBonds"); // contains parsed bonds of current atom
+    int CurrentBondsOfAtom;
+
+    // Parse the file line by line and count the bonds
+    while (!File.eof()) {
+      File.getline(buffer, MAXSTRINGSIZE);
+      stringstream line;
+      line.str(buffer);
+      int AtomNr = -1;
+      line >> AtomNr;
+      CurrentBondsOfAtom = -1; // we count one too far due to line end
+      // parse into structure
+      if ((AtomNr >= 0) && (AtomNr < AtomCount)) {
+        while (!line.eof())
+          line >> CurrentBonds[ ++CurrentBondsOfAtom ];
+        // compare against present bonds
+        //cout << Verbose(2) << "Walker is " << *Walker << ", bond partners: ";
+        if (CurrentBondsOfAtom == NumberOfBondsPerAtom[AtomNr]) {
+          for(int i=0;i<NumberOfBondsPerAtom[AtomNr];i++) {
+            int id = ListOfBondsPerAtom[AtomNr][i]->GetOtherAtom(ListOfAtoms[AtomNr])->nr;
+            int j = 0;
+            for (;(j<CurrentBondsOfAtom) && (CurrentBonds[j++] != id);); // check against all parsed bonds
+            if (CurrentBonds[j-1] != id) { // no match ? Then mark in ListOfAtoms
+              ListOfAtoms[AtomNr] = NULL;
+              NonMatchNumber++;
+              status = false;
+              //out << "[" << id << "]\t";
+            } else {
+              //out << id << "\t";
+            }
+          }
+          //out << endl;
+        } else {
+          *out << "Number of bonds for Atom " << *ListOfAtoms[AtomNr] << " does not match, parsed " << CurrentBondsOfAtom << " against " << NumberOfBondsPerAtom[AtomNr] << "." << endl;
+          status = false;
+        }
+      }
+    }
+    File.close();
+    File.clear();
+    if (status) { // if equal we parse the KeySetFile
+      *out << Verbose(1) << "done: Equal." << endl;
+      status = true;
+    } else
+      *out << Verbose(1) << "done: Not equal by " << NonMatchNumber << " atoms." << endl;
+    Free((void **)&CurrentBonds, "molecule::CheckAdjacencyFileAgainstMolecule - **CurrentBonds");
+  } else {
+    *out << Verbose(1) << "Adjacency file not found." << endl;
+    status = false;
+  }
+  *out << endl;
+  Free((void **)&buffer, "molecule::CheckAdjacencyFileAgainstMolecule: *buffer");
+
+  return status;
 };
 
@@ -2784,158 +3479,158 @@
 bool molecule::CheckOrderAtSite(ofstream *out, bool *AtomMask, Graph *GlobalKeySetList, int Order, int *MinimumRingSize, char *path)
 {
-	atom *Walker = start;
-	bool status = false;
-	ifstream InputFile;
-
-	// initialize mask list
-	for(int i=AtomCount;i--;)
-		AtomMask[i] = false;
-
-	if (Order < 0) { // adaptive increase of BondOrder per site
-		if (AtomMask[AtomCount] == true)	// break after one step
-			return false;
-		// parse the EnergyPerFragment file
-		char *buffer = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "molecule::CheckOrderAtSite: *buffer");
-		sprintf(buffer, "%s/%s%s.dat", path, FRAGMENTPREFIX, ENERGYPERFRAGMENT);
-		InputFile.open(buffer, ios::in);
-		if ((InputFile != NULL) && (GlobalKeySetList != NULL)) {
-			// transmorph graph keyset list into indexed KeySetList
-			map<int,KeySet> IndexKeySetList;
-			for(Graph::iterator runner = GlobalKeySetList->begin(); runner != GlobalKeySetList->end(); runner++) {
-				IndexKeySetList.insert( pair<int,KeySet>(runner->second.first,runner->first) );
-			}
-			int lines = 0;
-			// count the number of lines, i.e. the number of fragments
-			InputFile.getline(buffer, MAXSTRINGSIZE); // skip comment lines
-			InputFile.getline(buffer, MAXSTRINGSIZE);
-			while(!InputFile.eof()) {
-				InputFile.getline(buffer, MAXSTRINGSIZE);
-				lines++;
-			}
-			//*out << Verbose(2) << "Scanned " << lines-1 << " lines." << endl;	 // one endline too much
-			InputFile.clear();
-			InputFile.seekg(ios::beg);
-			map<int, pair<double,int> > AdaptiveCriteriaList;	// (Root No., (Value, Order)) !
-			int No, FragOrder;
-			double Value;
-			// each line represents a fragment root (Atom::nr) id and its energy contribution
-			InputFile.getline(buffer, MAXSTRINGSIZE); // skip comment lines
-			InputFile.getline(buffer, MAXSTRINGSIZE);
-			while(!InputFile.eof()) {
-				InputFile.getline(buffer, MAXSTRINGSIZE);
-				if (strlen(buffer) > 2) {
-					//*out << Verbose(2) << "Scanning: " << buffer << endl;
-					stringstream line(buffer);
-					line >> FragOrder;
-					line >> ws >> No;
-					line >> ws >> Value; // skip time entry
-					line >> ws >> Value;
-					No -= 1;	// indices start at 1 in file, not 0
-					//*out << Verbose(2) << " - yields (" << No << "," << Value << ", " << FragOrder << ")" << endl;
-
-					// clean the list of those entries that have been superceded by higher order terms already
-					map<int,KeySet>::iterator marker = IndexKeySetList.find(No);		// find keyset to Frag No.
-					if (marker != IndexKeySetList.end()) {	// if found
-						Value *= 1 + MYEPSILON*(*((*marker).second.begin()));		 // in case of equal energies this makes em not equal without changing anything actually
-						// as the smallest number in each set has always been the root (we use global id to keep the doubles away), seek smallest and insert into AtomMask
-						pair <map<int, pair<double,int> >::iterator, bool> InsertedElement = AdaptiveCriteriaList.insert( make_pair(*((*marker).second.begin()), pair<double,int>( fabs(Value), FragOrder) ));
-						map<int, pair<double,int> >::iterator PresentItem = InsertedElement.first;
-						if (!InsertedElement.second) { // this root is already present
-							if ((*PresentItem).second.second < FragOrder)	// if order there is lower, update entry with higher-order term
-								//if ((*PresentItem).second.first < (*runner).first)		// as higher-order terms are not always better, we skip this part (which would always include this site into adaptive increase)
-								{	// if value is smaller, update value and order
-								(*PresentItem).second.first = fabs(Value);
-								(*PresentItem).second.second = FragOrder;
-								*out << Verbose(2) << "Updated element (" <<	(*PresentItem).first << ",[" << (*PresentItem).second.first << "," << (*PresentItem).second.second << "])." << endl;
-							} else {
-								*out << Verbose(2) << "Did not update element " <<	(*PresentItem).first << " as " << FragOrder << " is less than or equal to " << (*PresentItem).second.second << "." << endl;
-							}
-						} else {
-							*out << Verbose(2) << "Inserted element (" <<	(*PresentItem).first << ",[" << (*PresentItem).second.first << "," << (*PresentItem).second.second << "])." << endl;
-						}
-					} else {
-						*out << Verbose(1) << "No Fragment under No. " << No << "found." << endl;
-					}
-				}
-			}
-			// then map back onto (Value, (Root Nr., Order)) (i.e. sorted by value to pick the highest ones)
-			map<double, pair<int,int> > FinalRootCandidates;
-			*out << Verbose(1) << "Root candidate list is: " << endl;
-			for(map<int, pair<double,int> >::iterator runner = AdaptiveCriteriaList.begin(); runner != AdaptiveCriteriaList.end(); runner++) {
-				Walker = FindAtom((*runner).first);
-				if (Walker != NULL) {
-					//if ((*runner).second.second >= Walker->AdaptiveOrder) { // only insert if this is an "active" root site for the current order
-					if (!Walker->MaxOrder) {
-						*out << Verbose(2) << "(" << (*runner).first << ",[" << (*runner).second.first << "," << (*runner).second.second << "])" << endl;
-						FinalRootCandidates.insert( make_pair( (*runner).second.first, pair<int,int>((*runner).first, (*runner).second.second) ) );
-					} else {
-						*out << Verbose(2) << "Excluding (" << *Walker << ", " << (*runner).first << ",[" << (*runner).second.first << "," << (*runner).second.second << "]), as it has reached its maximum order." << endl;
-					}
-				} else {
-					cerr << "Atom No. " << (*runner).second.first << " was not found in this molecule." << endl;
-				}
-			}
-			// pick the ones still below threshold and mark as to be adaptively updated
-			for(map<double, pair<int,int> >::iterator runner = FinalRootCandidates.upper_bound(pow(10.,Order)); runner != FinalRootCandidates.end(); runner++) {
-				No = (*runner).second.first;
-				Walker = FindAtom(No);
-				//if (Walker->AdaptiveOrder < MinimumRingSize[Walker->nr]) {
-					*out << Verbose(2) << "Root " << No << " is still above threshold (10^{" << Order <<"}: " << runner->first << ", setting entry " << No << " of Atom mask to true." << endl;
-					AtomMask[No] = true;
-					status = true;
-				//} else
-					//*out << Verbose(2) << "Root " << No << " is still above threshold (10^{" << Order <<"}: " << runner->first << ", however MinimumRingSize of " << MinimumRingSize[Walker->nr] << " does not allow further adaptive increase." << endl;
-			}
-			// close and done
-			InputFile.close();
-			InputFile.clear();
-		} else {
-			cerr << "Unable to parse " << buffer << " file, incrementing all." << endl;
-			while (Walker->next != end) {
-				Walker = Walker->next;
-		#ifdef ADDHYDROGEN
-				if (Walker->type->Z != 1) // skip hydrogen
-		#endif
-				{
-					AtomMask[Walker->nr] = true;	// include all (non-hydrogen) atoms
-					status = true;
-				}
-			}
-		}
-		Free((void **)&buffer, "molecule::CheckOrderAtSite: *buffer");
-		// pick a given number of highest values and set AtomMask
-	} else { // global increase of Bond Order
-		while (Walker->next != end) {
-			Walker = Walker->next;
-	#ifdef ADDHYDROGEN
-			if (Walker->type->Z != 1) // skip hydrogen
-	#endif
-			{
-				AtomMask[Walker->nr] = true;	// include all (non-hydrogen) atoms
-				if ((Order != 0) && (Walker->AdaptiveOrder < Order)) // && (Walker->AdaptiveOrder < MinimumRingSize[Walker->nr]))
-					status = true;
-			}
-		}
-		if ((Order == 0) && (AtomMask[AtomCount] == false))	// single stepping, just check
-			status = true;
-
-		if (!status) {
-			if (Order == 0)
-				*out << Verbose(1) << "Single stepping done." << endl;
-			else
-				*out << Verbose(1) << "Order at every site is already equal or above desired order " << Order << "." << endl;
-		}
-	}
-
-	// print atom mask for debugging
-	*out << "							";
-	for(int i=0;i<AtomCount;i++)
-		*out << (i % 10);
-	*out << endl << "Atom mask is: ";
-	for(int i=0;i<AtomCount;i++)
-		*out << (AtomMask[i] ? "t" : "f");
-	*out << endl;
-
-	return status;
+  atom *Walker = start;
+  bool status = false;
+  ifstream InputFile;
+
+  // initialize mask list
+  for(int i=AtomCount;i--;)
+    AtomMask[i] = false;
+
+  if (Order < 0) { // adaptive increase of BondOrder per site
+    if (AtomMask[AtomCount] == true)  // break after one step
+      return false;
+    // parse the EnergyPerFragment file
+    char *buffer = (char *) Malloc(sizeof(char)*MAXSTRINGSIZE, "molecule::CheckOrderAtSite: *buffer");
+    sprintf(buffer, "%s/%s%s.dat", path, FRAGMENTPREFIX, ENERGYPERFRAGMENT);
+    InputFile.open(buffer, ios::in);
+    if ((InputFile != NULL) && (GlobalKeySetList != NULL)) {
+      // transmorph graph keyset list into indexed KeySetList
+      map<int,KeySet> IndexKeySetList;
+      for(Graph::iterator runner = GlobalKeySetList->begin(); runner != GlobalKeySetList->end(); runner++) {
+        IndexKeySetList.insert( pair<int,KeySet>(runner->second.first,runner->first) );
+      }
+      int lines = 0;
+      // count the number of lines, i.e. the number of fragments
+      InputFile.getline(buffer, MAXSTRINGSIZE); // skip comment lines
+      InputFile.getline(buffer, MAXSTRINGSIZE);
+      while(!InputFile.eof()) {
+        InputFile.getline(buffer, MAXSTRINGSIZE);
+        lines++;
+      }
+      //*out << Verbose(2) << "Scanned " << lines-1 << " lines." << endl;   // one endline too much
+      InputFile.clear();
+      InputFile.seekg(ios::beg);
+      map<int, pair<double,int> > AdaptiveCriteriaList;  // (Root No., (Value, Order)) !
+      int No, FragOrder;
+      double Value;
+      // each line represents a fragment root (Atom::nr) id and its energy contribution
+      InputFile.getline(buffer, MAXSTRINGSIZE); // skip comment lines
+      InputFile.getline(buffer, MAXSTRINGSIZE);
+      while(!InputFile.eof()) {
+        InputFile.getline(buffer, MAXSTRINGSIZE);
+        if (strlen(buffer) > 2) {
+          //*out << Verbose(2) << "Scanning: " << buffer << endl;
+          stringstream line(buffer);
+          line >> FragOrder;
+          line >> ws >> No;
+          line >> ws >> Value; // skip time entry
+          line >> ws >> Value;
+          No -= 1;  // indices start at 1 in file, not 0
+          //*out << Verbose(2) << " - yields (" << No << "," << Value << ", " << FragOrder << ")" << endl;
+
+          // clean the list of those entries that have been superceded by higher order terms already
+          map<int,KeySet>::iterator marker = IndexKeySetList.find(No);    // find keyset to Frag No.
+          if (marker != IndexKeySetList.end()) {  // if found
+            Value *= 1 + MYEPSILON*(*((*marker).second.begin()));     // in case of equal energies this makes em not equal without changing anything actually
+            // as the smallest number in each set has always been the root (we use global id to keep the doubles away), seek smallest and insert into AtomMask
+            pair <map<int, pair<double,int> >::iterator, bool> InsertedElement = AdaptiveCriteriaList.insert( make_pair(*((*marker).second.begin()), pair<double,int>( fabs(Value), FragOrder) ));
+            map<int, pair<double,int> >::iterator PresentItem = InsertedElement.first;
+            if (!InsertedElement.second) { // this root is already present
+              if ((*PresentItem).second.second < FragOrder)  // if order there is lower, update entry with higher-order term
+                //if ((*PresentItem).second.first < (*runner).first)    // as higher-order terms are not always better, we skip this part (which would always include this site into adaptive increase)
+                {  // if value is smaller, update value and order
+                (*PresentItem).second.first = fabs(Value);
+                (*PresentItem).second.second = FragOrder;
+                *out << Verbose(2) << "Updated element (" <<  (*PresentItem).first << ",[" << (*PresentItem).second.first << "," << (*PresentItem).second.second << "])." << endl;
+              } else {
+                *out << Verbose(2) << "Did not update element " <<  (*PresentItem).first << " as " << FragOrder << " is less than or equal to " << (*PresentItem).second.second << "." << endl;
+              }
+            } else {
+              *out << Verbose(2) << "Inserted element (" <<  (*PresentItem).first << ",[" << (*PresentItem).second.first << "," << (*PresentItem).second.second << "])." << endl;
+            }
+          } else {
+            *out << Verbose(1) << "No Fragment under No. " << No << "found." << endl;
+          }
+        }
+      }
+      // then map back onto (Value, (Root Nr., Order)) (i.e. sorted by value to pick the highest ones)
+      map<double, pair<int,int> > FinalRootCandidates;
+      *out << Verbose(1) << "Root candidate list is: " << endl;
+      for(map<int, pair<double,int> >::iterator runner = AdaptiveCriteriaList.begin(); runner != AdaptiveCriteriaList.end(); runner++) {
+        Walker = FindAtom((*runner).first);
+        if (Walker != NULL) {
+          //if ((*runner).second.second >= Walker->AdaptiveOrder) { // only insert if this is an "active" root site for the current order
+          if (!Walker->MaxOrder) {
+            *out << Verbose(2) << "(" << (*runner).first << ",[" << (*runner).second.first << "," << (*runner).second.second << "])" << endl;
+            FinalRootCandidates.insert( make_pair( (*runner).second.first, pair<int,int>((*runner).first, (*runner).second.second) ) );
+          } else {
+            *out << Verbose(2) << "Excluding (" << *Walker << ", " << (*runner).first << ",[" << (*runner).second.first << "," << (*runner).second.second << "]), as it has reached its maximum order." << endl;
+          }
+        } else {
+          cerr << "Atom No. " << (*runner).second.first << " was not found in this molecule." << endl;
+        }
+      }
+      // pick the ones still below threshold and mark as to be adaptively updated
+      for(map<double, pair<int,int> >::iterator runner = FinalRootCandidates.upper_bound(pow(10.,Order)); runner != FinalRootCandidates.end(); runner++) {
+        No = (*runner).second.first;
+        Walker = FindAtom(No);
+        //if (Walker->AdaptiveOrder < MinimumRingSize[Walker->nr]) {
+          *out << Verbose(2) << "Root " << No << " is still above threshold (10^{" << Order <<"}: " << runner->first << ", setting entry " << No << " of Atom mask to true." << endl;
+          AtomMask[No] = true;
+          status = true;
+        //} else
+          //*out << Verbose(2) << "Root " << No << " is still above threshold (10^{" << Order <<"}: " << runner->first << ", however MinimumRingSize of " << MinimumRingSize[Walker->nr] << " does not allow further adaptive increase." << endl;
+      }
+      // close and done
+      InputFile.close();
+      InputFile.clear();
+    } else {
+      cerr << "Unable to parse " << buffer << " file, incrementing all." << endl;
+      while (Walker->next != end) {
+        Walker = Walker->next;
+    #ifdef ADDHYDROGEN
+        if (Walker->type->Z != 1) // skip hydrogen
+    #endif
+        {
+          AtomMask[Walker->nr] = true;  // include all (non-hydrogen) atoms
+          status = true;
+        }
+      }
+    }
+    Free((void **)&buffer, "molecule::CheckOrderAtSite: *buffer");
+    // pick a given number of highest values and set AtomMask
+  } else { // global increase of Bond Order
+    while (Walker->next != end) {
+      Walker = Walker->next;
+  #ifdef ADDHYDROGEN
+      if (Walker->type->Z != 1) // skip hydrogen
+  #endif
+      {
+        AtomMask[Walker->nr] = true;  // include all (non-hydrogen) atoms
+        if ((Order != 0) && (Walker->AdaptiveOrder < Order)) // && (Walker->AdaptiveOrder < MinimumRingSize[Walker->nr]))
+          status = true;
+      }
+    }
+    if ((Order == 0) && (AtomMask[AtomCount] == false))  // single stepping, just check
+      status = true;
+
+    if (!status) {
+      if (Order == 0)
+        *out << Verbose(1) << "Single stepping done." << endl;
+      else
+        *out << Verbose(1) << "Order at every site is already equal or above desired order " << Order << "." << endl;
+    }
+  }
+
+  // print atom mask for debugging
+  *out << "              ";
+  for(int i=0;i<AtomCount;i++)
+    *out << (i % 10);
+  *out << endl << "Atom mask is: ";
+  for(int i=0;i<AtomCount;i++)
+    *out << (AtomMask[i] ? "t" : "f");
+  *out << endl;
+
+  return status;
 };
 
@@ -2947,27 +3642,27 @@
 bool molecule::CreateMappingLabelsToConfigSequence(ofstream *out, int *&SortIndex)
 {
-	element *runner = elemente->start;
-	int AtomNo = 0;
-	atom *Walker = NULL;
-
-	if (SortIndex != NULL) {
-		*out << Verbose(1) << "SortIndex is " << SortIndex << " and not NULL as expected." << endl;
-		return false;
-	}
-	SortIndex = (int *) Malloc(sizeof(int)*AtomCount, "molecule::FragmentMolecule: *SortIndex");
-	for(int i=AtomCount;i--;)
-		SortIndex[i] = -1;
-	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++;
-			}
-		}
-	}
-	return true;
+  element *runner = elemente->start;
+  int AtomNo = 0;
+  atom *Walker = NULL;
+
+  if (SortIndex != NULL) {
+    *out << Verbose(1) << "SortIndex is " << SortIndex << " and not NULL as expected." << endl;
+    return false;
+  }
+  SortIndex = (int *) Malloc(sizeof(int)*AtomCount, "molecule::FragmentMolecule: *SortIndex");
+  for(int i=AtomCount;i--;)
+    SortIndex[i] = -1;
+  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++;
+      }
+    }
+  }
+  return true;
 };
 
@@ -2978,6 +3673,6 @@
 y contribution", and that's why this consciously not done in the following loop)
  * -# in a loop over all subgraphs
- *	-# calls FragmentBOSSANOVA with this RootStack and within the subgraph molecule structure
- *	-# creates molecule (fragment)s from the returned keysets (StoreFragmentFromKeySet)
+ *  -# calls FragmentBOSSANOVA with this RootStack and within the subgraph molecule structure
+ *  -# creates molecule (fragment)s from the returned keysets (StoreFragmentFromKeySet)
  * -# combines the generated molecule lists from all subgraphs
  * -# saves to disk: fragment configs, adjacency, orderatsite, keyset files
@@ -2992,184 +3687,185 @@
 int molecule::FragmentMolecule(ofstream *out, int Order, config *configuration)
 {
-	MoleculeListClass *BondFragments = NULL;
-	int *SortIndex = NULL;
-	int *MinimumRingSize = new int[AtomCount];
-	int FragmentCounter;
-	MoleculeLeafClass *MolecularWalker = NULL;
-	MoleculeLeafClass *Subgraphs = NULL;			// list of subgraphs from DFS analysis
-	fstream File;
-	bool FragmentationToDo = true;
-	class StackClass<bond *> *BackEdgeStack = NULL, *LocalBackEdgeStack = NULL;
-	bool CheckOrder = false;
-	Graph **FragmentList = NULL;
-	Graph *ParsedFragmentList = NULL;
-	Graph TotalGraph;		 // graph with all keysets however local numbers
-	int TotalNumberOfKeySets = 0;
-	atom **ListOfAtoms = NULL;
-	atom ***ListOfLocalAtoms = NULL;
-	bool *AtomMask = NULL;
-
-	*out << endl;
+  MoleculeListClass *BondFragments = NULL;
+  int *SortIndex = NULL;
+  int *MinimumRingSize = new int[AtomCount];
+  int FragmentCounter;
+  MoleculeLeafClass *MolecularWalker = NULL;
+  MoleculeLeafClass *Subgraphs = NULL;      // list of subgraphs from DFS analysis
+  fstream File;
+  bool FragmentationToDo = true;
+  class StackClass<bond *> *BackEdgeStack = NULL, *LocalBackEdgeStack = NULL;
+  bool CheckOrder = false;
+  Graph **FragmentList = NULL;
+  Graph *ParsedFragmentList = NULL;
+  Graph TotalGraph;     // graph with all keysets however local numbers
+  int TotalNumberOfKeySets = 0;
+  atom **ListOfAtoms = NULL;
+  atom ***ListOfLocalAtoms = NULL;
+  bool *AtomMask = NULL;
+
+  *out << endl;
 #ifdef ADDHYDROGEN
-	*out << Verbose(0) << "I will treat hydrogen special and saturate dangling bonds with it." << endl;
+  *out << Verbose(0) << "I will treat hydrogen special and saturate dangling bonds with it." << endl;
 #else
-	*out << Verbose(0) << "Hydrogen is treated just like the rest of the lot." << endl;
+  *out << Verbose(0) << "Hydrogen is treated just like the rest of the lot." << endl;
 #endif
 
-	// ++++++++++++++++++++++++++++ INITIAL STUFF: Bond structure analysis, file parsing, ... ++++++++++++++++++++++++++++++++++++++++++
-
-	// ===== 1. Check whether bond structure is same as stored in files ====
-
-	// fill the adjacency list
-	CreateListOfBondsPerAtom(out);
-
-	// create lookup table for Atom::nr
-	FragmentationToDo = FragmentationToDo && CreateFatherLookupTable(out, start, end, ListOfAtoms, AtomCount);
-
-	// === compare it with adjacency file ===
-	FragmentationToDo = FragmentationToDo && CheckAdjacencyFileAgainstMolecule(out, configuration->configpath, ListOfAtoms);
-	Free((void **)&ListOfAtoms, "molecule::FragmentMolecule - **ListOfAtoms");
-
-	// ===== 2. perform a DFS analysis to gather info on cyclic structure and a list of disconnected subgraphs =====
-	Subgraphs = DepthFirstSearchAnalysis(out, BackEdgeStack);
-	// fill the bond structure of the individually stored subgraphs
-	Subgraphs->next->FillBondStructureFromReference(out, this, (FragmentCounter = 0), ListOfLocalAtoms, false);	// we want to keep the created ListOfLocalAtoms
-	// analysis of the cycles (print rings, get minimum cycle length) for each subgraph
-	for(int i=AtomCount;i--;)
-		MinimumRingSize[i] = AtomCount;
-	MolecularWalker = Subgraphs;
-	FragmentCounter = 0;
-	while (MolecularWalker->next != NULL) {
-		MolecularWalker = MolecularWalker->next;
-		LocalBackEdgeStack = new StackClass<bond *> (MolecularWalker->Leaf->BondCount);
-//		// check the list of local atoms for debugging
-//		*out << Verbose(0) << "ListOfLocalAtoms for this subgraph is:" << endl;
-//		for (int i=0;i<AtomCount;i++)
-//			if (ListOfLocalAtoms[FragmentCounter][i] == NULL)
-//				*out << "\tNULL";
-//			else
-//				*out << "\t" << ListOfLocalAtoms[FragmentCounter][i]->Name;
-		*out << Verbose(0) << "Gathering local back edges for subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
-		MolecularWalker->Leaf->PickLocalBackEdges(out, ListOfLocalAtoms[FragmentCounter++], BackEdgeStack, LocalBackEdgeStack);
-		*out << Verbose(0) << "Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
-		MolecularWalker->Leaf->CyclicStructureAnalysis(out, LocalBackEdgeStack, MinimumRingSize);
-		*out << Verbose(0) << "Done with Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
-		delete(LocalBackEdgeStack);
-	}
-
-	// ===== 3. if structure still valid, parse key set file and others =====
-	FragmentationToDo = FragmentationToDo && ParseKeySetFile(out, configuration->configpath, ParsedFragmentList);
-
-	// ===== 4. check globally whether there's something to do actually (first adaptivity check)
-	FragmentationToDo = FragmentationToDo && ParseOrderAtSiteFromFile(out, configuration->configpath);
-
-	// =================================== Begin of FRAGMENTATION ===============================
-	// ===== 6a. assign each keyset to its respective subgraph =====
-	Subgraphs->next->AssignKeySetsToFragment(out, this, ParsedFragmentList, ListOfLocalAtoms, FragmentList, (FragmentCounter = 0), true);
-
-	// ===== 6b. prepare and go into the adaptive (Order<0), single-step (Order==0) or incremental (Order>0) cycle
-	KeyStack *RootStack = new KeyStack[Subgraphs->next->Count()];
-	AtomMask = new bool[AtomCount+1];
-	AtomMask[AtomCount] = false;
-	FragmentationToDo = false;	// if CheckOrderAtSite just ones recommends fragmentation, we will save fragments afterwards
-	while ((CheckOrder = CheckOrderAtSite(out, AtomMask, ParsedFragmentList, Order, MinimumRingSize, configuration->configpath))) {
-		FragmentationToDo = FragmentationToDo || CheckOrder;
-		AtomMask[AtomCount] = true;	 // last plus one entry is used as marker that we have been through this loop once already in CheckOrderAtSite()
-		// ===== 6b. fill RootStack for each subgraph (second adaptivity check) =====
-		Subgraphs->next->FillRootStackForSubgraphs(out, RootStack, AtomMask, (FragmentCounter = 0));
-
-		// ===== 7. fill the bond fragment list =====
-		FragmentCounter = 0;
-		MolecularWalker = Subgraphs;
-		while (MolecularWalker->next != NULL) {
-			MolecularWalker = MolecularWalker->next;
-			*out << Verbose(1) << "Fragmenting subgraph " << MolecularWalker << "." << endl;
-			//MolecularWalker->Leaf->OutputListOfBonds(out);	// output ListOfBondsPerAtom for debugging
-			if (MolecularWalker->Leaf->first->next != MolecularWalker->Leaf->last) {
-				// call BOSSANOVA method
-				*out << Verbose(0) << endl << " ========== BOND ENERGY of subgraph " << FragmentCounter << " ========================= " << endl;
-				MolecularWalker->Leaf->FragmentBOSSANOVA(out, FragmentList[FragmentCounter], RootStack[FragmentCounter], MinimumRingSize);
-			} else {
-				cerr << "Subgraph " << MolecularWalker << " has no atoms!" << endl;
-			}
-			FragmentCounter++;	// next fragment list
-		}
-	}
-	delete[](RootStack);
-	delete[](AtomMask);
-	delete(ParsedFragmentList);
-	delete[](MinimumRingSize);
-
-
-	// ==================================== End of FRAGMENTATION ============================================
-
-	// ===== 8a. translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
-	Subgraphs->next->TranslateIndicesToGlobalIDs(out, FragmentList, (FragmentCounter = 0), TotalNumberOfKeySets, TotalGraph);
-
-	// free subgraph memory again
-	FragmentCounter = 0;
-	if (Subgraphs != NULL) {
-		while (Subgraphs->next != NULL) {
-			Subgraphs = Subgraphs->next;
-			delete(FragmentList[FragmentCounter++]);
-			delete(Subgraphs->previous);
-		}
-		delete(Subgraphs);
-	}
-	Free((void **)&FragmentList, "molecule::FragmentMolecule - **FragmentList");
-
-	// ===== 8b. gather keyset lists (graphs) from all subgraphs and transform into MoleculeListClass =====
-	//if (FragmentationToDo) {		// we should always store the fragments again as coordination might have changed slightly without changing bond structure
-		// allocate memory for the pointer array and transmorph graphs into full molecular fragments
-		BondFragments = new MoleculeListClass();
-		int k=0;
-		for(Graph::iterator runner = TotalGraph.begin(); runner != TotalGraph.end(); runner++) {
-			KeySet test = (*runner).first;
-			*out << "Fragment No." << (*runner).second.first << " with TEFactor " << (*runner).second.second << "." << endl;
-			BondFragments->insert(StoreFragmentFromKeySet(out, test, configuration));
-			k++;
-		}
-		*out << k << "/" << BondFragments->ListOfMolecules.size() << " fragments generated from the keysets." << endl;
-
-		// ===== 9. Save fragments' configuration and keyset files et al to disk ===
-		if (BondFragments->ListOfMolecules.size() != 0) {
-			// create the SortIndex from BFS labels to order in the config file
-			CreateMappingLabelsToConfigSequence(out, SortIndex);
-
-			*out << Verbose(1) << "Writing " << BondFragments->ListOfMolecules.size() << " possible bond fragmentation configs" << endl;
-			if (BondFragments->OutputConfigForListOfFragments(out, configuration, SortIndex))
-				*out << Verbose(1) << "All configs written." << endl;
-			else
-				*out << Verbose(1) << "Some config writing failed." << endl;
-
-			// store force index reference file
-			BondFragments->StoreForcesFile(out, configuration->configpath, SortIndex);
-
-			// store keysets file
-			StoreKeySetFile(out, TotalGraph, configuration->configpath);
-
-			// store Adjacency file
-			StoreAdjacencyToFile(out, configuration->configpath);
-
-			// store Hydrogen saturation correction file
-			BondFragments->AddHydrogenCorrection(out, configuration->configpath);
-
-			// store adaptive orders into file
-			StoreOrderAtSiteFile(out, configuration->configpath);
-
-			// 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
-			Free((void **)&SortIndex, "molecule::FragmentMolecule: *SortIndex");
-		} else
-			*out << Verbose(1) << "FragmentList is zero on return, splitting failed." << endl;
-	//} else
-	//	*out << Verbose(1) << "No fragments to store." << endl;
-	*out << Verbose(0) << "End of bond fragmentation." << endl;
-
-	return ((int)(!FragmentationToDo)+1);		// 1 - continue, 2 - stop (no fragmentation occured)
+  // ++++++++++++++++++++++++++++ INITIAL STUFF: Bond structure analysis, file parsing, ... ++++++++++++++++++++++++++++++++++++++++++
+
+  // ===== 1. Check whether bond structure is same as stored in files ====
+
+  // fill the adjacency list
+  CreateListOfBondsPerAtom(out);
+
+  // create lookup table for Atom::nr
+  FragmentationToDo = FragmentationToDo && CreateFatherLookupTable(out, start, end, ListOfAtoms, AtomCount);
+
+  // === compare it with adjacency file ===
+  FragmentationToDo = FragmentationToDo && CheckAdjacencyFileAgainstMolecule(out, configuration->configpath, ListOfAtoms);
+  Free((void **)&ListOfAtoms, "molecule::FragmentMolecule - **ListOfAtoms");
+
+  // ===== 2. perform a DFS analysis to gather info on cyclic structure and a list of disconnected subgraphs =====
+  Subgraphs = DepthFirstSearchAnalysis(out, BackEdgeStack);
+  // fill the bond structure of the individually stored subgraphs
+  Subgraphs->next->FillBondStructureFromReference(out, this, (FragmentCounter = 0), ListOfLocalAtoms, false);  // we want to keep the created ListOfLocalAtoms
+  // analysis of the cycles (print rings, get minimum cycle length) for each subgraph
+  for(int i=AtomCount;i--;)
+    MinimumRingSize[i] = AtomCount;
+  MolecularWalker = Subgraphs;
+  FragmentCounter = 0;
+  while (MolecularWalker->next != NULL) {
+    MolecularWalker = MolecularWalker->next;
+    *out << Verbose(0) << "Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
+    LocalBackEdgeStack = new StackClass<bond *> (MolecularWalker->Leaf->BondCount);
+//    // check the list of local atoms for debugging
+//    *out << Verbose(0) << "ListOfLocalAtoms for this subgraph is:" << endl;
+//    for (int i=0;i<AtomCount;i++)
+//      if (ListOfLocalAtoms[FragmentCounter][i] == NULL)
+//        *out << "\tNULL";
+//      else
+//        *out << "\t" << ListOfLocalAtoms[FragmentCounter][i]->Name;
+    *out << Verbose(0) << "Gathering local back edges for subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
+    MolecularWalker->Leaf->PickLocalBackEdges(out, ListOfLocalAtoms[FragmentCounter++], BackEdgeStack, LocalBackEdgeStack);
+    *out << Verbose(0) << "Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
+    MolecularWalker->Leaf->CyclicStructureAnalysis(out, LocalBackEdgeStack, MinimumRingSize);
+    *out << Verbose(0) << "Done with Analysing the cycles of subgraph " << MolecularWalker->Leaf << " with nr. " << FragmentCounter << "." << endl;
+    delete(LocalBackEdgeStack);
+  }
+  
+  // ===== 3. if structure still valid, parse key set file and others =====
+  FragmentationToDo = FragmentationToDo && ParseKeySetFile(out, configuration->configpath, ParsedFragmentList);
+
+  // ===== 4. check globally whether there's something to do actually (first adaptivity check)
+  FragmentationToDo = FragmentationToDo && ParseOrderAtSiteFromFile(out, configuration->configpath);
+  
+  // =================================== Begin of FRAGMENTATION =============================== 
+  // ===== 6a. assign each keyset to its respective subgraph ===== 
+  Subgraphs->next->AssignKeySetsToFragment(out, this, ParsedFragmentList, ListOfLocalAtoms, FragmentList, (FragmentCounter = 0), true);
+
+  // ===== 6b. prepare and go into the adaptive (Order<0), single-step (Order==0) or incremental (Order>0) cycle
+  KeyStack *RootStack = new KeyStack[Subgraphs->next->Count()];
+  AtomMask = new bool[AtomCount+1];
+  AtomMask[AtomCount] = false;
+  FragmentationToDo = false;  // if CheckOrderAtSite just ones recommends fragmentation, we will save fragments afterwards
+  while ((CheckOrder = CheckOrderAtSite(out, AtomMask, ParsedFragmentList, Order, MinimumRingSize, configuration->configpath))) {
+    FragmentationToDo = FragmentationToDo || CheckOrder;
+    AtomMask[AtomCount] = true;   // last plus one entry is used as marker that we have been through this loop once already in CheckOrderAtSite()
+    // ===== 6b. fill RootStack for each subgraph (second adaptivity check) =====
+    Subgraphs->next->FillRootStackForSubgraphs(out, RootStack, AtomMask, (FragmentCounter = 0));
+
+    // ===== 7. fill the bond fragment list =====
+    FragmentCounter = 0;
+    MolecularWalker = Subgraphs;
+    while (MolecularWalker->next != NULL) {
+      MolecularWalker = MolecularWalker->next;
+      *out << Verbose(1) << "Fragmenting subgraph " << MolecularWalker << "." << endl;
+      //MolecularWalker->Leaf->OutputListOfBonds(out);  // output ListOfBondsPerAtom for debugging
+      if (MolecularWalker->Leaf->first->next != MolecularWalker->Leaf->last) {
+        // call BOSSANOVA method
+        *out << Verbose(0) << endl << " ========== BOND ENERGY of subgraph " << FragmentCounter << " ========================= " << endl;
+        MolecularWalker->Leaf->FragmentBOSSANOVA(out, FragmentList[FragmentCounter], RootStack[FragmentCounter], MinimumRingSize);
+      } else {
+        cerr << "Subgraph " << MolecularWalker << " has no atoms!" << endl;
+      }
+      FragmentCounter++;  // next fragment list
+    }
+  }
+  delete[](RootStack);
+  delete[](AtomMask);
+  delete(ParsedFragmentList);
+  delete[](MinimumRingSize);
+  
+
+  // ==================================== End of FRAGMENTATION ============================================
+
+  // ===== 8a. translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
+  Subgraphs->next->TranslateIndicesToGlobalIDs(out, FragmentList, (FragmentCounter = 0), TotalNumberOfKeySets, TotalGraph);
+
+  // free subgraph memory again
+  FragmentCounter = 0;
+  if (Subgraphs != NULL) {
+    while (Subgraphs->next != NULL) {
+      Subgraphs = Subgraphs->next;
+      delete(FragmentList[FragmentCounter++]);
+      delete(Subgraphs->previous);
+    }
+    delete(Subgraphs);
+  }
+  Free((void **)&FragmentList, "molecule::FragmentMolecule - **FragmentList");
+
+  // ===== 8b. gather keyset lists (graphs) from all subgraphs and transform into MoleculeListClass =====
+  //if (FragmentationToDo) {    // we should always store the fragments again as coordination might have changed slightly without changing bond structure
+    // allocate memory for the pointer array and transmorph graphs into full molecular fragments
+    BondFragments = new MoleculeListClass();
+    int k=0;
+    for(Graph::iterator runner = TotalGraph.begin(); runner != TotalGraph.end(); runner++) {
+      KeySet test = (*runner).first;
+      *out << "Fragment No." << (*runner).second.first << " with TEFactor " << (*runner).second.second << "." << endl;
+      BondFragments->insert(StoreFragmentFromKeySet(out, test, configuration));
+      k++;
+    }
+    *out << k << "/" << BondFragments->ListOfMolecules.size() << " fragments generated from the keysets." << endl;
+
+    // ===== 9. Save fragments' configuration and keyset files et al to disk ===
+    if (BondFragments->ListOfMolecules.size() != 0) {
+      // create the SortIndex from BFS labels to order in the config file
+      CreateMappingLabelsToConfigSequence(out, SortIndex);
+
+      *out << Verbose(1) << "Writing " << BondFragments->ListOfMolecules.size() << " possible bond fragmentation configs" << endl;
+      if (BondFragments->OutputConfigForListOfFragments(out, configuration, SortIndex))
+        *out << Verbose(1) << "All configs written." << endl;
+      else
+        *out << Verbose(1) << "Some config writing failed." << endl;
+
+      // store force index reference file
+      BondFragments->StoreForcesFile(out, configuration->configpath, SortIndex);
+
+      // store keysets file
+      StoreKeySetFile(out, TotalGraph, configuration->configpath);
+
+      // store Adjacency file
+      StoreAdjacencyToFile(out, configuration->configpath);
+
+      // store Hydrogen saturation correction file
+      BondFragments->AddHydrogenCorrection(out, configuration->configpath);
+
+      // store adaptive orders into file
+      StoreOrderAtSiteFile(out, configuration->configpath);
+
+      // 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
+      Free((void **)&SortIndex, "molecule::FragmentMolecule: *SortIndex");
+    } else
+      *out << Verbose(1) << "FragmentList is zero on return, splitting failed." << endl;
+  //} else
+  //  *out << Verbose(1) << "No fragments to store." << endl;
+  *out << Verbose(0) << "End of bond fragmentation." << endl;
+
+  return ((int)(!FragmentationToDo)+1);    // 1 - continue, 2 - stop (no fragmentation occured)
 };
 
@@ -3184,31 +3880,31 @@
 bool molecule::PickLocalBackEdges(ofstream *out, atom **ListOfLocalAtoms, class StackClass<bond *> *&ReferenceStack, class StackClass<bond *> *&LocalStack)
 {
-	bool status = true;
-	if (ReferenceStack->IsEmpty()) {
-		cerr << "ReferenceStack is empty!" << endl;
-		return false;
-	}
-	bond *Binder = ReferenceStack->PopFirst();
-	bond *FirstBond = Binder;	 // mark the first bond, so that we don't loop through the stack indefinitely
-	atom *Walker = NULL, *OtherAtom = NULL;
-	ReferenceStack->Push(Binder);
-
-	do {	// go through all bonds and push local ones
-		Walker = ListOfLocalAtoms[Binder->leftatom->nr];	// get one atom in the reference molecule
-		if (Walker != NULL) // if this Walker exists in the subgraph ...
-			for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {		// go through the local list of bonds
-				OtherAtom = ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker);
-				if (OtherAtom == ListOfLocalAtoms[Binder->rightatom->nr]) { // found the bond
-					LocalStack->Push(ListOfBondsPerAtom[Walker->nr][i]);
-					*out << Verbose(3) << "Found local edge " << *(ListOfBondsPerAtom[Walker->nr][i]) << "." << endl;
-					break;
-				}
-			}
-		Binder = ReferenceStack->PopFirst();	// loop the stack for next item
-		*out << Verbose(3) << "Current candidate edge " << Binder << "." << endl;
-		ReferenceStack->Push(Binder);
-	} while (FirstBond != Binder);
-
-	return status;
+  bool status = true;
+  if (ReferenceStack->IsEmpty()) {
+    cerr << "ReferenceStack is empty!" << endl;
+    return false;
+  }
+  bond *Binder = ReferenceStack->PopFirst();
+  bond *FirstBond = Binder;   // mark the first bond, so that we don't loop through the stack indefinitely
+  atom *Walker = NULL, *OtherAtom = NULL;
+  ReferenceStack->Push(Binder);
+  
+  do {  // go through all bonds and push local ones
+    Walker = ListOfLocalAtoms[Binder->leftatom->nr];  // get one atom in the reference molecule
+    if (Walker != NULL) // if this Walker exists in the subgraph ...
+      for(int i=0;i<NumberOfBondsPerAtom[Walker->nr];i++) {    // go through the local list of bonds
+        OtherAtom = ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker);
+        if (OtherAtom == ListOfLocalAtoms[Binder->rightatom->nr]) { // found the bond
+          LocalStack->Push(ListOfBondsPerAtom[Walker->nr][i]);
+          *out << Verbose(3) << "Found local edge " << *(ListOfBondsPerAtom[Walker->nr][i]) << "." << endl;
+          break;
+        }
+      }
+    Binder = ReferenceStack->PopFirst();  // loop the stack for next item
+    *out << Verbose(3) << "Current candidate edge " << Binder << "." << endl;
+    ReferenceStack->Push(Binder);
+  } while (FirstBond != Binder);
+
+  return status;
 };
 
@@ -3221,24 +3917,24 @@
 bool molecule::StoreOrderAtSiteFile(ofstream *out, char *path)
 {
-	stringstream line;
-	ofstream file;
-
-	line << path << "/" << FRAGMENTPREFIX << ORDERATSITEFILE;
-	file.open(line.str().c_str());
-	*out << Verbose(1) << "Writing OrderAtSite " << ORDERATSITEFILE << " ... " << endl;
-	if (file != NULL) {
-		atom *Walker = start;
-		while (Walker->next != end) {
-			Walker = Walker->next;
-			file << Walker->nr << "\t" << (int)Walker->AdaptiveOrder << "\t" << (int)Walker->MaxOrder << endl;
-			*out << Verbose(2) << "Storing: " << Walker->nr << "\t" << (int)Walker->AdaptiveOrder << "\t" << (int)Walker->MaxOrder << "." << endl;
-		}
-		file.close();
-		*out << Verbose(1) << "done." << endl;
-		return true;
-	} else {
-		*out << Verbose(1) << "failed to open file " << line.str() << "." << endl;
-		return false;
-	}
+  stringstream line;
+  ofstream file;
+
+  line << path << "/" << FRAGMENTPREFIX << ORDERATSITEFILE;
+  file.open(line.str().c_str());
+  *out << Verbose(1) << "Writing OrderAtSite " << ORDERATSITEFILE << " ... " << endl;
+  if (file != NULL) {
+    atom *Walker = start;
+    while (Walker->next != end) {
+      Walker = Walker->next;
+      file << Walker->nr << "\t" << (int)Walker->AdaptiveOrder << "\t" << (int)Walker->MaxOrder << endl;
+      *out << Verbose(2) << "Storing: " << Walker->nr << "\t" << (int)Walker->AdaptiveOrder << "\t" << (int)Walker->MaxOrder << "." << endl;
+    }
+    file.close();
+    *out << Verbose(1) << "done." << endl;
+    return true;
+  } else {
+    *out << Verbose(1) << "failed to open file " << line.str() << "." << endl;
+    return false;
+  }
 };
 
@@ -3252,51 +3948,51 @@
 bool molecule::ParseOrderAtSiteFromFile(ofstream *out, char *path)
 {
-	unsigned char *OrderArray = (unsigned char *) Malloc(sizeof(unsigned char)*AtomCount, "molecule::ParseOrderAtSiteFromFile - *OrderArray");
-	bool *MaxArray = (bool *) Malloc(sizeof(bool)*AtomCount, "molecule::ParseOrderAtSiteFromFile - *MaxArray");
-	bool status;
-	int AtomNr, value;
-	stringstream line;
-	ifstream file;
-
-	*out << Verbose(1) << "Begin of ParseOrderAtSiteFromFile" << endl;
-	for(int i=AtomCount;i--;)
-		OrderArray[i] = 0;
-	line << path << "/" << FRAGMENTPREFIX << ORDERATSITEFILE;
-	file.open(line.str().c_str());
-	if (file != NULL) {
-		for (int i=AtomCount;i--;) { // initialise with 0
-			OrderArray[i] = 0;
-			MaxArray[i] = 0;
-		}
-		while (!file.eof()) { // parse from file
-			AtomNr = -1;
-			file >> AtomNr;
-			if (AtomNr != -1) {	 // test whether we really parsed something (this is necessary, otherwise last atom is set twice and to 0 on second time)
-				file >> value;
-				OrderArray[AtomNr] = value;
-				file >> value;
-				MaxArray[AtomNr] = value;
-				//*out << Verbose(2) << "AtomNr " << AtomNr << " with order " << (int)OrderArray[AtomNr] << " and max order set to " << (int)MaxArray[AtomNr] << "." << endl;
-			}
-		}
-		atom *Walker = start;
-		while (Walker->next != end) { // fill into atom classes
-			Walker = Walker->next;
-			Walker->AdaptiveOrder = OrderArray[Walker->nr];
-			Walker->MaxOrder = MaxArray[Walker->nr];
-			*out << Verbose(2) << *Walker << " gets order " << (int)Walker->AdaptiveOrder << " and is " << (!Walker->MaxOrder ? "not " : " ") << "maxed." << endl;
-		}
-		file.close();
-		*out << Verbose(1) << "done." << endl;
-		status = true;
-	} else {
-		*out << Verbose(1) << "failed to open file " << line.str() << "." << endl;
-		status = false;
-	}
-	Free((void **)&OrderArray, "molecule::ParseOrderAtSiteFromFile - *OrderArray");
-	Free((void **)&MaxArray, "molecule::ParseOrderAtSiteFromFile - *MaxArray");
-
-	*out << Verbose(1) << "End of ParseOrderAtSiteFromFile" << endl;
-	return status;
+  unsigned char *OrderArray = (unsigned char *) Malloc(sizeof(unsigned char)*AtomCount, "molecule::ParseOrderAtSiteFromFile - *OrderArray");
+  bool *MaxArray = (bool *) Malloc(sizeof(bool)*AtomCount, "molecule::ParseOrderAtSiteFromFile - *MaxArray");
+  bool status;
+  int AtomNr, value;
+  stringstream line;
+  ifstream file;
+
+  *out << Verbose(1) << "Begin of ParseOrderAtSiteFromFile" << endl;
+  for(int i=AtomCount;i--;)
+    OrderArray[i] = 0;
+  line << path << "/" << FRAGMENTPREFIX << ORDERATSITEFILE;
+  file.open(line.str().c_str());
+  if (file != NULL) {
+    for (int i=AtomCount;i--;) { // initialise with 0
+      OrderArray[i] = 0;
+      MaxArray[i] = 0;
+    }
+    while (!file.eof()) { // parse from file
+      AtomNr = -1;
+      file >> AtomNr;
+      if (AtomNr != -1) {   // test whether we really parsed something (this is necessary, otherwise last atom is set twice and to 0 on second time)
+        file >> value;
+        OrderArray[AtomNr] = value;
+        file >> value;
+        MaxArray[AtomNr] = value;
+        //*out << Verbose(2) << "AtomNr " << AtomNr << " with order " << (int)OrderArray[AtomNr] << " and max order set to " << (int)MaxArray[AtomNr] << "." << endl;
+      }
+    }
+    atom *Walker = start;
+    while (Walker->next != end) { // fill into atom classes
+      Walker = Walker->next;
+      Walker->AdaptiveOrder = OrderArray[Walker->nr];
+      Walker->MaxOrder = MaxArray[Walker->nr];
+      *out << Verbose(2) << *Walker << " gets order " << (int)Walker->AdaptiveOrder << " and is " << (!Walker->MaxOrder ? "not " : " ") << "maxed." << endl;
+    }
+    file.close();
+    *out << Verbose(1) << "done." << endl;
+    status = true;
+  } else {
+    *out << Verbose(1) << "failed to open file " << line.str() << "." << endl;
+    status = false;
+  }
+  Free((void **)&OrderArray, "molecule::ParseOrderAtSiteFromFile - *OrderArray");
+  Free((void **)&MaxArray, "molecule::ParseOrderAtSiteFromFile - *MaxArray");
+
+  *out << Verbose(1) << "End of ParseOrderAtSiteFromFile" << endl;
+  return status;
 };
 
@@ -3309,59 +4005,59 @@
 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=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=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]++;
-	}
-	for(int i=AtomCount;i--;) {
-		// allocate list of bonds per atom
-		ListOfBondsPerAtom[i] = (bond **) Malloc(sizeof(bond *)*NumberOfBondsPerAtom[i], "molecule::CreateListOfBondsPerAtom: **ListOfBondsPerAtom[]");
-		// clear the list again, now each NumberOfBondsPerAtom marks current free field
-		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 << "/" << Walker->nr << " 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;
+  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=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=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]++;
+  }
+  for(int i=AtomCount;i--;) {
+    // allocate list of bonds per atom
+    ListOfBondsPerAtom[i] = (bond **) Malloc(sizeof(bond *)*NumberOfBondsPerAtom[i], "molecule::CreateListOfBondsPerAtom: **ListOfBondsPerAtom[]");
+    // clear the list again, now each NumberOfBondsPerAtom marks current free field
+    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 << "/" << Walker->nr << " 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;
 };
 
@@ -3380,115 +4076,115 @@
 void molecule::BreadthFirstSearchAdd(ofstream *out, molecule *Mol, atom **&AddedAtomList, bond **&AddedBondList, atom *Root, bond *Bond, int BondOrder, bool IsAngstroem)
 {
-	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");
-	class StackClass<atom *> *AtomStack = new StackClass<atom *>(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=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))) ) { // 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)
-							*out << ", is not part of a cyclic bond, saturating bond with Hydrogen." << endl;
-						if (AddedBondList[Binder->nr] == NULL) {
-							if ((AddedAtomList[OtherAtom->nr] != NULL)) { // .. whether we add or saturate
-								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 {
+  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");
+  class StackClass<atom *> *AtomStack = new StackClass<atom *>(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=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))) ) { // 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)
+              *out << ", is not part of a cyclic bond, saturating bond with Hydrogen." << endl;
+            if (AddedBondList[Binder->nr] == NULL) {
+              if ((AddedAtomList[OtherAtom->nr] != NULL)) { // .. whether we add or saturate
+                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
-								if (!Mol->AddHydrogenReplacementAtom(out, Binder, AddedAtomList[Walker->nr], Walker, OtherAtom, ListOfBondsPerAtom[Walker->nr], NumberOfBondsPerAtom[Walker->nr], IsAngstroem))
-									exit(1);
+                if (!Mol->AddHydrogenReplacementAtom(out, Binder, AddedAtomList[Walker->nr], Walker, OtherAtom, ListOfBondsPerAtom[Walker->nr], NumberOfBondsPerAtom[Walker->nr], IsAngstroem))
+                  exit(1);
 #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))) {
-							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)
+              }
+            }
+          }
+        } 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))) {
+              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
-							if(!Mol->AddHydrogenReplacementAtom(out, Binder, AddedAtomList[Walker->nr], Walker, OtherAtom, ListOfBondsPerAtom[Walker->nr], NumberOfBondsPerAtom[Walker->nr], IsAngstroem))
-								exit(1);
+              if(!Mol->AddHydrogenReplacementAtom(out, Binder, AddedAtomList[Walker->nr], Walker, OtherAtom, ListOfBondsPerAtom[Walker->nr], NumberOfBondsPerAtom[Walker->nr], IsAngstroem))
+                exit(1);
 #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);
+            }
+          }
+        }
+      }
+    }
+    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);
 };
 
@@ -3504,48 +4200,48 @@
 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=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;
+  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=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;
 };
 
@@ -3559,20 +4255,20 @@
 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;
+  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;
 };
 
@@ -3587,104 +4283,267 @@
 molecule * molecule::StoreFragmentFromKeySet(ofstream *out, KeySet &Leaflet, bool IsAngstroem)
 {
-	atom *Runner = NULL, *FatherOfRunner = NULL, *OtherFather = NULL;
-	atom **SonList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::StoreFragmentFromStack: **SonList");
-	molecule *Leaf = new molecule(elemente);
-	bool LonelyFlag = false;
-	int size;
-
-//	*out << Verbose(1) << "Begin of StoreFragmentFromKeyset." << endl;
-
-	Leaf->BondDistance = BondDistance;
-	for(int 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=AtomCount;i--;)
-		SonList[i] = NULL;
-
-	// first create the minimal set of atoms from the KeySet
-	size = 0;
-	for(KeySet::iterator runner = Leaflet.begin(); runner != Leaflet.end(); runner++) {
-		FatherOfRunner = FindAtom((*runner));	// find the id
-		SonList[FatherOfRunner->nr] = Leaf->AddCopyAtom(FatherOfRunner);
-		size++;
-	}
-
-	// 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;
-		LonelyFlag = true;
-		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: ";
-//						*out <<
-						Leaf->AddBond(Runner, SonList[OtherFather->nr], ListOfBondsPerAtom[FatherOfRunner->nr][i]->BondDegree);
-//						*out << "." << endl;
-						//NumBonds[Runner->nr]++;
-					} else {
-//						*out << Verbose(3) << "Not adding bond, labels in wrong order." << endl;
-					}
-					LonelyFlag = false;
-				} else {
-//					*out << ", who has no son in this fragment molecule." << endl;
+  atom *Runner = NULL, *FatherOfRunner = NULL, *OtherFather = NULL;
+  atom **SonList = (atom **) Malloc(sizeof(atom *)*AtomCount, "molecule::StoreFragmentFromStack: **SonList");
+  molecule *Leaf = new molecule(elemente);
+  bool LonelyFlag = false;
+  int size;
+
+//  *out << Verbose(1) << "Begin of StoreFragmentFromKeyset." << endl;
+
+  Leaf->BondDistance = BondDistance;
+  for(int 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=AtomCount;i--;)
+    SonList[i] = NULL;
+
+  // first create the minimal set of atoms from the KeySet
+  size = 0;
+  for(KeySet::iterator runner = Leaflet.begin(); runner != Leaflet.end(); runner++) {
+    FatherOfRunner = FindAtom((*runner));  // find the id
+    SonList[FatherOfRunner->nr] = Leaf->AddCopyAtom(FatherOfRunner);
+    size++;
+  }
+
+  // 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;
+    LonelyFlag = true;
+    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: ";
+//            *out <<
+            Leaf->AddBond(Runner, SonList[OtherFather->nr], ListOfBondsPerAtom[FatherOfRunner->nr][i]->BondDegree);
+//            *out << "." << endl;
+            //NumBonds[Runner->nr]++;
+          } else {
+//            *out << Verbose(3) << "Not adding bond, labels in wrong order." << endl;
+          }
+          LonelyFlag = false;
+        } 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;
-					if(!Leaf->AddHydrogenReplacementAtom(out, ListOfBondsPerAtom[FatherOfRunner->nr][i], Runner, FatherOfRunner, OtherFather, ListOfBondsPerAtom[FatherOfRunner->nr],NumberOfBondsPerAtom[FatherOfRunner->nr], IsAngstroem))
-						exit(1);
+          //*out << Verbose(3) << "Adding Hydrogen to " << Runner->Name << " and a bond in between." << endl;
+          if(!Leaf->AddHydrogenReplacementAtom(out, ListOfBondsPerAtom[FatherOfRunner->nr][i], Runner, FatherOfRunner, OtherFather, ListOfBondsPerAtom[FatherOfRunner->nr],NumberOfBondsPerAtom[FatherOfRunner->nr], IsAngstroem))
+            exit(1);
 #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;
-		}
-		if ((LonelyFlag) && (size > 1)) {
-			*out << Verbose(0) << *Runner << "has got bonds only to hydrogens!" << endl;
-		}
+          //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;
+    }
+    if ((LonelyFlag) && (size > 1)) {
+      *out << Verbose(0) << *Runner << "has got bonds only to hydrogens!" << endl;
+    }
 #ifdef ADDHYDROGEN
-		while ((Runner->next != Leaf->end) && (Runner->next->type->Z == 1)) // skip added hydrogen
-			Runner = Runner->next;
+    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;
-};
+  }
+  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");
+  StackClass<atom *> *RootStack = new StackClass<atom *>(AtomCount);
+  StackClass<atom *> *TouchedStack = new StackClass<atom *>((int)pow(4,Order)+2); // number of atoms reached from one with maximal 4 bonds plus Root itself
+  StackClass<atom *> *SnakeStack = new StackClass<atom *>(Order+1); // equal to Order is not possible, as then the StackClass<atom *> 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)
+        }
+      }
+      *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 (
+              (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;
-	double TEFactor;
-	int *ShortestPathList;
-	bool **UsedList;
-	bond **BondsPerSPList;
-	int *BondsPerSPCount;
+  config *configuration;
+  atom *Root;
+  Graph *Leaflet;
+  KeySet *FragmentSet;
+  int ANOVAOrder;
+  int FragmentCounter;
+  int CurrentIndex;
+  double TEFactor;
+  int *ShortestPathList;
+  bool **UsedList;
+  bond **BondsPerSPList;
+  int *BondsPerSPCount;
 };
 
 /** From a given set of Bond sorted by Shortest Path distance, create all possible fragments of size \a SetDimension.
  * -# loops over every possible combination (2^dimension of edge set)
- *	-# inserts current set, if there's still space left
- *		-# yes: calls SPFragmentGenerator with structure, created new edge list and size respective to root dist
+ *  -# inserts current set, if there's still space left
+ *    -# yes: calls SPFragmentGenerator with structure, created new edge list and size respective to root dist
 ance+1
- *		-# no: stores fragment into keyset list by calling InsertFragmentIntoGraph
- *	-# removes all items added into the snake stack (in UniqueFragments structure) added during level (root
+ *    -# no: stores fragment into keyset list by calling InsertFragmentIntoGraph
+ *  -# removes all items added into the snake stack (in UniqueFragments structure) added during level (root
 distance) and current set
  * \param *out output stream for debugging
@@ -3696,128 +4555,128 @@
 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, Added;
-	int Removal;
-	int SpaceLeft;
-	int *TouchedList = (int *) Malloc(sizeof(int)*(SubOrder+1), "molecule::SPFragmentGenerator: *TouchedList");
-	bond *Binder = NULL;
-	bond **BondsList = NULL;
-	KeySetTestPair TestKeySetInsert;
-
-	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=SubOrder+1;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=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
-			Added = 0;
-			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;
-					*out << Verbose(2+verbosity) << "Adding " << *OtherWalker << " with nr " << OtherWalker->nr << "." << endl;
-					TestKeySetInsert = FragmentSearch->FragmentSet->insert(OtherWalker->nr);
-					if (TestKeySetInsert.second) {
-						TouchedList[TouchedIndex++] = OtherWalker->nr;	// note as added
-						Added++;
-					} else {
-						*out << Verbose(2+verbosity) << "This was item was already present in the keyset." << endl;
-					}
-						//FragmentSearch->UsedList[OtherWalker->nr][i] = true;
-					//}
-				} else {
-					*out << Verbose(2+verbosity) << "Not adding." << endl;
-				}
-			}
-
-			SpaceLeft = SubOrder - Added ;// SubOrder - bits; // due to item's maybe being already present, this does not work anymore
-			if (SpaceLeft > 0) {
-				*out << Verbose(1+verbosity) << "There's still some space left on stack: " << SpaceLeft << "." << endl;
-				if (SubOrder > 1) {		// Due to Added above we have to check extra whether we're not already reaching beyond the desired Order
-					// --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=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 << "], local nr.s are: ";
-				for(KeySet::iterator runner = FragmentSearch->FragmentSet->begin(); runner != FragmentSearch->FragmentSet->end(); runner++)
-					*out << (*runner) << " ";
-				*out << endl;
-				//if (!CheckForConnectedSubgraph(out, FragmentSearch->FragmentSet))
-					//*out << Verbose(0) << "ERROR: The found fragment is not a connected subgraph!" << endl;
-				InsertFragmentIntoGraph(out, FragmentSearch);
-				//Removal = LookForRemovalCandidate(out, FragmentSearch->FragmentSet, FragmentSearch->ShortestPathList);
-				//Removal = StoreFragmentFromStack(out, FragmentSearch->Root, FragmentSearch->Leaflet, FragmentSearch->FragmentStack, FragmentSearch->ShortestPathList, &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 << " from snake stack." << endl;
-				FragmentSearch->FragmentSet->erase(Removal);
-				TouchedList[j] = -1;
-			}
-			*out << Verbose(2) << "Remaining local nr.s on snake stack are: ";
-			for(KeySet::iterator runner = FragmentSearch->FragmentSet->begin(); runner != FragmentSearch->FragmentSet->end(); runner++)
-				*out << (*runner) << " ";
-			*out << endl;
-			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;
+  atom *OtherWalker = NULL;
+  int verbosity = 0; //FragmentSearch->ANOVAOrder-SubOrder;
+  int NumCombinations;
+  bool bit;
+  int bits, TouchedIndex, SubSetDimension, SP, Added;
+  int Removal;
+  int SpaceLeft;
+  int *TouchedList = (int *) Malloc(sizeof(int)*(SubOrder+1), "molecule::SPFragmentGenerator: *TouchedList");
+  bond *Binder = NULL;
+  bond **BondsList = NULL;
+  KeySetTestPair TestKeySetInsert;
+
+  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=SubOrder+1;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=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
+      Added = 0;
+      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;
+          *out << Verbose(2+verbosity) << "Adding " << *OtherWalker << " with nr " << OtherWalker->nr << "." << endl;
+          TestKeySetInsert = FragmentSearch->FragmentSet->insert(OtherWalker->nr);
+          if (TestKeySetInsert.second) {
+            TouchedList[TouchedIndex++] = OtherWalker->nr;  // note as added
+            Added++;
+          } else {
+            *out << Verbose(2+verbosity) << "This was item was already present in the keyset." << endl;
+          }
+            //FragmentSearch->UsedList[OtherWalker->nr][i] = true;
+          //}
+        } else {
+          *out << Verbose(2+verbosity) << "Not adding." << endl;
+        }
+      }
+
+      SpaceLeft = SubOrder - Added ;// SubOrder - bits; // due to item's maybe being already present, this does not work anymore
+      if (SpaceLeft > 0) {
+        *out << Verbose(1+verbosity) << "There's still some space left on stack: " << SpaceLeft << "." << endl;
+        if (SubOrder > 1) {    // Due to Added above we have to check extra whether we're not already reaching beyond the desired Order
+          // --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=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 << "], local nr.s are: ";
+        for(KeySet::iterator runner = FragmentSearch->FragmentSet->begin(); runner != FragmentSearch->FragmentSet->end(); runner++)
+          *out << (*runner) << " ";
+        *out << endl;
+        //if (!CheckForConnectedSubgraph(out, FragmentSearch->FragmentSet))
+          //*out << Verbose(0) << "ERROR: The found fragment is not a connected subgraph!" << endl;
+        InsertFragmentIntoGraph(out, FragmentSearch);
+        //Removal = LookForRemovalCandidate(out, FragmentSearch->FragmentSet, FragmentSearch->ShortestPathList);
+        //Removal = StoreFragmentFromStack(out, FragmentSearch->Root, FragmentSearch->Leaflet, FragmentSearch->FragmentStack, FragmentSearch->ShortestPathList, &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 << " from snake stack." << endl;
+        FragmentSearch->FragmentSet->erase(Removal);
+        TouchedList[j] = -1;
+      }
+      *out << Verbose(2) << "Remaining local nr.s on snake stack are: ";
+      for(KeySet::iterator runner = FragmentSearch->FragmentSet->begin(); runner != FragmentSearch->FragmentSet->end(); runner++)
+        *out << (*runner) << " ";
+      *out << endl;
+      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;
 };
 
@@ -3830,44 +4689,44 @@
 bool molecule::CheckForConnectedSubgraph(ofstream *out, KeySet *Fragment)
 {
-	atom *Walker = NULL, *Walker2 = NULL;
-	bool BondStatus = false;
-	int size;
-
-	*out << Verbose(1) << "Begin of CheckForConnectedSubgraph" << endl;
-	*out << Verbose(2) << "Disconnected atom: ";
-
-	// count number of atoms in graph
-	size = 0;
-	for(KeySet::iterator runner = Fragment->begin(); runner != Fragment->end(); runner++)
-		size++;
-	if (size > 1)
-		for(KeySet::iterator runner = Fragment->begin(); runner != Fragment->end(); runner++) {
-			Walker = FindAtom(*runner);
-			BondStatus = false;
-			for(KeySet::iterator runners = Fragment->begin(); runners != Fragment->end(); runners++) {
-				Walker2 = FindAtom(*runners);
-				for (int i=0;i<NumberOfBondsPerAtom[Walker->nr]; i++) {
-					if (ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker) == Walker2) {
-						BondStatus = true;
-						break;
-					}
-					if (BondStatus)
-						break;
-				}
-			}
-			if (!BondStatus) {
-				*out << (*Walker) << endl;
-				return false;
-			}
-		}
-	else {
-		*out << "none." << endl;
-		return true;
-	}
-	*out << "none." << endl;
-
-	*out << Verbose(1) << "End of CheckForConnectedSubgraph" << endl;
-
-	return true;
+  atom *Walker = NULL, *Walker2 = NULL;
+  bool BondStatus = false;
+  int size;
+
+  *out << Verbose(1) << "Begin of CheckForConnectedSubgraph" << endl;
+  *out << Verbose(2) << "Disconnected atom: ";
+
+  // count number of atoms in graph
+  size = 0;
+  for(KeySet::iterator runner = Fragment->begin(); runner != Fragment->end(); runner++)
+    size++;
+  if (size > 1)
+    for(KeySet::iterator runner = Fragment->begin(); runner != Fragment->end(); runner++) {
+      Walker = FindAtom(*runner);
+      BondStatus = false;
+      for(KeySet::iterator runners = Fragment->begin(); runners != Fragment->end(); runners++) {
+        Walker2 = FindAtom(*runners);
+        for (int i=0;i<NumberOfBondsPerAtom[Walker->nr]; i++) {
+          if (ListOfBondsPerAtom[Walker->nr][i]->GetOtherAtom(Walker) == Walker2) {
+            BondStatus = true;
+            break;
+          }
+          if (BondStatus)
+            break;
+        }
+      }
+      if (!BondStatus) {
+        *out << (*Walker) << endl;
+        return false;
+      }
+    }
+  else {
+    *out << "none." << endl;
+    return true;
+  }
+  *out << "none." << endl;
+
+  *out << Verbose(1) << "End of CheckForConnectedSubgraph" << endl;
+
+  return true;
 }
 
@@ -3889,146 +4748,146 @@
 int molecule::PowerSetGenerator(ofstream *out, int Order, struct UniqueFragments &FragmentSearch, KeySet RestrictedKeySet)
 {
-	int SP, AtomKeyNr;
-	atom *Walker = NULL, *OtherWalker = NULL, *Predecessor = NULL;
-	bond *Binder = NULL;
-	bond *CurrentEdge = NULL;
-	bond **BondsList = NULL;
-	int RootKeyNr = FragmentSearch.Root->GetTrueFather()->nr;
-	int Counter = FragmentSearch.FragmentCounter;
-	int RemainingWalkers;
-
-	*out << endl;
-	*out << Verbose(0) << "Begin of PowerSetGenerator with order " << Order << " at Root " << *FragmentSearch.Root << "." << endl;
-
-	// prepare Label and SP arrays of the BFS search
-	FragmentSearch.ShortestPathList[FragmentSearch.Root->nr] = 0;
-
-	// prepare root level (SP = 0) and a loop bond denoting Root
-	for (int i=1;i<Order;i++)
-		FragmentSearch.BondsPerSPCount[i] = 0;
-	FragmentSearch.BondsPerSPCount[0] = 1;
-	Binder = new bond(FragmentSearch.Root, FragmentSearch.Root);
-	add(Binder, FragmentSearch.BondsPerSPList[1]);
-
-	// do a BFS search to fill the SP lists and label the found vertices
-	// Actually, we should construct a spanning tree vom the root atom and select all edges therefrom and put them into
-	// according shortest path lists. However, we don't. Rather we fill these lists right away, as they do form a spanning
-	// tree already sorted into various SP levels. That's why we just do loops over the depth (CurrentSP) and breadth
-	// (EdgeinSPLevel) of this tree ...
-	// In another picture, the bonds always contain a direction by rightatom being the one more distant from root and hence
-	// naturally leftatom forming its predecessor, preventing the BFS"seeker" from continuing in the wrong direction.
-	*out << endl;
-	*out << Verbose(0) << "Starting BFS analysis ..." << endl;
-	for (SP = 0; SP < (Order-1); SP++) {
-		*out << Verbose(1) << "New SP level reached: " << SP << ", creating new SP list with " << FragmentSearch.BondsPerSPCount[SP] << " item(s)";
-		if (SP > 0) {
-			*out << ", old level closed with " << FragmentSearch.BondsPerSPCount[SP-1] << " item(s)." << endl;
-			FragmentSearch.BondsPerSPCount[SP] = 0;
-		} else
-			*out << "." << endl;
-
-		RemainingWalkers = FragmentSearch.BondsPerSPCount[SP];
-		CurrentEdge = FragmentSearch.BondsPerSPList[2*SP];		/// start of this SP level's list
-		while (CurrentEdge->next != FragmentSearch.BondsPerSPList[2*SP+1]) {		/// end of this SP level's list
-			CurrentEdge = CurrentEdge->next;
-			RemainingWalkers--;
-			Walker = CurrentEdge->rightatom;		// rightatom is always the one more distant
-			Predecessor = CurrentEdge->leftatom;		// ... and leftatom is predecessor
-			AtomKeyNr = Walker->nr;
-			*out << Verbose(0) << "Current Walker is: " << *Walker << " with nr " << Walker->nr << " and SP of " << SP << ", with " << RemainingWalkers << " remaining walkers on this level." << endl;
-			// check for new sp level
-			// go through all its bonds
-			*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 ((RestrictedKeySet.find(OtherWalker->nr) != RestrictedKeySet.end())
-	#ifdef ADDHYDROGEN
-				 && (OtherWalker->type->Z != 1)
-	#endif
-																															) {	// skip hydrogens and restrict to fragment
-					*out << Verbose(2) << "Current partner is " << *OtherWalker << " with nr " << OtherWalker->nr << " in bond " << *Binder << "." << endl;
-					// set the label if not set (and push on root stack as well)
-					if ((OtherWalker != Predecessor) && (OtherWalker->GetTrueFather()->nr > RootKeyNr)) { // only pass through those with label bigger than Root's
-						FragmentSearch.ShortestPathList[OtherWalker->nr] = SP+1;
-						*out << Verbose(3) << "Set Shortest Path to " << FragmentSearch.ShortestPathList[OtherWalker->nr] << "." << endl;
-						// add the bond in between to the SP list
-						Binder = new bond(Walker, OtherWalker); // create a new bond in such a manner, that bond::rightatom is always the one more distant
-						add(Binder, FragmentSearch.BondsPerSPList[2*(SP+1)+1]);
-						FragmentSearch.BondsPerSPCount[SP+1]++;
-						*out << Verbose(3) << "Added its bond to SP list, having now " << FragmentSearch.BondsPerSPCount[SP+1] << " item(s)." << endl;
-					} else {
-						if (OtherWalker != Predecessor)
-							*out << Verbose(3) << "Not passing on, as index of " << *OtherWalker << " " << OtherWalker->GetTrueFather()->nr << " is smaller than that of Root " << RootKeyNr << "." << endl;
-						else
-							*out << Verbose(3) << "This is my predecessor " << *Predecessor << "." << endl;
-					}
-				} else *out << Verbose(2) << "Is not in the restricted keyset or skipping hydrogen " << *OtherWalker << "." << endl;
-			}
-		}
-	}
-
-	// outputting all list for debugging
-	*out << Verbose(0) << "Printing all found lists." << endl;
-	for(int i=1;i<Order;i++) {		// skip the root edge in the printing
-		Binder = FragmentSearch.BondsPerSPList[2*i];
-		*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	(may be done in reverse order, faster)
-	SP = -1;	// the Root <-> Root edge must be subtracted!
-	for(int 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 << ", local nr is " << FragmentSearch.Root->nr << "." << endl;
-		FragmentSearch.FragmentSet->clear();
-		*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::PowerSetGenerator: **BondsList");
-		BondsList[0] = FragmentSearch.BondsPerSPList[0]->next;	// on SP level 0 there's only the root bond
-
-		SPFragmentGenerator(out, &FragmentSearch, 0, BondsList, FragmentSearch.BondsPerSPCount[0], Order);
-
-		Free((void **)&BondsList, "molecule::PowerSetGenerator: **BondsList");
-	} else {
-		*out << Verbose(0) << "Not enough total number of edges to build " << Order << "-body fragments." << endl;
-	}
-
-	// as FragmentSearch structure is used only once, we don't have to clean it anymore
-	// remove root from stack
-	*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=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;
-			// *out << "Removing atom " << Binder->leftatom->nr << " and " << Binder->rightatom->nr << "." << endl; // make sure numbers are local
-			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;
-	}
-
-	// return list
-	*out << Verbose(0) << "End of PowerSetGenerator." << endl;
-	return (FragmentSearch.FragmentCounter - Counter);
+  int SP, AtomKeyNr;
+  atom *Walker = NULL, *OtherWalker = NULL, *Predecessor = NULL;
+  bond *Binder = NULL;
+  bond *CurrentEdge = NULL;
+  bond **BondsList = NULL;
+  int RootKeyNr = FragmentSearch.Root->GetTrueFather()->nr;
+  int Counter = FragmentSearch.FragmentCounter;
+  int RemainingWalkers;
+
+  *out << endl;
+  *out << Verbose(0) << "Begin of PowerSetGenerator with order " << Order << " at Root " << *FragmentSearch.Root << "." << endl;
+
+  // prepare Label and SP arrays of the BFS search
+  FragmentSearch.ShortestPathList[FragmentSearch.Root->nr] = 0;
+
+  // prepare root level (SP = 0) and a loop bond denoting Root
+  for (int i=1;i<Order;i++)
+    FragmentSearch.BondsPerSPCount[i] = 0;
+  FragmentSearch.BondsPerSPCount[0] = 1;
+  Binder = new bond(FragmentSearch.Root, FragmentSearch.Root);
+  add(Binder, FragmentSearch.BondsPerSPList[1]);
+
+  // do a BFS search to fill the SP lists and label the found vertices
+  // Actually, we should construct a spanning tree vom the root atom and select all edges therefrom and put them into
+  // according shortest path lists. However, we don't. Rather we fill these lists right away, as they do form a spanning
+  // tree already sorted into various SP levels. That's why we just do loops over the depth (CurrentSP) and breadth
+  // (EdgeinSPLevel) of this tree ...
+  // In another picture, the bonds always contain a direction by rightatom being the one more distant from root and hence
+  // naturally leftatom forming its predecessor, preventing the BFS"seeker" from continuing in the wrong direction.
+  *out << endl;
+  *out << Verbose(0) << "Starting BFS analysis ..." << endl;
+  for (SP = 0; SP < (Order-1); SP++) {
+    *out << Verbose(1) << "New SP level reached: " << SP << ", creating new SP list with " << FragmentSearch.BondsPerSPCount[SP] << " item(s)";
+    if (SP > 0) {
+      *out << ", old level closed with " << FragmentSearch.BondsPerSPCount[SP-1] << " item(s)." << endl;
+      FragmentSearch.BondsPerSPCount[SP] = 0;
+    } else
+      *out << "." << endl;
+
+    RemainingWalkers = FragmentSearch.BondsPerSPCount[SP];
+    CurrentEdge = FragmentSearch.BondsPerSPList[2*SP];    /// start of this SP level's list
+    while (CurrentEdge->next != FragmentSearch.BondsPerSPList[2*SP+1]) {    /// end of this SP level's list
+      CurrentEdge = CurrentEdge->next;
+      RemainingWalkers--;
+      Walker = CurrentEdge->rightatom;    // rightatom is always the one more distant
+      Predecessor = CurrentEdge->leftatom;    // ... and leftatom is predecessor
+      AtomKeyNr = Walker->nr;
+      *out << Verbose(0) << "Current Walker is: " << *Walker << " with nr " << Walker->nr << " and SP of " << SP << ", with " << RemainingWalkers << " remaining walkers on this level." << endl;
+      // check for new sp level
+      // go through all its bonds
+      *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 ((RestrictedKeySet.find(OtherWalker->nr) != RestrictedKeySet.end())
+  #ifdef ADDHYDROGEN
+         && (OtherWalker->type->Z != 1)
+  #endif
+                                                              ) {  // skip hydrogens and restrict to fragment
+          *out << Verbose(2) << "Current partner is " << *OtherWalker << " with nr " << OtherWalker->nr << " in bond " << *Binder << "." << endl;
+          // set the label if not set (and push on root stack as well)
+          if ((OtherWalker != Predecessor) && (OtherWalker->GetTrueFather()->nr > RootKeyNr)) { // only pass through those with label bigger than Root's
+            FragmentSearch.ShortestPathList[OtherWalker->nr] = SP+1;
+            *out << Verbose(3) << "Set Shortest Path to " << FragmentSearch.ShortestPathList[OtherWalker->nr] << "." << endl;
+            // add the bond in between to the SP list
+            Binder = new bond(Walker, OtherWalker); // create a new bond in such a manner, that bond::rightatom is always the one more distant
+            add(Binder, FragmentSearch.BondsPerSPList[2*(SP+1)+1]);
+            FragmentSearch.BondsPerSPCount[SP+1]++;
+            *out << Verbose(3) << "Added its bond to SP list, having now " << FragmentSearch.BondsPerSPCount[SP+1] << " item(s)." << endl;
+          } else {
+            if (OtherWalker != Predecessor)
+              *out << Verbose(3) << "Not passing on, as index of " << *OtherWalker << " " << OtherWalker->GetTrueFather()->nr << " is smaller than that of Root " << RootKeyNr << "." << endl;
+            else
+              *out << Verbose(3) << "This is my predecessor " << *Predecessor << "." << endl;
+          }
+        } else *out << Verbose(2) << "Is not in the restricted keyset or skipping hydrogen " << *OtherWalker << "." << endl;
+      }
+    }
+  }
+
+  // outputting all list for debugging
+  *out << Verbose(0) << "Printing all found lists." << endl;
+  for(int i=1;i<Order;i++) {    // skip the root edge in the printing
+    Binder = FragmentSearch.BondsPerSPList[2*i];
+    *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  (may be done in reverse order, faster)
+  SP = -1;  // the Root <-> Root edge must be subtracted!
+  for(int 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 << ", local nr is " << FragmentSearch.Root->nr << "." << endl;
+    FragmentSearch.FragmentSet->clear();
+    *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::PowerSetGenerator: **BondsList");
+    BondsList[0] = FragmentSearch.BondsPerSPList[0]->next;  // on SP level 0 there's only the root bond
+
+    SPFragmentGenerator(out, &FragmentSearch, 0, BondsList, FragmentSearch.BondsPerSPCount[0], Order);
+
+    Free((void **)&BondsList, "molecule::PowerSetGenerator: **BondsList");
+  } else {
+    *out << Verbose(0) << "Not enough total number of edges to build " << Order << "-body fragments." << endl;
+  }
+
+  // as FragmentSearch structure is used only once, we don't have to clean it anymore
+  // remove root from stack
+  *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=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;
+      // *out << "Removing atom " << Binder->leftatom->nr << " and " << Binder->rightatom->nr << "." << endl; // make sure numbers are local
+      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;
+  }
+
+  // return list
+  *out << Verbose(0) << "End of PowerSetGenerator." << endl;
+  return (FragmentSearch.FragmentCounter - Counter);
 };
 
@@ -4041,82 +4900,82 @@
 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;
-	//class StackClass<atom *> *CompStack = NULL;
-	class StackClass<atom *> *AtomStack = new StackClass<atom *>(AtomCount);
-	bool flag = true;
-
-	*out << Verbose(2) << "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=NDIM;i--;)
-			Translationvector.x[i] = 0.;
-		// scan all bonds
-		Binder = first;
-		flag = false;
-		while ((!flag) && (Binder->next != last)) {
-			Binder = Binder->next;
-			for (int 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=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 << Verbose(3) << "Translation vector is ";
-			Translationvector.Output(out);
-			*out << endl;
-			// apply to all atoms of first component via BFS
-			for (int 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(3) << "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(2) << "End of ScanForPeriodicCorrection." << endl;
+  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;
+  //class StackClass<atom *> *CompStack = NULL;
+  class StackClass<atom *> *AtomStack = new StackClass<atom *>(AtomCount);
+  bool flag = true;
+
+  *out << Verbose(2) << "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=NDIM;i--;)
+      Translationvector.x[i] = 0.;
+    // scan all bonds
+    Binder = first;
+    flag = false;
+    while ((!flag) && (Binder->next != last)) {
+      Binder = Binder->next;
+      for (int 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=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 << Verbose(3) << "Translation vector is ";
+      Translationvector.Output(out);
+      *out << endl;
+      // apply to all atoms of first component via BFS
+      for (int 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(3) << "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(2) << "End of ScanForPeriodicCorrection." << endl;
 };
 
@@ -4127,45 +4986,45 @@
 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;
+  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
+  //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);
+//  return KeyCompare(SubgraphA, SubgraphB);
 //};
 
@@ -4179,23 +5038,23 @@
 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;	// increase the "created" counter
-		*out << Verbose(2) << "New factor is " << ((*(testGraphInsert.first)).second).second << "." << endl;
-	}
+  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;  // increase the "created" counter
+    *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);
+//  // 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);
 //};
 
@@ -4208,16 +5067,16 @@
 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;
-		}
-	}
+  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;
+    }
+  }
 };
 
@@ -4226,9 +5085,9 @@
  * -# constructs a complete keyset of the molecule
  * -# In a loop over all possible roots from the given rootstack
- *	-# increases order of root site
- *	-# calls PowerSetGenerator with this order, the complete keyset and the rootkeynr
- *	-# for all consecutive lower levels PowerSetGenerator is called with the suborder, the higher order keyset
+ *  -# increases order of root site
+ *  -# calls PowerSetGenerator with this order, the complete keyset and the rootkeynr
+ *  -# for all consecutive lower levels PowerSetGenerator is called with the suborder, the higher order keyset
 as the restricted one and each site in the set as the root)
- *	-# these are merged into a fragment list of keysets
+ *  -# these are merged into a fragment list of keysets
  * -# All fragment lists (for all orders, i.e. from all destination fields) are merged into one list for return
  * Important only is that we create all fragments, it is not important if we create them more than once
@@ -4242,185 +5101,185 @@
 void molecule::FragmentBOSSANOVA(ofstream *out, Graph *&FragmentList, KeyStack &RootStack, int *MinimumRingSize)
 {
-	Graph ***FragmentLowerOrdersList = NULL;
-	int NumLevels, NumMolecules, TotalNumMolecules = 0, *NumMoleculesOfOrder = NULL;
-	int counter = 0, Order;
-	int UpgradeCount = RootStack.size();
-	KeyStack FragmentRootStack;
-	int RootKeyNr, RootNr;
-	struct UniqueFragments FragmentSearch;
-
-	*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)*UpgradeCount, "molecule::FragmentBOSSANOVA: *NumMoleculesOfOrder");
-	FragmentLowerOrdersList = (Graph ***) Malloc(sizeof(Graph **)*UpgradeCount, "molecule::FragmentBOSSANOVA: ***FragmentLowerOrdersList");
-
-	// initialise the fragments structure
-	FragmentSearch.ShortestPathList = (int *) Malloc(sizeof(int)*AtomCount, "molecule::PowerSetGenerator: *ShortestPathList");
-	FragmentSearch.FragmentCounter = 0;
-	FragmentSearch.FragmentSet = new KeySet;
-	FragmentSearch.Root = FindAtom(RootKeyNr);
-	for (int i=AtomCount;i--;) {
-		FragmentSearch.ShortestPathList[i] = -1;
-	}
-
-	// Construct the complete KeySet which we need for topmost level only (but for all Roots)
-	atom *Walker = start;
-	KeySet CompleteMolecule;
-	while (Walker->next != end) {
-		Walker = Walker->next;
-		CompleteMolecule.insert(Walker->GetTrueFather()->nr);
-	}
-
-	// 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)
-	RootNr = 0;	 // counts through the roots in RootStack
-	while ((RootNr < UpgradeCount) && (!RootStack.empty())) {
-		RootKeyNr = RootStack.front();
-		RootStack.pop_front();
-		Walker = FindAtom(RootKeyNr);
-		// check cyclic lengths
-		//if ((MinimumRingSize[Walker->GetTrueFather()->nr] != -1) && (Walker->GetTrueFather()->AdaptiveOrder+1 > MinimumRingSize[Walker->GetTrueFather()->nr])) {
-		//	*out << Verbose(0) << "Bond order " << Walker->GetTrueFather()->AdaptiveOrder << " of Root " << *Walker << " greater than or equal to Minimum Ring size of " << MinimumRingSize << " found is not allowed." << endl;
-		//} else
-		{
-			// increase adaptive order by one
-			Walker->GetTrueFather()->AdaptiveOrder++;
-			Order = Walker->AdaptiveOrder = Walker->GetTrueFather()->AdaptiveOrder;
-
-			// initialise Order-dependent entries of UniqueFragments structure
-			FragmentSearch.BondsPerSPList = (bond **) Malloc(sizeof(bond *)*Order*2, "molecule::PowerSetGenerator: ***BondsPerSPList");
-			FragmentSearch.BondsPerSPCount = (int *) Malloc(sizeof(int)*Order, "molecule::PowerSetGenerator: *BondsPerSPCount");
-			for (int 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;
-			}
-
-			// allocate memory for all lower level orders in this 1D-array of ptrs
-			NumLevels = 1 << (Order-1); // (int)pow(2,Order);
-			FragmentLowerOrdersList[RootNr] = (Graph **) Malloc(sizeof(Graph *)*NumLevels, "molecule::FragmentBOSSANOVA: **FragmentLowerOrdersList[]");
-			for (int i=0;i<NumLevels;i++)
-				FragmentLowerOrdersList[RootNr][i] = NULL;
-
-			// create top order where nothing is reduced
-			*out << Verbose(0) << "==============================================================================================================" << endl;
-			*out << Verbose(0) << "Creating KeySets of Bond Order " << Order << " for " << *Walker << ", " << (RootStack.size()-RootNr) << " Roots remaining." << endl; // , NumLevels is " << NumLevels << "
-
-			// Create list of Graphs of current Bond Order (i.e. F_{ij})
-			FragmentLowerOrdersList[RootNr][0] =	new Graph;
-			FragmentSearch.TEFactor = 1.;
-			FragmentSearch.Leaflet = FragmentLowerOrdersList[RootNr][0];			// set to insertion graph
-			FragmentSearch.Root = Walker;
-			NumMoleculesOfOrder[RootNr] = PowerSetGenerator(out, Walker->AdaptiveOrder, FragmentSearch, CompleteMolecule);
-			*out << Verbose(1) << "Number of resulting KeySets is: " << NumMoleculesOfOrder[RootNr] << "." << endl;
-			if (NumMoleculesOfOrder[RootNr] != 0) {
-				NumMolecules = 0;
-
-				// we don't have to dive into suborders! These keysets are all already created on lower orders!
-				// this was all ancient stuff, when we still depended on the TEFactors (and for those the suborders were needed)
-
-//				if ((NumLevels >> 1) > 0) {
-//					// create lower order fragments
-//					*out << Verbose(0) << "Creating list of unique fragments of lower Bond Order terms to be subtracted." << endl;
-//					Order = Walker->AdaptiveOrder;
-//					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 << (Walker->AdaptiveOrder-Order))) // (int)pow(2,Walker->AdaptiveOrder-Order))
-//							Order--;
-//						*out << Verbose(0) << "Current Order is: " << Order << "." << endl;
-//						for (int SubOrder=Order-1;SubOrder>0;SubOrder--) {
-//							int dest = source + (1 << (Walker->AdaptiveOrder-(SubOrder+1)));
-//							*out << Verbose(0) << "--------------------------------------------------------------------------------------------------------------" << endl;
-//							*out << Verbose(0) << "Current SubOrder is: " << SubOrder << " with source " << source << " to destination " << dest << "." << endl;
+  Graph ***FragmentLowerOrdersList = NULL;
+  int NumLevels, NumMolecules, TotalNumMolecules = 0, *NumMoleculesOfOrder = NULL;
+  int counter = 0, Order;
+  int UpgradeCount = RootStack.size();
+  KeyStack FragmentRootStack;
+  int RootKeyNr, RootNr;
+  struct UniqueFragments FragmentSearch;
+
+  *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)*UpgradeCount, "molecule::FragmentBOSSANOVA: *NumMoleculesOfOrder");
+  FragmentLowerOrdersList = (Graph ***) Malloc(sizeof(Graph **)*UpgradeCount, "molecule::FragmentBOSSANOVA: ***FragmentLowerOrdersList");
+
+  // initialise the fragments structure
+  FragmentSearch.ShortestPathList = (int *) Malloc(sizeof(int)*AtomCount, "molecule::PowerSetGenerator: *ShortestPathList");
+  FragmentSearch.FragmentCounter = 0;
+  FragmentSearch.FragmentSet = new KeySet;
+  FragmentSearch.Root = FindAtom(RootKeyNr);
+  for (int i=AtomCount;i--;) {
+    FragmentSearch.ShortestPathList[i] = -1;
+  }
+
+  // Construct the complete KeySet which we need for topmost level only (but for all Roots)
+  atom *Walker = start;
+  KeySet CompleteMolecule;
+  while (Walker->next != end) {
+    Walker = Walker->next;
+    CompleteMolecule.insert(Walker->GetTrueFather()->nr);
+  }
+
+  // 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)
+  RootNr = 0;   // counts through the roots in RootStack
+  while ((RootNr < UpgradeCount) && (!RootStack.empty())) {
+    RootKeyNr = RootStack.front();
+    RootStack.pop_front();
+    Walker = FindAtom(RootKeyNr);
+    // check cyclic lengths
+    //if ((MinimumRingSize[Walker->GetTrueFather()->nr] != -1) && (Walker->GetTrueFather()->AdaptiveOrder+1 > MinimumRingSize[Walker->GetTrueFather()->nr])) {
+    //  *out << Verbose(0) << "Bond order " << Walker->GetTrueFather()->AdaptiveOrder << " of Root " << *Walker << " greater than or equal to Minimum Ring size of " << MinimumRingSize << " found is not allowed." << endl;
+    //} else
+    {
+      // increase adaptive order by one
+      Walker->GetTrueFather()->AdaptiveOrder++;
+      Order = Walker->AdaptiveOrder = Walker->GetTrueFather()->AdaptiveOrder;
+
+      // initialise Order-dependent entries of UniqueFragments structure
+      FragmentSearch.BondsPerSPList = (bond **) Malloc(sizeof(bond *)*Order*2, "molecule::PowerSetGenerator: ***BondsPerSPList");
+      FragmentSearch.BondsPerSPCount = (int *) Malloc(sizeof(int)*Order, "molecule::PowerSetGenerator: *BondsPerSPCount");
+      for (int 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;
+      }
+
+      // allocate memory for all lower level orders in this 1D-array of ptrs
+      NumLevels = 1 << (Order-1); // (int)pow(2,Order);
+      FragmentLowerOrdersList[RootNr] = (Graph **) Malloc(sizeof(Graph *)*NumLevels, "molecule::FragmentBOSSANOVA: **FragmentLowerOrdersList[]");
+      for (int i=0;i<NumLevels;i++)
+        FragmentLowerOrdersList[RootNr][i] = NULL;
+
+      // create top order where nothing is reduced
+      *out << Verbose(0) << "==============================================================================================================" << endl;
+      *out << Verbose(0) << "Creating KeySets of Bond Order " << Order << " for " << *Walker << ", " << (RootStack.size()-RootNr) << " Roots remaining." << endl; // , NumLevels is " << NumLevels << "
+
+      // Create list of Graphs of current Bond Order (i.e. F_{ij})
+      FragmentLowerOrdersList[RootNr][0] =  new Graph;
+      FragmentSearch.TEFactor = 1.;
+      FragmentSearch.Leaflet = FragmentLowerOrdersList[RootNr][0];      // set to insertion graph
+      FragmentSearch.Root = Walker;
+      NumMoleculesOfOrder[RootNr] = PowerSetGenerator(out, Walker->AdaptiveOrder, FragmentSearch, CompleteMolecule);
+      *out << Verbose(1) << "Number of resulting KeySets is: " << NumMoleculesOfOrder[RootNr] << "." << endl;
+      if (NumMoleculesOfOrder[RootNr] != 0) {
+        NumMolecules = 0;
+
+        // we don't have to dive into suborders! These keysets are all already created on lower orders!
+        // this was all ancient stuff, when we still depended on the TEFactors (and for those the suborders were needed)
+
+//        if ((NumLevels >> 1) > 0) {
+//          // create lower order fragments
+//          *out << Verbose(0) << "Creating list of unique fragments of lower Bond Order terms to be subtracted." << endl;
+//          Order = Walker->AdaptiveOrder;
+//          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 << (Walker->AdaptiveOrder-Order))) // (int)pow(2,Walker->AdaptiveOrder-Order))
+//              Order--;
+//            *out << Verbose(0) << "Current Order is: " << Order << "." << endl;
+//            for (int SubOrder=Order-1;SubOrder>0;SubOrder--) {
+//              int dest = source + (1 << (Walker->AdaptiveOrder-(SubOrder+1)));
+//              *out << Verbose(0) << "--------------------------------------------------------------------------------------------------------------" << endl;
+//              *out << Verbose(0) << "Current SubOrder is: " << SubOrder << " 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[RootNr][source]).size() << " molecules of the " << source << "th cell in the array." << endl;
-//							//NumMolecules = 0;
-//							FragmentLowerOrdersList[RootNr][dest] = new Graph;
-//							for(Graph::iterator runner = (*FragmentLowerOrdersList[RootNr][source]).begin();runner != (*FragmentLowerOrdersList[RootNr][source]).end(); runner++) {
-//								for (KeySet::iterator sprinter = (*runner).first.begin();sprinter != (*runner).first.end(); sprinter++) {
-//									Graph TempFragmentList;
-//									FragmentSearch.TEFactor = -(*runner).second.second;
-//									FragmentSearch.Leaflet = &TempFragmentList;			// set to insertion graph
-//									FragmentSearch.Root = FindAtom(*sprinter);
-//									NumMoleculesOfOrder[RootNr] += PowerSetGenerator(out, SubOrder, FragmentSearch, (*runner).first);
-//									// insert new keysets FragmentList into FragmentLowerOrdersList[Walker->AdaptiveOrder-1][dest]
-//									*out << Verbose(1) << "Merging resulting key sets with those present in destination " << dest << "." << endl;
-//									InsertGraphIntoGraph(out, *FragmentLowerOrdersList[RootNr][dest], TempFragmentList, &NumMolecules);
-//								}
-//							}
-//							*out << Verbose(1) << "Number of resulting molecules for SubOrder " << SubOrder << " is: " << NumMolecules << "." << endl;
-//						}
-//					}
-//				}
-			} else {
-				Walker->GetTrueFather()->MaxOrder = true;
-//				*out << Verbose(1) << "Hence, we don't dive into SubOrders ... " << endl;
-			}
-			// now, we have completely filled each cell of FragmentLowerOrdersList[] for the current Walker->AdaptiveOrder
-			//NumMoleculesOfOrder[Walker->AdaptiveOrder-1] = NumMolecules;
-			TotalNumMolecules += NumMoleculesOfOrder[RootNr];
-//			*out << Verbose(1) << "Number of resulting molecules for Order " << (int)Walker->GetTrueFather()->AdaptiveOrder << " is: " << NumMoleculesOfOrder[RootNr] << "." << endl;
-			RootStack.push_back(RootKeyNr); // put back on stack
-			RootNr++;
-
-			// free Order-dependent entries of UniqueFragments structure for next loop cycle
-			Free((void **)&FragmentSearch.BondsPerSPCount, "molecule::PowerSetGenerator: *BondsPerSPCount");
-			for (int i=Order;i--;) {
-				delete(FragmentSearch.BondsPerSPList[2*i]);
-				delete(FragmentSearch.BondsPerSPList[2*i+1]);
-			}
-			Free((void **)&FragmentSearch.BondsPerSPList, "molecule::PowerSetGenerator: ***BondsPerSPList");
-		}
-	}
-	*out << Verbose(0) << "==============================================================================================================" << endl;
-	*out << Verbose(1) << "Total number of resulting molecules is: " << TotalNumMolecules << "." << endl;
-	*out << Verbose(0) << "==============================================================================================================" << endl;
-
-	// cleanup FragmentSearch structure
-	Free((void **)&FragmentSearch.ShortestPathList, "molecule::PowerSetGenerator: *ShortestPathList");
-	delete(FragmentSearch.FragmentSet);
-
-	// 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 all into a single list (FragmentList)
-
-	*out << Verbose(0) << "Combining the lists of all orders per order and finally into a single one." << endl;
-	if (FragmentList == NULL) {
-		FragmentList = new Graph;
-		counter = 0;
-	} else {
-		counter = FragmentList->size();
-	}
-	RootNr = 0;
-	while (!RootStack.empty()) {
-		RootKeyNr = RootStack.front();
-		RootStack.pop_front();
-		Walker = FindAtom(RootKeyNr);
-		NumLevels = 1 << (Walker->AdaptiveOrder - 1);
-		for(int i=0;i<NumLevels;i++) {
-			if (FragmentLowerOrdersList[RootNr][i] != NULL) {
-				InsertGraphIntoGraph(out, *FragmentList, (*FragmentLowerOrdersList[RootNr][i]), &counter);
-				delete(FragmentLowerOrdersList[RootNr][i]);
-			}
-		}
-		Free((void **)&FragmentLowerOrdersList[RootNr], "molecule::FragmentBOSSANOVA: **FragmentLowerOrdersList[]");
-		RootNr++;
-	}
-	Free((void **)&FragmentLowerOrdersList, "molecule::FragmentBOSSANOVA: ***FragmentLowerOrdersList");
-	Free((void **)&NumMoleculesOfOrder, "molecule::FragmentBOSSANOVA: *NumMoleculesOfOrder");
-
-	*out << Verbose(0) << "End of FragmentBOSSANOVA." << endl;
+//              // every molecule is split into a list of again (Order - 1) molecules, while counting all molecules
+//              //*out << Verbose(1) << "Splitting the " << (*FragmentLowerOrdersList[RootNr][source]).size() << " molecules of the " << source << "th cell in the array." << endl;
+//              //NumMolecules = 0;
+//              FragmentLowerOrdersList[RootNr][dest] = new Graph;
+//              for(Graph::iterator runner = (*FragmentLowerOrdersList[RootNr][source]).begin();runner != (*FragmentLowerOrdersList[RootNr][source]).end(); runner++) {
+//                for (KeySet::iterator sprinter = (*runner).first.begin();sprinter != (*runner).first.end(); sprinter++) {
+//                  Graph TempFragmentList;
+//                  FragmentSearch.TEFactor = -(*runner).second.second;
+//                  FragmentSearch.Leaflet = &TempFragmentList;      // set to insertion graph
+//                  FragmentSearch.Root = FindAtom(*sprinter);
+//                  NumMoleculesOfOrder[RootNr] += PowerSetGenerator(out, SubOrder, FragmentSearch, (*runner).first);
+//                  // insert new keysets FragmentList into FragmentLowerOrdersList[Walker->AdaptiveOrder-1][dest]
+//                  *out << Verbose(1) << "Merging resulting key sets with those present in destination " << dest << "." << endl;
+//                  InsertGraphIntoGraph(out, *FragmentLowerOrdersList[RootNr][dest], TempFragmentList, &NumMolecules);
+//                }
+//              }
+//              *out << Verbose(1) << "Number of resulting molecules for SubOrder " << SubOrder << " is: " << NumMolecules << "." << endl;
+//            }
+//          }
+//        }
+      } else {
+        Walker->GetTrueFather()->MaxOrder = true;
+//        *out << Verbose(1) << "Hence, we don't dive into SubOrders ... " << endl;
+      }
+      // now, we have completely filled each cell of FragmentLowerOrdersList[] for the current Walker->AdaptiveOrder
+      //NumMoleculesOfOrder[Walker->AdaptiveOrder-1] = NumMolecules;
+      TotalNumMolecules += NumMoleculesOfOrder[RootNr];
+//      *out << Verbose(1) << "Number of resulting molecules for Order " << (int)Walker->GetTrueFather()->AdaptiveOrder << " is: " << NumMoleculesOfOrder[RootNr] << "." << endl;
+      RootStack.push_back(RootKeyNr); // put back on stack
+      RootNr++;
+
+      // free Order-dependent entries of UniqueFragments structure for next loop cycle
+      Free((void **)&FragmentSearch.BondsPerSPCount, "molecule::PowerSetGenerator: *BondsPerSPCount");
+      for (int i=Order;i--;) {
+        delete(FragmentSearch.BondsPerSPList[2*i]);
+        delete(FragmentSearch.BondsPerSPList[2*i+1]);
+      }
+      Free((void **)&FragmentSearch.BondsPerSPList, "molecule::PowerSetGenerator: ***BondsPerSPList");
+    }
+  }
+  *out << Verbose(0) << "==============================================================================================================" << endl;
+  *out << Verbose(1) << "Total number of resulting molecules is: " << TotalNumMolecules << "." << endl;
+  *out << Verbose(0) << "==============================================================================================================" << endl;
+
+  // cleanup FragmentSearch structure
+  Free((void **)&FragmentSearch.ShortestPathList, "molecule::PowerSetGenerator: *ShortestPathList");
+  delete(FragmentSearch.FragmentSet);
+
+  // 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 all into a single list (FragmentList)
+
+  *out << Verbose(0) << "Combining the lists of all orders per order and finally into a single one." << endl;
+  if (FragmentList == NULL) {
+    FragmentList = new Graph;
+    counter = 0;
+  } else {
+    counter = FragmentList->size();
+  }
+  RootNr = 0;
+  while (!RootStack.empty()) {
+    RootKeyNr = RootStack.front();
+    RootStack.pop_front();
+    Walker = FindAtom(RootKeyNr);
+    NumLevels = 1 << (Walker->AdaptiveOrder - 1);
+    for(int i=0;i<NumLevels;i++) {
+      if (FragmentLowerOrdersList[RootNr][i] != NULL) {
+        InsertGraphIntoGraph(out, *FragmentList, (*FragmentLowerOrdersList[RootNr][i]), &counter);
+        delete(FragmentLowerOrdersList[RootNr][i]);
+      }
+    }
+    Free((void **)&FragmentLowerOrdersList[RootNr], "molecule::FragmentBOSSANOVA: **FragmentLowerOrdersList[]");
+    RootNr++;
+  }
+  Free((void **)&FragmentLowerOrdersList, "molecule::FragmentBOSSANOVA: ***FragmentLowerOrdersList");
+  Free((void **)&NumMoleculesOfOrder, "molecule::FragmentBOSSANOVA: *NumMoleculesOfOrder");
+
+  *out << Verbose(0) << "End of FragmentBOSSANOVA." << endl;
 };
 
@@ -4432,10 +5291,10 @@
 inline 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;
+  if (*(double *)a > *(double *)b)
+    return -1;
+  else if (*(double *)a < *(double *)b)
+    return 1;
+  else
+    return 0;
 };
 
@@ -4448,118 +5307,118 @@
 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=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;
-		DetermineCenter(CenterOfGravity);
-		OtherMolecule->DetermineCenter(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.DistanceSquared(&OtherCenterOfGravity) > threshold*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;
-			Distances[Walker->nr] = CenterOfGravity.DistanceSquared(&Walker->x);
-		}
-		Walker = OtherMolecule->start;
-		while (Walker->next != OtherMolecule->end) {
-			Walker = Walker->next;
-			OtherDistances[Walker->nr] = OtherCenterOfGravity.DistanceSquared(&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=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 squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " <<	threshold << endl;
-			if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold*threshold)
-				flag = 1;
-		}
-		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;
-	}
+  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=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;
+    DeterminePeriodicCenter(CenterOfGravity);
+    OtherMolecule->DeterminePeriodicCenter(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.DistanceSquared(&OtherCenterOfGravity) > threshold*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;
+      Distances[Walker->nr] = CenterOfGravity.DistanceSquared(&Walker->x);
+    }
+    Walker = OtherMolecule->start;
+    while (Walker->next != OtherMolecule->end) {
+      Walker = Walker->next;
+      OtherDistances[Walker->nr] = OtherCenterOfGravity.DistanceSquared(&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=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 squared: |" << Distances[PermMap[i]] << " - " << OtherDistances[OtherPermMap[i]] << "| = " << fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) << " ?<? " <<  threshold << endl;
+      if (fabs(Distances[PermMap[i]] - OtherDistances[OtherPermMap[i]]) > threshold*threshold)
+        flag = 1;
+    }
+    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;
+  }
 };
 
@@ -4573,37 +5432,37 @@
 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=AtomCount;i--;)
-		AtomicMap[i] = -1;
-	if (OtherMolecule == this) {	// same molecule
-		for (int 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;
+  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=AtomCount;i--;)
+    AtomicMap[i] = -1;
+  if (OtherMolecule == this) {  // same molecule
+    for (int 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;
 };
 
@@ -4619,21 +5478,21 @@
 bool molecule::OutputTemperatureFromTrajectories(ofstream *out, int startstep, int endstep, ofstream *output)
 {
-	double temperature;
-	atom *Walker = NULL;
-	// test stream
-	if (output == NULL)
-		return false;
-	else
-		*output << "# Step Temperature [K] Temperature [a.u.]" << endl;
-	for (int step=startstep;step < endstep; step++) { // loop over all time steps
-		temperature = 0.;
-		Walker = start;
-		while (Walker->next != end) {
-			Walker = Walker->next;
-			for (int i=NDIM;i--;)
-				temperature += Walker->type->mass * Trajectories[Walker].U.at(step).x[i]* Trajectories[Walker].U.at(step).x[i];
-		}
-		*output << step << "\t" << temperature*AtomicEnergyToKelvin << "\t" << temperature << endl;
-	}
-	return true;
-};
+  double temperature;
+  atom *Walker = NULL;
+  // test stream
+  if (output == NULL)
+    return false;
+  else
+    *output << "# Step Temperature [K] Temperature [a.u.]" << endl;
+  for (int step=startstep;step < endstep; step++) { // loop over all time steps
+    temperature = 0.;
+    Walker = start;
+    while (Walker->next != end) {
+      Walker = Walker->next;
+      for (int i=NDIM;i--;)
+        temperature += Walker->type->mass * Trajectories[Walker].U.at(step).x[i]* Trajectories[Walker].U.at(step).x[i];
+    }
+    *output << step << "\t" << temperature*AtomicEnergyToKelvin << "\t" << temperature << endl;
+  }
+  return true;
+};
Index: src/molecules.hpp
===================================================================
--- src/molecules.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/molecules.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -10,9 +10,11 @@
 
 // GSL headers
+#include <gsl/gsl_eigen.h>
+#include <gsl/gsl_heapsort.h>
+#include <gsl/gsl_linalg.h>
+#include <gsl/gsl_matrix.h>
 #include <gsl/gsl_multimin.h>
 #include <gsl/gsl_vector.h>
-#include <gsl/gsl_matrix.h>
-#include <gsl/gsl_eigen.h>
-#include <gsl/gsl_heapsort.h>
+#include <gsl/gsl_randist.h>
 
 // STL headers
@@ -33,6 +35,8 @@
 class config;
 class molecule;
+class MoleculeLeafClass;
 class MoleculeListClass;
 class Verbose;
+class Tesselation;
 
 /******************************** Some definitions for easier reading **********************************/
@@ -79,18 +83,18 @@
 struct KeyCompare
 {
-	bool operator() (const KeySet SubgraphA, const KeySet SubgraphB) const;
+  bool operator() (const KeySet SubgraphA, const KeySet SubgraphB) const;
 };
 
 struct Trajectory
 {
-	vector<Vector> R;	//!< position vector
-	vector<Vector> U;	//!< velocity vector
-	vector<Vector> F;	//!< last force vector
-	atom *ptr;				 //!< pointer to atom whose trajectory we contain
-};
-
-//bool operator < (KeySet SubgraphA, KeySet SubgraphB);	 //note: this declaration is important, otherwise normal < is used (producing wrong order)
+  vector<Vector> R;  //!< position vector
+  vector<Vector> U;  //!< velocity vector
+  vector<Vector> F;  //!< last force vector
+  atom *ptr;         //!< pointer to atom whose trajectory we contain
+};
+
+//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
+inline void InsertGraphIntoGraph(ofstream *out, Graph &graph1, Graph &graph2, int *counter);  // Insert all KeySet's in a Graph into another Graph
 int CompareDoubles (const void * a, const void * b);
 
@@ -100,6 +104,6 @@
 
 // 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
+#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
 
 
@@ -107,6 +111,6 @@
  */
 struct LSQ_params {
-	Vector **vectors;
-	int num;
+  Vector **vectors;
+  int num;
 };
 
@@ -116,7 +120,7 @@
  */
 struct lsq_params {
-	gsl_vector *x;
-	const molecule *mol;
-	element *type;
+  gsl_vector *x;
+  const molecule *mol;
+  element *type;
 };
 
@@ -125,33 +129,34 @@
  */
 class atom {
-	public:
-		Vector x;			 //!< coordinate array of atom, giving position within cell
-		Vector v;			 //!< velocity array of atom
-		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 FixedIon;	 //!< config variable that states whether forces act on the ion or not
-		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, determined in DepthFirstSearchAnalysis()
-		bool IsCyclic;				//!< whether atom belong to as cycle or not, determined in DepthFirstSearchAnalysis()
-		unsigned char AdaptiveOrder;	//!< current present bond order at site (0 means "not set")
-		bool MaxOrder;	//!< whether this atom as a root in fragmentation still creates more fragments on higher orders or not
-
-	atom();
-	~atom();
-
-	bool Output(int ElementNo, int AtomNo, ofstream *out, const char *comment = NULL) const;
-	bool OutputXYZLine(ofstream *out) const;
-	atom *GetTrueFather();
-	bool Compare(const atom &ptr);
-
-	private:
+  public:
+    Vector x;       //!< coordinate array of atom, giving position within cell
+    Vector v;       //!< velocity array of atom
+    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 FixedIon;   //!< config variable that states whether forces act on the ion or not
+    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, determined in DepthFirstSearchAnalysis()
+    bool IsCyclic;        //!< whether atom belong to as cycle or not, determined in DepthFirstSearchAnalysis()
+    unsigned char AdaptiveOrder;  //!< current present bond order at site (0 means "not set")
+    bool MaxOrder;  //!< whether this atom as a root in fragmentation still creates more fragments on higher orders or not
+
+  atom();
+  atom(class atom *pointer);
+  ~atom();
+
+  bool Output(int ElementNo, int AtomNo, ofstream *out, const char *comment = NULL) const;
+  bool OutputXYZLine(ofstream *out) const;
+  atom *GetTrueFather();
+  bool Compare(const atom &ptr);
+
+  private:
 };
 
@@ -164,38 +169,41 @@
  */
 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;
+  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, const bond &b);
+
+#define MaxThermostats 6      //!< maximum number of thermostat entries in Ions#ThermostatNames and Ions#ThermostatImplemented 
+enum thermostats { None, Woodcock, Gaussian, Langevin, Berendsen, NoseHoover };   //!< Thermostat names for output
+
 
 /** The complete molecule.
@@ -203,135 +211,143 @@
  */
 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
-		map<atom *, struct Trajectory> Trajectories; //!< contains old trajectory points
-		int MDSteps;				//!< The number of MD steps in Trajectories
-		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
-		bool ActiveFlag;    //!< in a MoleculeListClass used to discern active from inactive molecules
-		Vector Center;      //!< Center of molecule in a global box
-		char name[MAXSTRINGSIZE];         //!< arbitrary name
-		int IndexNr;        //!< index of molecule in a MoleculeListClass
-
-	molecule(periodentafel *teil);
-	~molecule();
-
-	/// remove atoms from molecule.
-	bool AddAtom(atom *pointer);
-	bool RemoveAtom(atom *pointer);
-	bool UnlinkAtom(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(string text);
-
-	/// Count and change present atoms' coordination.
-	void CountAtoms(ofstream *out);
-	void CountElements();
-	void CalculateOrbitals(class config &configuration);
-	bool CenterInBox(ofstream *out, Vector *BoxLengths);
-	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 DetermineCenter(Vector &center);
-	Vector * DetermineCenterOfGravity(ofstream *out);
-	Vector * DetermineCenterOfAll(ofstream *out);
-	void SetNameFromFilename(char *filename);
-	void SetBoxDimension(Vector *dim);
-	double * ReturnFullMatrixforSymmetric(double *cell_size);
-	void ScanForPeriodicCorrection(ofstream *out);
-	void PrincipalAxisSystem(ofstream *out, bool DoRotate);
-	double VolumeOfConvexEnvelope(ofstream *out, bool IsAngstroem);
-	Vector* FindEmbeddingHole(ofstream *out, molecule *srcmol);
-
-	bool VerletForceIntegration(char *file, double delta_t, bool IsAngstroem);
-
-	bool CheckBounds(const Vector *x) const;
-	void GetAlignvector(struct lsq_params * par) const;
-
-	/// Initialising routines in fragmentation
-	void CreateAdjacencyList2(ofstream *out, ifstream *output);
-	void CreateAdjacencyList(ofstream *out, double bonddistance, bool IsAngstroem);
-	void CreateListOfBondsPerAtom(ofstream *out);
-
-	// Graph analysis
-	MoleculeLeafClass * DepthFirstSearchAnalysis(ofstream *out, class StackClass<bond *> *&BackEdgeStack);
-	void CyclicStructureAnalysis(ofstream *out, class StackClass<bond *> *BackEdgeStack, int *&MinimumRingSize);
-	bool PickLocalBackEdges(ofstream *out, atom **ListOfLocalAtoms, class StackClass<bond *> *&ReferenceStack, class StackClass<bond *> *&LocalStack);
-	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);
-	bool CheckForConnectedSubgraph(ofstream *out, KeySet *Fragment);
-	string GetColor(enum Shading color);
-
-	molecule *CopyMolecule();
-
-	/// Fragment molecule by two different approaches:
-	int FragmentMolecule(ofstream *out, int Order, config *configuration);
-	bool CheckOrderAtSite(ofstream *out, bool *AtomMask, Graph *GlobalKeySetList, int Order, int *MinimumRingSize, char *path = NULL);
-	bool StoreAdjacencyToFile(ofstream *out, char *path);
-	bool CheckAdjacencyFileAgainstMolecule(ofstream *out, char *path, atom **ListOfAtoms);
-	bool ParseOrderAtSiteFromFile(ofstream *out, char *path);
-	bool StoreOrderAtSiteFile(ofstream *out, char *path);
-	bool ParseKeySetFile(ofstream *out, char *filename, Graph *&FragmentList);
-	bool StoreKeySetFile(ofstream *out, Graph &KeySetList, char *path);
-	bool StoreForcesFile(ofstream *out, MoleculeListClass *BondFragments, char *path, int *SortIndex);
-	bool CreateMappingLabelsToConfigSequence(ofstream *out, int *&SortIndex);
-	bool ScanBufferIntoKeySet(ofstream *out, char *buffer, KeySet &CurrentSet);
-	void BreadthFirstSearchAdd(ofstream *out, molecule *Mol, atom **&AddedAtomList, bond **&AddedBondList, atom *Root, bond *Bond, int BondOrder, bool IsAngstroem);
-	/// -# BOSSANOVA
-	void FragmentBOSSANOVA(ofstream *out, Graph *&FragmentList, KeyStack &RootStack, int *MinimumRingSize);
-	int PowerSetGenerator(ofstream *out, int Order, struct UniqueFragments &FragmentSearch, KeySet RestrictedKeySet);
-	bool BuildInducedSubgraph(ofstream *out, const molecule *Father);
-	molecule * StoreFragmentFromKeySet(ofstream *out, KeySet &Leaflet, bool IsAngstroem);
-	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 OutputTrajectories(ofstream *out);
-	void OutputListOfBonds(ofstream *out) const;
-	bool OutputXYZ(ofstream *out) const;
-	bool OutputTrajectoriesXYZ(ofstream *out);
-	bool Checkout(ofstream *out) const;
-	bool OutputTemperatureFromTrajectories(ofstream *out, int startstep, int endstep, ofstream *output);
-
-	private:
-	int last_atom;			//!< number given to last atom
+  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
+    map<atom *, struct Trajectory> Trajectories; //!< contains old trajectory points
+    int MDSteps;        //!< The number of MD steps in Trajectories
+    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
+    bool ActiveFlag;    //!< in a MoleculeListClass used to discern active from inactive molecules
+    Vector Center;      //!< Center of molecule in a global box
+    char name[MAXSTRINGSIZE];         //!< arbitrary name
+    int IndexNr;        //!< index of molecule in a MoleculeListClass
+
+  molecule(periodentafel *teil);
+  ~molecule();
+
+  /// remove atoms from molecule.
+  bool AddAtom(atom *pointer);
+  bool RemoveAtom(atom *pointer);
+  bool UnlinkAtom(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(string text);
+
+  /// Count and change present atoms' coordination.
+  void CountAtoms(ofstream *out);
+  void CountElements();
+  void CalculateOrbitals(class config &configuration);
+  bool CenterInBox(ofstream *out);
+  void CenterEdge(ofstream *out, Vector *max);
+  void CenterOrigin(ofstream *out);
+  void CenterPeriodic(ofstream *out);
+  void CenterAtVector(ofstream *out, Vector *newcenter);
+  void Translate(const Vector *x);
+  void TranslatePeriodically(const Vector *trans);
+  void Mirror(const Vector *x);
+  void Align(Vector *n);
+  void Scale(double **factor);
+  void DeterminePeriodicCenter(Vector &center);
+  Vector * DetermineCenterOfGravity(ofstream *out);
+  Vector * DetermineCenterOfAll(ofstream *out);
+  void SetNameFromFilename(const char *filename);
+  void SetBoxDimension(Vector *dim);
+  double * ReturnFullMatrixforSymmetric(double *cell_size);
+  void ScanForPeriodicCorrection(ofstream *out);
+  bool VerletForceIntegration(ofstream *out, char *file, config &configuration);
+  void Thermostats(config &configuration, double ActualTemp, int Thermostat);
+  void PrincipalAxisSystem(ofstream *out, bool DoRotate);
+  double VolumeOfConvexEnvelope(ofstream *out, bool IsAngstroem);
+  Vector* FindEmbeddingHole(ofstream *out, molecule *srcmol);
+
+
+  double ConstrainedPotential(ofstream *out, atom **permutation, int start, int end, double *constants, bool IsAngstroem);
+  double MinimiseConstrainedPotential(ofstream *out, atom **&permutation, int startstep, int endstep, bool IsAngstroem);
+  void EvaluateConstrainedForces(ofstream *out, int startstep, int endstep, atom **PermutationMap, ForceMatrix *Force);
+  bool LinearInterpolationBetweenConfiguration(ofstream *out, int startstep, int endstep, const char *prefix, config &configuration); 
+	
+  bool CheckBounds(const Vector *x) const;
+  void GetAlignvector(struct lsq_params * par) const;
+
+  /// Initialising routines in fragmentation
+  void CreateAdjacencyList2(ofstream *out, ifstream *output);
+  void CreateAdjacencyList(ofstream *out, double bonddistance, bool IsAngstroem);
+  void CreateListOfBondsPerAtom(ofstream *out);
+
+  // Graph analysis
+  MoleculeLeafClass * DepthFirstSearchAnalysis(ofstream *out, class StackClass<bond *> *&BackEdgeStack);
+  void CyclicStructureAnalysis(ofstream *out, class StackClass<bond *> *BackEdgeStack, int *&MinimumRingSize);
+  bool PickLocalBackEdges(ofstream *out, atom **ListOfLocalAtoms, class StackClass<bond *> *&ReferenceStack, class StackClass<bond *> *&LocalStack);
+  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);
+  bool CheckForConnectedSubgraph(ofstream *out, KeySet *Fragment);
+  string GetColor(enum Shading color);
+
+  molecule *CopyMolecule();
+
+  /// Fragment molecule by two different approaches:
+  int FragmentMolecule(ofstream *out, int Order, config *configuration);
+  bool CheckOrderAtSite(ofstream *out, bool *AtomMask, Graph *GlobalKeySetList, int Order, int *MinimumRingSize, char *path = NULL);
+  bool StoreAdjacencyToFile(ofstream *out, char *path);
+  bool CheckAdjacencyFileAgainstMolecule(ofstream *out, char *path, atom **ListOfAtoms);
+  bool ParseOrderAtSiteFromFile(ofstream *out, char *path);
+  bool StoreOrderAtSiteFile(ofstream *out, char *path);
+  bool ParseKeySetFile(ofstream *out, char *filename, Graph *&FragmentList);
+  bool StoreKeySetFile(ofstream *out, Graph &KeySetList, char *path);
+  bool StoreForcesFile(ofstream *out, MoleculeListClass *BondFragments, char *path, int *SortIndex);
+  bool CreateMappingLabelsToConfigSequence(ofstream *out, int *&SortIndex);
+  bool ScanBufferIntoKeySet(ofstream *out, char *buffer, KeySet &CurrentSet);
+  void BreadthFirstSearchAdd(ofstream *out, molecule *Mol, atom **&AddedAtomList, bond **&AddedBondList, atom *Root, bond *Bond, int BondOrder, bool IsAngstroem);
+  /// -# BOSSANOVA
+  void FragmentBOSSANOVA(ofstream *out, Graph *&FragmentList, KeyStack &RootStack, int *MinimumRingSize);
+  int PowerSetGenerator(ofstream *out, int Order, struct UniqueFragments &FragmentSearch, KeySet RestrictedKeySet);
+  bool BuildInducedSubgraph(ofstream *out, const molecule *Father);
+  molecule * StoreFragmentFromKeySet(ofstream *out, KeySet &Leaflet, bool IsAngstroem);
+  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 OutputTrajectories(ofstream *out);
+  void OutputListOfBonds(ofstream *out) const;
+  bool OutputXYZ(ofstream *out) const;
+  bool OutputTrajectoriesXYZ(ofstream *out);
+  bool Checkout(ofstream *out) const;
+  bool OutputTemperatureFromTrajectories(ofstream *out, int startstep, int endstep, ofstream *output);
+
+  private:
+  int last_atom;      //!< number given to last atom
 };
 
@@ -339,21 +355,21 @@
  */
 class MoleculeListClass {
-	public:
-	  MoleculeList ListOfMolecules; //!< List of the contained molecules
-	  int MaxIndex;
-
-	MoleculeListClass();
-	~MoleculeListClass();
-
-	bool AddHydrogenCorrection(ofstream *out, char *path);
-	bool StoreForcesFile(ofstream *out, char *path, int *SortIndex);
-	bool insert(molecule *mol);
-	molecule * ReturnIndex(int index);
-	bool OutputConfigForListOfFragments(ofstream *out, config *configuration, int *SortIndex);
-	int NumberOfActiveMolecules();
-	void Enumerate(ofstream *out);
-	void Output(ofstream *out);
-
-	// merging of molecules
+  public:
+    MoleculeList ListOfMolecules; //!< List of the contained molecules
+    int MaxIndex;
+
+  MoleculeListClass();
+  ~MoleculeListClass();
+
+  bool AddHydrogenCorrection(ofstream *out, char *path);
+  bool StoreForcesFile(ofstream *out, char *path, int *SortIndex);
+  void insert(molecule *mol);
+  molecule * ReturnIndex(int index);
+  bool OutputConfigForListOfFragments(ofstream *out, config *configuration, int *SortIndex);
+  int NumberOfActiveMolecules();
+  void Enumerate(ofstream *out);
+  void Output(ofstream *out);
+
+  // merging of molecules
   bool SimpleMerge(molecule *mol, molecule *srcmol);
   bool SimpleAdd(molecule *mol, molecule *srcmol);
@@ -363,5 +379,5 @@
   bool EmbedMerge(molecule *mol, molecule *srcmol);
 
-	private:
+  private:
 };
 
@@ -371,23 +387,39 @@
  */
 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);
-	bool FillBondStructureFromReference(ofstream *out, molecule *reference, int &FragmentCounter, atom ***&ListOfLocalAtoms, bool FreeList = false);
-	bool FillRootStackForSubgraphs(ofstream *out, KeyStack *&RootStack, bool *AtomMask, int &FragmentCounter);
-	bool AssignKeySetsToFragment(ofstream *out, molecule *reference, Graph *KeySetList, atom ***&ListOfLocalAtoms, Graph **&FragmentList, int &FragmentCounter, bool FreeList = false);
-	bool FillListOfLocalAtoms(ofstream *out, atom ***&ListOfLocalAtoms, const int FragmentCounter, const int GlobalAtomCount, bool &FreeList);
-	void TranslateIndicesToGlobalIDs(ofstream *out, Graph **FragmentList, int &FragmentCounter, int &TotalNumberOfKeySets, Graph &TotalGraph);
-	int Count() const;
-};
+  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);
+  bool FillBondStructureFromReference(ofstream *out, molecule *reference, int &FragmentCounter, atom ***&ListOfLocalAtoms, bool FreeList = false);
+  bool FillRootStackForSubgraphs(ofstream *out, KeyStack *&RootStack, bool *AtomMask, int &FragmentCounter);
+  bool AssignKeySetsToFragment(ofstream *out, molecule *reference, Graph *KeySetList, atom ***&ListOfLocalAtoms, Graph **&FragmentList, int &FragmentCounter, bool FreeList = false);
+  bool FillListOfLocalAtoms(ofstream *out, atom ***&ListOfLocalAtoms, const int FragmentCounter, const int GlobalAtomCount, bool &FreeList);
+  void TranslateIndicesToGlobalIDs(ofstream *out, Graph **FragmentList, int &FragmentCounter, int &TotalNumberOfKeySets, Graph &TotalGraph);
+  int Count() const;
+};
+
+class ConfigFileBuffer {
+  public:
+    char **buffer;
+    int *LineMapping;
+    int CurrentLine;
+    int NoLines;
+
+    ConfigFileBuffer();
+    ConfigFileBuffer(char *filename);
+    ~ConfigFileBuffer();
+
+    void InitMapping();
+    void MapIonTypesInBuffer(int NoAtoms);
+};
+
 
 /** The config file.
@@ -395,92 +427,102 @@
  */
 class config {
-	public:
-		int PsiType;
-		int MaxPsiDouble;
-		int PsiMaxNoUp;
-		int PsiMaxNoDown;
-		int MaxMinStopStep;
-		int InitMaxMinStopStep;
-		int ProcPEGamma;
-		int ProcPEPsi;
-		char *configpath;
-		char *configname;
-		bool FastParsing;
-		double Deltat;
-		string basis;
+  public:
+    int PsiType;
+    int MaxPsiDouble;
+    int PsiMaxNoUp;
+    int PsiMaxNoDown;
+    int MaxMinStopStep;
+    int InitMaxMinStopStep;
+    int ProcPEGamma;
+    int ProcPEPsi;
+    char *configpath;
+    char *configname;
+    bool FastParsing;
+    double Deltat;
+    string basis;
 
     char *databasepath;
 
-	private:
-		char *mainname;
-		char *defaultpath;
-		char *pseudopotpath;
-
-		int DoOutVis;
-		int DoOutMes;
-		int DoOutNICS;
-		int DoOutOrbitals;
-		int DoOutCurrent;
-		int DoFullCurrent;
-		int DoPerturbation;
-		int DoWannier;
-		int CommonWannier;
-		double SawtoothStart;
-		int VectorPlane;
-		double VectorCut;
-		int UseAddGramSch;
-		int Seed;
-
-		int MaxOuterStep;
-		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(char *filename, periodentafel *periode, molecule *mol);
-	void Load(char *filename, periodentafel *periode, molecule *mol);
-	void LoadOld(char *filename, periodentafel *periode, molecule *mol);
-	void RetrieveConfigPathAndName(string filename);
-	bool Save(const char *filename, periodentafel *periode, molecule *mol) const;
-	bool SaveMPQC(const char *filename, molecule *mol) const;
-	void Edit();
-	bool GetIsAngstroem() const;
-	char *GetDefaultPath() const;
-	void SetDefaultPath(const char *path);
+    int DoConstrainedMD;
+    int MaxOuterStep;
+    int Thermostat;
+    int *ThermostatImplemented;
+    char **ThermostatNames;
+    double TempFrequency;
+    double alpha;
+    double HooverMass;
+    double TargetTemp;
+    int ScaleTempStep;
+    
+  private:
+    char *mainname;
+    char *defaultpath;
+    char *pseudopotpath;
+
+    int DoOutVis;
+    int DoOutMes;
+    int DoOutNICS;
+    int DoOutOrbitals;
+    int DoOutCurrent;
+    int DoFullCurrent;
+    int DoPerturbation;
+    int DoWannier;
+    int CommonWannier;
+    double SawtoothStart;
+    int VectorPlane;
+    double VectorCut;
+    int UseAddGramSch;
+    int Seed;
+
+    int OutVisStep;
+    int OutSrcStep;
+    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);
+  int ParseForParameter(int verbose, struct ConfigFileBuffer *FileBuffer, const char *name, int sequential, int const xth, int const yth, int type, void *value, int repetition, int critical);
+
+  public:
+  config();
+  ~config();
+
+  int TestSyntax(char *filename, periodentafel *periode, molecule *mol);
+  void Load(char *filename, periodentafel *periode, molecule *mol);
+  void LoadOld(char *filename, periodentafel *periode, molecule *mol);
+  void RetrieveConfigPathAndName(string filename);
+  bool Save(const char *filename, periodentafel *periode, molecule *mol) const;
+  bool SaveMPQC(const char *filename, molecule *mol) const;
+  void Edit();
+  bool GetIsAngstroem() const;
+  char *GetDefaultPath() const;
+  void SetDefaultPath(const char *path);
+  void InitThermostats(ifstream *source);
 };
 
Index: src/parser.cpp
===================================================================
--- src/parser.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/parser.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -24,14 +24,14 @@
 bool FilePresent(const char *filename, bool test)
 {
-	ifstream input;
-
-	input.open(filename, ios::in);
-	if (input == NULL) {
-		if (!test)
-			cout << endl << "Unable to open " << filename << ", is the directory correct?" << endl;
-		return false;
-	}
-	input.close();
-	return true;
+  ifstream input;
+
+  input.open(filename, ios::in);
+  if (input == NULL) {
+    if (!test)
+      cout << endl << "Unable to open " << filename << ", is the directory correct?" << endl;
+    return false;
+  }
+  input.close();
+  return true;
 };
 
@@ -43,9 +43,9 @@
 bool TestParams(int argc, char **argv)
 {
-	ifstream input;
-	stringstream line;
-
-	line << argv[1] << FRAGMENTPREFIX << KEYSETFILE;
-	return FilePresent(line.str().c_str(), false);
+  ifstream input;
+  stringstream line;
+
+  line << argv[1] << FRAGMENTPREFIX << KEYSETFILE;
+  return FilePresent(line.str().c_str(), false);
 };
 
@@ -55,12 +55,14 @@
  */
 MatrixContainer::MatrixContainer() {
-	Indices = NULL;
-	Header = (char *) Malloc(sizeof(char)*1023, "MatrixContainer::MatrixContainer: *Header");
-	Matrix = (double ***) Malloc(sizeof(double **)*(1), "MatrixContainer::MatrixContainer: ***Matrix"); // one more each for the total molecule
-	RowCounter = (int *) Malloc(sizeof(int)*(1), "MatrixContainer::MatrixContainer: *RowCounter");
-	Matrix[0] = NULL;
-	RowCounter[0] = -1;
-	MatrixCounter = 0;
-	ColumnCounter = 0;
+  Indices = NULL;
+  Header = (char **) Malloc(sizeof(char)*1, "MatrixContainer::MatrixContainer: **Header");
+  Matrix = (double ***) Malloc(sizeof(double **)*(1), "MatrixContainer::MatrixContainer: ***Matrix"); // one more each for the total molecule
+  RowCounter = (int *) Malloc(sizeof(int)*(1), "MatrixContainer::MatrixContainer: *RowCounter");
+  ColumnCounter = (int *) Malloc(sizeof(int)*(1), "MatrixContainer::MatrixContainer: *ColumnCounter");
+  Header[0] = NULL;
+  Matrix[0] = NULL;
+  RowCounter[0] = -1;
+  MatrixCounter = 0;
+  ColumnCounter[0] = -1;
 };
 
@@ -68,37 +70,75 @@
  */
 MatrixContainer::~MatrixContainer() {
-	if (Matrix != NULL) {
-		for(int i=MatrixCounter;i--;) {
-			if (RowCounter != NULL) {
-					for(int j=RowCounter[i]+1;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=RowCounter[MatrixCounter]+1;j--;)
-				Free((void **)&Matrix[MatrixCounter][j], "MatrixContainer::~MatrixContainer: *Matrix[MatrixCounter][]");
-		if (MatrixCounter != 0)
-			Free((void **)&Matrix[MatrixCounter], "MatrixContainer::~MatrixContainer: **Matrix[MatrixCounter]");
-		Free((void **)&Matrix, "MatrixContainer::~MatrixContainer: ***Matrix");
-	}
-	if (Indices != NULL)
-		for(int i=MatrixCounter+1;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");
-};
-
+  if (Matrix != NULL) {
+    for(int i=MatrixCounter;i--;) {
+      if ((ColumnCounter != NULL) && (RowCounter != NULL)) {
+          for(int j=RowCounter[i]+1;j--;)
+            Free((void **)&Matrix[i][j], "MatrixContainer::~MatrixContainer: *Matrix[][]");
+        Free((void **)&Matrix[i], "MatrixContainer::~MatrixContainer: **Matrix[]");
+      }
+    }
+    if ((ColumnCounter != NULL) && (RowCounter != NULL) && (Matrix[MatrixCounter] != NULL))
+      for(int j=RowCounter[MatrixCounter]+1;j--;)
+        Free((void **)&Matrix[MatrixCounter][j], "MatrixContainer::~MatrixContainer: *Matrix[MatrixCounter][]");
+    if (MatrixCounter != 0)
+      Free((void **)&Matrix[MatrixCounter], "MatrixContainer::~MatrixContainer: **Matrix[MatrixCounter]");
+    Free((void **)&Matrix, "MatrixContainer::~MatrixContainer: ***Matrix");
+  }
+  if (Indices != NULL)
+    for(int i=MatrixCounter+1;i--;) {
+      Free((void **)&Indices[i], "MatrixContainer::~MatrixContainer: *Indices[]");
+    }
+  Free((void **)&Indices, "MatrixContainer::~MatrixContainer: **Indices"); 
+  
+  if (Header != NULL)
+    for(int i=MatrixCounter+1;i--;)
+      Free((void **)&Header[i], "MatrixContainer::~MatrixContainer: *Header[]");
+  Free((void **)&Header, "MatrixContainer::~MatrixContainer: **Header");
+  Free((void **)&RowCounter, "MatrixContainer::~MatrixContainer: *RowCounter");
+  Free((void **)&ColumnCounter, "MatrixContainer::~MatrixContainer: *RowCounter");
+};
+
+/** Either copies index matrix from another MatrixContainer or initialises with trivial mapping if NULL.
+ * This either copies the index matrix or just maps 1 to 1, 2 to 2 and so on for all fragments.
+ * \param *Matrix pointer to other MatrixContainer
+ * \return true - copy/initialisation sucessful, false - dimension false for copying
+ */
+bool MatrixContainer::InitialiseIndices(class MatrixContainer *Matrix) 
+{
+  cout << "Initialising indices";
+  if (Matrix == NULL) {
+    cout << " with trivial mapping." << endl;
+    Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "MatrixContainer::InitialiseIndices: **Indices");
+    for(int i=MatrixCounter+1;i--;) {
+      Indices[i] = (int *) Malloc(sizeof(int)*RowCounter[i], "MatrixContainer::InitialiseIndices: *Indices[]");
+      for(int j=RowCounter[i];j--;)
+        Indices[i][j] = j;
+    }
+  } else {
+    cout << " from other MatrixContainer." << endl;
+    if (MatrixCounter != Matrix->MatrixCounter)
+      return false;
+    Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "MatrixContainer::InitialiseIndices: **Indices");
+    for(int i=MatrixCounter+1;i--;) {
+      if (RowCounter[i] != Matrix->RowCounter[i])
+        return false;
+      Indices[i] = (int *) Malloc(sizeof(int)*Matrix->RowCounter[i], "MatrixContainer::InitialiseIndices: *Indices[]");
+      for(int j=Matrix->RowCounter[i];j--;) {
+        Indices[i][j] = Matrix->Indices[i][j];
+        //cout << Indices[i][j] << "\t";
+      }
+      //cout << endl;
+    }
+  }
+  return true; 
+};
 
 /** Parsing a number of matrices.
- *		-# open the matrix file
- *		-# skip some lines (\a skiplines)
- *		-# scan header lines for number of columns
- *		-# scan lines for number of rows
- *		-# allocate matrix
- *		-# loop over found column and row counts and parse in each entry
+ *    -# open the matrix file
+ *    -# skip some lines (\a skiplines)
+ *    -# scan header lines for number of columns
+ *    -# scan lines for number of rows
+ *    -# allocate matrix
+ *    -# loop over found column and row counts and parse in each entry
  * \param *name directory with files
  * \param skiplines number of inital lines to skip
@@ -109,83 +149,84 @@
 bool MatrixContainer::ParseMatrix(const char *name, int skiplines, int skipcolumns, int MatrixNr)
 {
-	ifstream input;
-	stringstream line;
-	string token;
-	char filename[1023];
-
-	input.open(name, ios::in);
-	//cout << "Opening " << name << " ... "	<< input << endl;
-	if (input == NULL) {
-		cerr << endl << "Unable to open " << name << ", is the directory correct?" << endl;
-		return false;
-	}
-
-	// skip some initial lines
-	for (int m=skiplines+1;m--;)
-		input.getline(Header, 1023);
-
-	// scan header for number of columns
-	line.str(Header);
-	for(int k=skipcolumns;k--;)
-		line >> Header;
-	//cout << line.str() << endl;
-	ColumnCounter=0;
-	while ( getline(line,token, '\t') ) {
-		if (token.length() > 0)
-			ColumnCounter++;
-	}
-	//cout << line.str() << endl;
-	//cout << "ColumnCounter: " << ColumnCounter << "." << endl;
-	if (ColumnCounter == 0)
-		cerr << "ColumnCounter: " << ColumnCounter << " from file " << name << ", this is probably an error!" << endl;
-
-	// scan rest for number of rows/lines
-	RowCounter[MatrixNr]=-1;		// counts one line too much
-	while (!input.eof()) {
-		input.getline(filename, 1023);
-		//cout << "Comparing: " << strncmp(filename,"MeanForce",9) << endl;
-		RowCounter[MatrixNr]++; // then line was not last MeanForce
-		if (strncmp(filename,"MeanForce", 9) == 0) {
-			break;
-		}
-	}
-	//cout << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << "." << endl;
-	if (RowCounter[MatrixNr] == 0)
-		cerr << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl;
-
-	// allocate matrix if it's not zero dimension in one direction
-	if ((ColumnCounter > 0) && (RowCounter[MatrixNr] > -1)) {
-		Matrix[MatrixNr] = (double **) Malloc(sizeof(double *)*(RowCounter[MatrixNr]+1), "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
-
-		// parse in each entry for this matrix
-		input.clear();
-		input.seekg(ios::beg);
-		for (int m=skiplines+1;m--;)
-			input.getline(Header, 1023);		// skip header
-		line.str(Header);
-		for(int k=skipcolumns;k--;)	// skip columns in header too
-			line >> filename;
-		strncpy(Header, line.str().c_str(), 1023);
-		for(int j=0;j<RowCounter[MatrixNr];j++) {
-			Matrix[MatrixNr][j] = (double *) Malloc(sizeof(double)*ColumnCounter, "MatrixContainer::ParseFragmentMatrix: *Matrix[][]");
-			input.getline(filename, 1023);
-			stringstream lines(filename);
-			//cout << "Matrix at level " << j << ":";// << filename << endl;
-			for(int k=skipcolumns;k--;)
-				lines >> filename;
-			for(int k=0;(k<ColumnCounter) && (!lines.eof());k++) {
-				lines >> Matrix[MatrixNr][j][k];
-				//cout << " " << setprecision(2) << Matrix[MatrixNr][j][k];;
-			}
-			//cout << endl;
-			Matrix[MatrixNr][ RowCounter[MatrixNr] ] = (double *) Malloc(sizeof(double)*ColumnCounter, "MatrixContainer::ParseFragmentMatrix: *Matrix[RowCounter[MatrixNr]][]");
-			for(int j=ColumnCounter;j--;)
-				Matrix[MatrixNr][ RowCounter[MatrixNr] ][j] = 0.;
-		}
-	} else {
-		cerr << "ERROR: Matrix nr. " << MatrixNr << " has column and row count of (" << ColumnCounter << "," << RowCounter[MatrixNr] << "), could not allocate nor parse!" << endl;
-	}
-	input.close();
-	return true;
+  ifstream input;
+  stringstream line;
+  string token;
+  char filename[1023];
+
+  input.open(name, ios::in);
+  //cout << "Opening " << name << " ... "  << input << endl;
+  if (input == NULL) {
+    cerr << endl << "Unable to open " << name << ", is the directory correct?" << endl;
+    return false;
+  }
+
+  // parse header
+  Header[MatrixNr] = (char *) Malloc(sizeof(char)*1024, "MatrixContainer::ParseMatrix: *Header[]");
+  for (int m=skiplines+1;m--;)
+    input.getline(Header[MatrixNr], 1023);
+  
+  // scan header for number of columns
+  line.str(Header[MatrixNr]);
+  for(int k=skipcolumns;k--;)
+    line >> Header[MatrixNr];
+  //cout << line.str() << endl;
+  ColumnCounter[MatrixNr]=0;
+  while ( getline(line,token, '\t') ) {
+    if (token.length() > 0)
+      ColumnCounter[MatrixNr]++;
+  }
+  //cout << line.str() << endl;
+  //cout << "ColumnCounter[" << MatrixNr << "]: " << ColumnCounter[MatrixNr] << "." << endl;
+  if (ColumnCounter[MatrixNr] == 0)
+    cerr << "ColumnCounter[" << MatrixNr << "]: " << ColumnCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl;
+  
+  // scan rest for number of rows/lines
+  RowCounter[MatrixNr]=-1;    // counts one line too much
+  while (!input.eof()) {
+    input.getline(filename, 1023);
+    //cout << "Comparing: " << strncmp(filename,"MeanForce",9) << endl;
+    RowCounter[MatrixNr]++; // then line was not last MeanForce
+    if (strncmp(filename,"MeanForce", 9) == 0) {
+      break;
+    }
+  }
+  //cout << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << "." << endl;
+  if (RowCounter[MatrixNr] == 0)
+    cerr << "RowCounter[" << MatrixNr << "]: " << RowCounter[MatrixNr] << " from file " << name << ", this is probably an error!" << endl;
+
+  // allocate matrix if it's not zero dimension in one direction
+  if ((ColumnCounter[MatrixNr] > 0) && (RowCounter[MatrixNr] > -1)) {
+    Matrix[MatrixNr] = (double **) Malloc(sizeof(double *)*(RowCounter[MatrixNr]+1), "MatrixContainer::ParseMatrix: **Matrix[]");
+  
+    // parse in each entry for this matrix
+    input.clear();
+    input.seekg(ios::beg);
+    for (int m=skiplines+1;m--;)
+      input.getline(Header[MatrixNr], 1023);    // skip header
+    line.str(Header[MatrixNr]);
+    for(int k=skipcolumns;k--;)  // skip columns in header too
+      line >> filename;
+    strncpy(Header[MatrixNr], line.str().c_str(), 1023);  
+    for(int j=0;j<RowCounter[MatrixNr];j++) {
+      Matrix[MatrixNr][j] = (double *) Malloc(sizeof(double)*ColumnCounter[MatrixNr], "MatrixContainer::ParseMatrix: *Matrix[][]");
+      input.getline(filename, 1023);
+      stringstream lines(filename);
+      //cout << "Matrix at level " << j << ":";// << filename << endl;
+      for(int k=skipcolumns;k--;)
+        lines >> filename;
+      for(int k=0;(k<ColumnCounter[MatrixNr]) && (!lines.eof());k++) {
+        lines >> Matrix[MatrixNr][j][k];
+        //cout << " " << setprecision(2) << Matrix[MatrixNr][j][k];;
+      }
+      //cout << endl;
+      Matrix[MatrixNr][ RowCounter[MatrixNr] ] = (double *) Malloc(sizeof(double)*ColumnCounter[MatrixNr], "MatrixContainer::ParseMatrix: *Matrix[RowCounter[MatrixNr]][]");
+      for(int j=ColumnCounter[MatrixNr];j--;)
+        Matrix[MatrixNr][ RowCounter[MatrixNr] ][j] = 0.;
+    }
+  } else {
+    cerr << "ERROR: Matrix nr. " << MatrixNr << " has column and row count of (" << ColumnCounter[MatrixNr] << "," << RowCounter[MatrixNr] << "), could not allocate nor parse!" << endl; 
+  }
+  input.close();
+  return true;
 };
 
@@ -193,11 +234,11 @@
  * -# First, count the number of matrices by counting lines in KEYSETFILE
  * -# Then,
- *		-# construct the fragment number
- *		-# open the matrix file
- *		-# skip some lines (\a skiplines)
- *		-# scan header lines for number of columns
- *		-# scan lines for number of rows
- *		-# allocate matrix
- *		-# loop over found column and row counts and parse in each entry
+ *    -# construct the fragment number
+ *    -# open the matrix file
+ *    -# skip some lines (\a skiplines)
+ *    -# scan header lines for number of columns
+ *    -# scan lines for number of rows
+ *    -# allocate matrix
+ *    -# loop over found column and row counts and parse in each entry
  * -# Finally, allocate one additional matrix (\a MatrixCounter) containing combined or temporary values
  * \param *name directory with files
@@ -210,71 +251,76 @@
 bool MatrixContainer::ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns)
 {
-	char filename[1023];
-	ifstream input;
-	char *FragmentNumber = NULL;
-	stringstream file;
-	string token;
-
-	// count the number of matrices
-	MatrixCounter = -1; // we count one too much
-	file << name << FRAGMENTPREFIX << KEYSETFILE;
-	input.open(file.str().c_str(), ios::in);
-	if (input == NULL) {
-		cout << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
-		return false;
-	}
-	while (!input.eof()) {
-		input.getline(filename, 1023);
-		stringstream zeile(filename);
-		MatrixCounter++;
-	}
-	input.close();
-	cout << "Determined " << MatrixCounter << " fragments." << endl;
-
-	cout << "Parsing through each fragment and retrieving " << prefix << suffix << "." << endl;
-	Matrix = (double ***) ReAlloc(Matrix, sizeof(double **)*(MatrixCounter+1), "MatrixContainer::ParseFragmentMatrix: ***Matrix"); // one more each for the total molecule
-	RowCounter = (int *) ReAlloc(RowCounter, sizeof(int)*(MatrixCounter+1), "MatrixContainer::ParseFragmentMatrix: *RowCounter");
-	for(int i=MatrixCounter+1;i--;) {
-		Matrix[i] = NULL;
-		RowCounter[i] = -1;
-	}
-	for(int i=0; i < MatrixCounter;i++) {
-		// open matrix file
-		FragmentNumber = FixedDigitNumber(MatrixCounter, i);
-		file.str(" ");
-		file << name << FRAGMENTPREFIX << FragmentNumber << prefix << suffix;
-		if (!ParseMatrix(file.str().c_str(), skiplines, skipcolumns, i))
-			return false;
-		Free((void **)&FragmentNumber, "MatrixContainer::ParseFragmentMatrix: *FragmentNumber");
-	}
-	return true;
+  char filename[1023];
+  ifstream input;
+  char *FragmentNumber = NULL;
+  stringstream file;
+  string token;
+
+  // count the number of matrices
+  MatrixCounter = -1; // we count one too much
+  file << name << FRAGMENTPREFIX << KEYSETFILE;
+  input.open(file.str().c_str(), ios::in);
+  if (input == NULL) {
+    cout << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
+    return false;
+  }
+  while (!input.eof()) {
+    input.getline(filename, 1023);
+    stringstream zeile(filename);
+    MatrixCounter++;
+  }
+  input.close();
+  cout << "Determined " << MatrixCounter << " fragments." << endl;
+
+  cout << "Parsing through each fragment and retrieving " << prefix << suffix << "." << endl;
+  Header = (char **) ReAlloc(Header, sizeof(char *)*(MatrixCounter+1), "MatrixContainer::ParseFragmentMatrix: **Header"); // one more each for the total molecule
+  Matrix = (double ***) ReAlloc(Matrix, sizeof(double **)*(MatrixCounter+1), "MatrixContainer::ParseFragmentMatrix: ***Matrix"); // one more each for the total molecule
+  RowCounter = (int *) ReAlloc(RowCounter, sizeof(int)*(MatrixCounter+1), "MatrixContainer::ParseFragmentMatrix: *RowCounter");
+  ColumnCounter = (int *) ReAlloc(ColumnCounter, sizeof(int)*(MatrixCounter+1), "MatrixContainer::ParseFragmentMatrix: *ColumnCounter");
+  for(int i=MatrixCounter+1;i--;) {
+    Matrix[i] = NULL;
+    Header[i] = NULL;
+    RowCounter[i] = -1;
+    ColumnCounter[i] = -1;
+  }
+  for(int i=0; i < MatrixCounter;i++) {
+    // open matrix file
+    FragmentNumber = FixedDigitNumber(MatrixCounter, i);
+    file.str(" ");
+    file << name << FRAGMENTPREFIX << FragmentNumber << prefix << suffix;
+    if (!ParseMatrix(file.str().c_str(), skiplines, skipcolumns, i))
+      return false;
+    Free((void **)&FragmentNumber, "MatrixContainer::ParseFragmentMatrix: *FragmentNumber");
+  }
+  return true;
 };
 
 /** Allocates and resets the memory for a number \a MCounter of matrices.
- * \param *GivenHeader Header line
+ * \param **GivenHeader Header line for each matrix
  * \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(const char *GivenHeader, int MCounter, int *RCounter, int CCounter)
-{
-	Header = (char *) Malloc(sizeof(char)*1024, "MatrixContainer::ParseFragmentMatrix: *EnergyHeader");
-	strncpy(Header, GivenHeader, 1023);
-
-	MatrixCounter = MCounter;
-	ColumnCounter = CCounter;
-	Matrix = (double ***) Malloc(sizeof(double **)*(MatrixCounter+1), "MatrixContainer::ParseFragmentMatrix: ***Matrix"); // one more each for the total molecule
-	RowCounter = (int *) Malloc(sizeof(int)*(MatrixCounter+1), "MatrixContainer::ParseFragmentMatrix: *RowCounter");
-	for(int i=MatrixCounter+1;i--;) {
-		RowCounter[i] = RCounter[i];
-		Matrix[i] = (double **) Malloc(sizeof(double *)*(RowCounter[i]+1), "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
-		for(int j=RowCounter[i]+1;j--;) {
-			Matrix[i][j] = (double *) Malloc(sizeof(double)*ColumnCounter, "MatrixContainer::ParseFragmentMatrix: *Matrix[][]");
-			for(int k=ColumnCounter;k--;)
-				Matrix[i][j][k] = 0.;
-		}
-	}
-	return true;
+ * \param *CCounter number of columns for each matrix
+ * \return Allocation successful 
+ */
+bool MatrixContainer::AllocateMatrix(char **GivenHeader, int MCounter, int *RCounter, int *CCounter)
+{
+  MatrixCounter = MCounter;
+  Header = (char **) Malloc(sizeof(char *)*(MatrixCounter+1), "MatrixContainer::AllocateMatrix: *Header");
+  Matrix = (double ***) Malloc(sizeof(double **)*(MatrixCounter+1), "MatrixContainer::AllocateMatrix: ***Matrix"); // one more each for the total molecule
+  RowCounter = (int *) Malloc(sizeof(int)*(MatrixCounter+1), "MatrixContainer::AllocateMatrix: *RowCounter");
+  ColumnCounter = (int *) Malloc(sizeof(int)*(MatrixCounter+1), "MatrixContainer::AllocateMatrix: *ColumnCounter");
+  for(int i=MatrixCounter+1;i--;) {
+    Header[i] = (char *) Malloc(sizeof(char)*1024, "MatrixContainer::AllocateMatrix: *Header[i]");
+    strncpy(Header[i], GivenHeader[i], 1023);
+    RowCounter[i] = RCounter[i];
+    ColumnCounter[i] = CCounter[i];
+    Matrix[i] = (double **) Malloc(sizeof(double *)*(RowCounter[i]+1), "MatrixContainer::AllocateMatrix: **Matrix[]");  
+    for(int j=RowCounter[i]+1;j--;) {
+      Matrix[i][j] = (double *) Malloc(sizeof(double)*ColumnCounter[i], "MatrixContainer::AllocateMatrix: *Matrix[][]");
+      for(int k=ColumnCounter[i];k--;)
+        Matrix[i][j][k] = 0.;
+    }
+  }
+  return true;
 };
 
@@ -284,9 +330,9 @@
 bool MatrixContainer::ResetMatrix()
 {
-	for(int i=MatrixCounter+1;i--;)
-		for(int j=RowCounter[i]+1;j--;)
-			for(int k=ColumnCounter;k--;)
-				Matrix[i][j][k] = 0.;
-	 return true;
+  for(int i=MatrixCounter+1;i--;)
+    for(int j=RowCounter[i]+1;j--;)
+      for(int k=ColumnCounter[i];k--;)
+        Matrix[i][j][k] = 0.;
+   return true;
 };
 
@@ -296,12 +342,12 @@
 double MatrixContainer::FindMaxValue()
 {
-	double max = Matrix[0][0][0];
-	for(int i=MatrixCounter+1;i--;)
-		for(int j=RowCounter[i]+1;j--;)
-			for(int k=ColumnCounter;k--;)
-				if (fabs(Matrix[i][j][k]) > max)
-					max = fabs(Matrix[i][j][k]);
-	if (fabs(max) < MYEPSILON)
-		max += MYEPSILON;
+  double max = Matrix[0][0][0];
+  for(int i=MatrixCounter+1;i--;)
+    for(int j=RowCounter[i]+1;j--;)
+      for(int k=ColumnCounter[i];k--;)
+        if (fabs(Matrix[i][j][k]) > max)
+          max = fabs(Matrix[i][j][k]);
+  if (fabs(max) < MYEPSILON)
+    max += MYEPSILON;
  return max;
 };
@@ -312,13 +358,13 @@
 double MatrixContainer::FindMinValue()
 {
-	double min = Matrix[0][0][0];
-	for(int i=MatrixCounter+1;i--;)
-		for(int j=RowCounter[i]+1;j--;)
-			for(int k=ColumnCounter;k--;)
-				if (fabs(Matrix[i][j][k]) < min)
-					min = fabs(Matrix[i][j][k]);
-	if (fabs(min) < MYEPSILON)
-		min += MYEPSILON;
-	return min;
+  double min = Matrix[0][0][0];
+  for(int i=MatrixCounter+1;i--;)
+    for(int j=RowCounter[i]+1;j--;)
+      for(int k=ColumnCounter[i];k--;)
+        if (fabs(Matrix[i][j][k]) < min)
+          min = fabs(Matrix[i][j][k]);
+  if (fabs(min) < MYEPSILON)
+    min += MYEPSILON;
+  return min;
 };
 
@@ -330,8 +376,8 @@
 bool MatrixContainer::SetLastMatrix(double value, int skipcolumns)
 {
-	for(int j=RowCounter[MatrixCounter]+1;j--;)
-		for(int k=skipcolumns;k<ColumnCounter;k++)
-			Matrix[MatrixCounter][j][k] = value;
-	 return true;
+  for(int j=RowCounter[MatrixCounter]+1;j--;)
+    for(int k=skipcolumns;k<ColumnCounter[MatrixCounter];k++)
+      Matrix[MatrixCounter][j][k] = value;
+   return true;
 };
 
@@ -343,13 +389,13 @@
 bool MatrixContainer::SetLastMatrix(double **values, int skipcolumns)
 {
-	for(int j=RowCounter[MatrixCounter]+1;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.
+  for(int j=RowCounter[MatrixCounter]+1;j--;)
+    for(int k=skipcolumns;k<ColumnCounter[MatrixCounter];k++)
+      Matrix[MatrixCounter][j][k] = values[j][k];
+   return true;
+};
+
+/** Sums the entries with each factor and put into last element of \a ***Matrix.
  * Sums over "E"-terms to create the "F"-terms
- * \param Matrix MatrixContainer with matrices (LevelCounter by ColumnCounter) with all the 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
@@ -358,49 +404,49 @@
 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 " << MatrixValues.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 << "In fragment No. " << KeySet.OrderSet[Order][CurrentFragment]	 << " 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=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=ColumnCounter;l--;)
-									Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][m][l] -= Matrix[ KeySet.OrderSet[SubOrder][j] ][k][l];
-							}
-						}
-						//if ((ColumnCounter>1) && (RowCounter[0]-1 >= 1))
-						 //cout << "Fragments[ KeySet.OrderSet[" << Order << "][" << CurrentFragment << "]=" << KeySet.OrderSet[Order][CurrentFragment] << " ][" << RowCounter[0]-1 << "][" << 1 << "] = " <<	Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][RowCounter[0]-1][1] << endl;
-					}
-				} else {
-					//cout << "Fragment " << KeySet.OrderSet[SubOrder][j] << " is not contained in fragment " << KeySet.OrderSet[Order][CurrentFragment] << "." << endl;
-				}
-			}
-		}
-	 //cout << "Final Fragments[ KeySet.OrderSet[" << Order << "][" << CurrentFragment << "]=" << KeySet.OrderSet[Order][CurrentFragment] << " ][" << KeySet.AtomCounter[0]-1 << "][" << 1 << "] = " <<	Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][KeySet.AtomCounter[0]-1][1] << endl;
-	}
-
-	return true;
+  // 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 " << MatrixValues.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 << "In fragment No. " << KeySet.OrderSet[Order][CurrentFragment]   << " 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=ColumnCounter[ KeySet.OrderSet[SubOrder][j] ];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=ColumnCounter[ KeySet.OrderSet[SubOrder][j] ];l--;)
+                  Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][m][l] -= Matrix[ KeySet.OrderSet[SubOrder][j] ][k][l];
+              }
+            }
+            //if ((ColumnCounter[ KeySet.OrderSet[SubOrder][j] ]>1) && (RowCounter[0]-1 >= 1))
+             //cout << "Fragments[ KeySet.OrderSet[" << Order << "][" << CurrentFragment << "]=" << KeySet.OrderSet[Order][CurrentFragment] << " ][" << RowCounter[0]-1 << "][" << 1 << "] = " <<  Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][RowCounter[0]-1][1] << endl;
+          }
+        } else {
+          //cout << "Fragment " << KeySet.OrderSet[SubOrder][j] << " is not contained in fragment " << KeySet.OrderSet[Order][CurrentFragment] << "." << endl;
+        }
+      }
+    }
+   //cout << "Final Fragments[ KeySet.OrderSet[" << Order << "][" << CurrentFragment << "]=" << KeySet.OrderSet[Order][CurrentFragment] << " ][" << KeySet.AtomCounter[0]-1 << "][" << 1 << "] = " <<  Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][KeySet.AtomCounter[0]-1][1] << endl;
+  }
+
+  return true;
 };
 
@@ -412,27 +458,27 @@
 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;
+  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[i] << endl;
+    for(int j=0;j<RowCounter[i];j++) {
+      for(int k=0;k<ColumnCounter[i];k++)
+        output << scientific << Matrix[i][j][k] << "\t";
+      output << endl;
+    }
+    output.close();
+  }
+  return true;
 };
 
@@ -445,22 +491,22 @@
 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;
+  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[MatrixCounter] << endl;
+  for(int j=0;j<RowCounter[MatrixCounter];j++) {
+    for(int k=0;k<ColumnCounter[MatrixCounter];k++)
+      output << scientific << Matrix[MatrixCounter][j][k] << "\t";
+    output << endl;
+  }
+  output.close();
+  return true;
 };
 
@@ -473,17 +519,17 @@
 bool EnergyMatrix::ParseIndices()
 {
-	cout << "Parsing energy indices." << endl;
-	Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "EnergyMatrix::ParseIndices: **Indices");
-	for(int i=MatrixCounter+1;i--;) {
-		Indices[i] = (int *) Malloc(sizeof(int)*RowCounter[i], "EnergyMatrix::ParseIndices: *Indices[]");
-		for(int j=RowCounter[i];j--;)
-			Indices[i][j] = j;
-	}
-	return true;
+  cout << "Parsing energy indices." << endl;
+  Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "EnergyMatrix::ParseIndices: **Indices");
+  for(int i=MatrixCounter+1;i--;) {
+    Indices[i] = (int *) Malloc(sizeof(int)*RowCounter[i], "EnergyMatrix::ParseIndices: *Indices[]");
+    for(int 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.
  * Sums over the "F"-terms in ANOVA decomposition.
- * \param Matrix MatrixContainer with matrices (LevelCounter by ColumnCounter) with all the energies.
+ * \param Matrix MatrixContainer with matrices (LevelCounter by *ColumnCounter) with all the energies.
  * \param CorrectionFragments MatrixContainer with hydrogen saturation correction per fragments
  * \param KeySet KeySetContainer with bond Order and association mapping of each fragment to an order
@@ -494,16 +540,16 @@
 bool EnergyMatrix::SumSubEnergy(class EnergyMatrix &Fragments, class EnergyMatrix *CorrectionFragments, class KeySetsContainer &KeySet, int Order, double sign)
 {
-	// sum energy
-	if (CorrectionFragments == NULL)
-		for(int i=KeySet.FragmentsPerOrder[Order];i--;)
-			for(int j=RowCounter[ KeySet.OrderSet[Order][i] ];j--;)
-				for(int k=ColumnCounter;k--;)
-					Matrix[MatrixCounter][j][k] += sign*Fragments.Matrix[ KeySet.OrderSet[Order][i] ][j][k];
-	else
-		for(int i=KeySet.FragmentsPerOrder[Order];i--;)
-			for(int j=RowCounter[ KeySet.OrderSet[Order][i] ];j--;)
-				for(int k=ColumnCounter;k--;)
-					Matrix[MatrixCounter][j][k] += sign*(Fragments.Matrix[ KeySet.OrderSet[Order][i] ][j][k] + CorrectionFragments->Matrix[ KeySet.OrderSet[Order][i] ][j][k]);
-	return true;
+  // sum energy
+  if (CorrectionFragments == NULL)
+    for(int i=KeySet.FragmentsPerOrder[Order];i--;)
+      for(int j=RowCounter[ KeySet.OrderSet[Order][i] ];j--;)
+        for(int k=ColumnCounter[ KeySet.OrderSet[Order][i] ];k--;)
+          Matrix[MatrixCounter][j][k] += sign*Fragments.Matrix[ KeySet.OrderSet[Order][i] ][j][k];
+  else
+    for(int i=KeySet.FragmentsPerOrder[Order];i--;)
+      for(int j=RowCounter[ KeySet.OrderSet[Order][i] ];j--;)
+        for(int k=ColumnCounter[ KeySet.OrderSet[Order][i] ];k--;)
+          Matrix[MatrixCounter][j][k] += sign*(Fragments.Matrix[ KeySet.OrderSet[Order][i] ][j][k] + CorrectionFragments->Matrix[ KeySet.OrderSet[Order][i] ][j][k]);
+  return true;
 };
 
@@ -518,26 +564,30 @@
 bool EnergyMatrix::ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns)
 {
-	char filename[1024];
-	bool status = MatrixContainer::ParseFragmentMatrix(name, prefix, suffix, skiplines, skipcolumns);
-
-	if (status) {
-		// count maximum of columns
-		RowCounter[MatrixCounter] = 0;
-		for(int j=0; j < MatrixCounter;j++) // (energy matrix might be bigger than number of atoms in terms of rows)
-			if (RowCounter[j] > RowCounter[MatrixCounter])
-				RowCounter[MatrixCounter] = RowCounter[j];
-		// allocate last plus one matrix
-		cout << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter << " columns." << endl;
-		Matrix[MatrixCounter] = (double **) Malloc(sizeof(double *)*(RowCounter[MatrixCounter]+1), "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
-		for(int j=0;j<=RowCounter[MatrixCounter];j++)
-			Matrix[MatrixCounter][j] = (double *) Malloc(sizeof(double)*ColumnCounter, "MatrixContainer::ParseFragmentMatrix: *Matrix[][]");
-
-		// try independently to parse global energysuffix file if present
-		strncpy(filename, name, 1023);
-		strncat(filename, prefix, 1023-strlen(filename));
-		strncat(filename, suffix.c_str(), 1023-strlen(filename));
-		ParseMatrix(filename, skiplines, skipcolumns, MatrixCounter);
-	}
-	return status;
+  char filename[1024];
+  bool status = MatrixContainer::ParseFragmentMatrix(name, prefix, suffix, skiplines, skipcolumns);
+
+  if (status) {
+    // count maximum of columns
+    RowCounter[MatrixCounter] = 0;
+    ColumnCounter[MatrixCounter] = 0;
+    for(int j=0; j < MatrixCounter;j++) { // (energy matrix might be bigger than number of atoms in terms of rows)
+      if (RowCounter[j] > RowCounter[MatrixCounter])
+        RowCounter[MatrixCounter] = RowCounter[j];
+      if (ColumnCounter[j] > ColumnCounter[MatrixCounter])  // take maximum of all for last matrix
+        ColumnCounter[MatrixCounter] = ColumnCounter[j];
+    }
+    // allocate last plus one matrix
+    cout << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl;
+    Matrix[MatrixCounter] = (double **) Malloc(sizeof(double *)*(RowCounter[MatrixCounter]+1), "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
+    for(int j=0;j<=RowCounter[MatrixCounter];j++)
+      Matrix[MatrixCounter][j] = (double *) Malloc(sizeof(double)*ColumnCounter[MatrixCounter], "MatrixContainer::ParseFragmentMatrix: *Matrix[][]");
+    
+    // try independently to parse global energysuffix file if present
+    strncpy(filename, name, 1023);
+    strncat(filename, prefix, 1023-strlen(filename));
+    strncat(filename, suffix.c_str(), 1023-strlen(filename));
+    ParseMatrix(filename, skiplines, skipcolumns, MatrixCounter);
+  }
+  return status;
 };
 
@@ -550,69 +600,69 @@
 bool ForceMatrix::ParseIndices(const char *name)
 {
-	ifstream input;
-	char *FragmentNumber = NULL;
-	char filename[1023];
-	stringstream line;
-
-	cout << "Parsing force indices for " << MatrixCounter << " matrices." << endl;
-	Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "ForceMatrix::ParseIndices: **Indices");
-	line << name << FRAGMENTPREFIX << 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
-		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=RowCounter[MatrixCounter];j--;) {
-		Indices[MatrixCounter][j] = j;
-	}
-	input.close();
-	return true;
+  ifstream input;
+  char *FragmentNumber = NULL;
+  char filename[1023];
+  stringstream line;
+
+  cout << "Parsing force indices for " << MatrixCounter << " matrices." << endl;
+  Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "ForceMatrix::ParseIndices: **Indices");
+  line << name << FRAGMENTPREFIX << 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
+    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=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 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
- *	\param sign +1 or -1
+ *  \param sign +1 or -1
  * \return true if summing was successful
  */
 bool ForceMatrix::SumSubForces(class ForceMatrix &Fragments, class KeySetsContainer &KeySet, int Order, double sign)
 {
-	int FragmentNr;
-	// sum forces
-	for(int i=0;i<KeySet.FragmentsPerOrder[Order];i++) {
-		FragmentNr = KeySet.OrderSet[Order][i];
-		for(int l=0;l<RowCounter[ FragmentNr ];l++) {
-			int j = Indices[ FragmentNr ][l];
-			if (j > RowCounter[MatrixCounter]) {
-				cerr << "Current force index " << j << " is greater than " << RowCounter[MatrixCounter] << "!" << endl;
-				return false;
-			}
-			if (j != -1) {
-				//if (j == 0) cout << "Summing onto ion 0, type 0 from fragment " << FragmentNr << ", ion " << l << "." << endl;
-				for(int k=2;k<ColumnCounter;k++)
-					Matrix[MatrixCounter][j][k] += sign*Fragments.Matrix[ FragmentNr ][l][k];
-			}
-		}
-	}
-	return true;
+  int FragmentNr;
+  // sum forces
+  for(int i=0;i<KeySet.FragmentsPerOrder[Order];i++) {
+    FragmentNr = KeySet.OrderSet[Order][i];
+    for(int l=0;l<RowCounter[ FragmentNr ];l++) {
+      int j = Indices[ FragmentNr ][l];
+      if (j > RowCounter[MatrixCounter]) {
+        cerr << "Current force index " << j << " is greater than " << RowCounter[MatrixCounter] << "!" << endl;
+        return false;
+      }
+      if (j != -1) {
+        //if (j == 0) cout << "Summing onto ion 0, type 0 from fragment " << FragmentNr << ", ion " << l << "." << endl;
+        for(int k=2;k<ColumnCounter[MatrixCounter];k++)
+          Matrix[MatrixCounter][j][k] += sign*Fragments.Matrix[ FragmentNr ][l][k];
+      }
+    }
+  }
+  return true;
 };
 
@@ -628,47 +678,277 @@
 bool ForceMatrix::ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns)
 {
-	char filename[1023];
-	ifstream input;
-	stringstream file;
-	int nr;
-	bool status = MatrixContainer::ParseFragmentMatrix(name, prefix, suffix, skiplines, skipcolumns);
-
-	if (status) {
-		// count number of atoms for last plus one matrix
-		file << name << FRAGMENTPREFIX << KEYSETFILE;
-		input.open(file.str().c_str(), ios::in);
-		if (input == NULL) {
-			cout << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
-			return false;
-		}
-		RowCounter[MatrixCounter] = 0;
-		while (!input.eof()) {
-			input.getline(filename, 1023);
-			stringstream zeile(filename);
-			while (!zeile.eof()) {
-				zeile >> nr;
-				//cout << "Current index: " << nr << "." << endl;
-				if (nr > RowCounter[MatrixCounter])
-					RowCounter[MatrixCounter] = nr;
-			}
-		}
-		RowCounter[MatrixCounter]++;		// nr start at 0, count starts at 1
-		input.close();
-
-		// allocate last plus one matrix
-		cout << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter << " columns." << endl;
-		Matrix[MatrixCounter] = (double **) Malloc(sizeof(double *)*(RowCounter[MatrixCounter]+1), "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
-		for(int j=0;j<=RowCounter[MatrixCounter];j++)
-			Matrix[MatrixCounter][j] = (double *) Malloc(sizeof(double)*ColumnCounter, "MatrixContainer::ParseFragmentMatrix: *Matrix[][]");
-
-		// try independently to parse global forcesuffix file if present
-		strncpy(filename, name, 1023);
-		strncat(filename, prefix, 1023-strlen(filename));
-		strncat(filename, suffix.c_str(), 1023-strlen(filename));
-		ParseMatrix(filename, skiplines, skipcolumns, MatrixCounter);
-	}
-
-
-	return status;
+  char filename[1023];
+  ifstream input;
+  stringstream file;
+  int nr;
+  bool status = MatrixContainer::ParseFragmentMatrix(name, prefix, suffix, skiplines, skipcolumns);
+
+  if (status) {
+    // count number of atoms for last plus one matrix
+    file << name << FRAGMENTPREFIX << KEYSETFILE;
+    input.open(file.str().c_str(), ios::in);
+    if (input == NULL) {
+      cout << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
+      return false;
+    }
+    RowCounter[MatrixCounter] = 0;
+    while (!input.eof()) {
+      input.getline(filename, 1023);
+      stringstream zeile(filename);
+      while (!zeile.eof()) {
+        zeile >> nr;
+        //cout << "Current index: " << nr << "." << endl;
+        if (nr > RowCounter[MatrixCounter])
+          RowCounter[MatrixCounter] = nr;
+      }
+    }
+    RowCounter[MatrixCounter]++;    // nr start at 0, count starts at 1
+    input.close();
+
+    ColumnCounter[MatrixCounter] = 0;
+    for(int j=0; j < MatrixCounter;j++) { // (energy matrix might be bigger than number of atoms in terms of rows)
+      if (ColumnCounter[j] > ColumnCounter[MatrixCounter])  // take maximum of all for last matrix
+        ColumnCounter[MatrixCounter] = ColumnCounter[j];
+    }
+  
+    // allocate last plus one matrix
+    cout << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl;
+    Matrix[MatrixCounter] = (double **) Malloc(sizeof(double *)*(RowCounter[MatrixCounter]+1), "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
+    for(int j=0;j<=RowCounter[MatrixCounter];j++)
+      Matrix[MatrixCounter][j] = (double *) Malloc(sizeof(double)*ColumnCounter[MatrixCounter], "MatrixContainer::ParseFragmentMatrix: *Matrix[][]");
+
+    // try independently to parse global forcesuffix file if present
+    strncpy(filename, name, 1023);
+    strncat(filename, prefix, 1023-strlen(filename));
+    strncat(filename, suffix.c_str(), 1023-strlen(filename));
+    ParseMatrix(filename, skiplines, skipcolumns, MatrixCounter);
+  }
+ 
+
+  return status;
+};
+
+// ======================================= CLASS HessianMatrix =============================
+
+/** Parsing force Indices of each fragment
+ * \param *name directory with \a ForcesFile
+ * \return parsing successful 
+ */
+bool HessianMatrix::ParseIndices(char *name) 
+{
+  ifstream input;
+  char *FragmentNumber = NULL;
+  char filename[1023];
+  stringstream line;
+  
+  cout << "Parsing hessian indices for " << MatrixCounter << " matrices." << endl;
+  Indices = (int **) Malloc(sizeof(int *)*(MatrixCounter+1), "HessianMatrix::ParseIndices: **Indices");
+  line << name << FRAGMENTPREFIX << 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
+    input.getline(filename, 1023);
+    line.str(filename);
+    // parse the values
+    Indices[i] = (int *) Malloc(sizeof(int)*RowCounter[i], "HessianMatrix::ParseIndices: *Indices[]");
+    FragmentNumber = FixedDigitNumber(MatrixCounter, i);
+    //cout << FRAGMENTPREFIX << FragmentNumber << "[" << RowCounter[i] << "]:";
+    Free((void **)&FragmentNumber, "HessianMatrix::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], "HessianMatrix::ParseIndices: *Indices[]");
+  for(int j=RowCounter[MatrixCounter];j--;) {
+    Indices[MatrixCounter][j] = j;
+  }
+  input.close();
+  return true;
+};
+
+
+/** Sums the hessian entries and puts into last element of \a HessianMatrix::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
+ *  \param sign +1 or -1
+ * \return true if summing was successful
+ */
+bool HessianMatrix::SumSubHessians(class HessianMatrix &Fragments, class KeySetsContainer &KeySet, int Order, double sign)
+{
+  int FragmentNr;
+  // sum forces
+  for(int i=0;i<KeySet.FragmentsPerOrder[Order];i++) {
+    FragmentNr = KeySet.OrderSet[Order][i];
+    for(int l=0;l<RowCounter[ FragmentNr ];l++) {
+      int j = Indices[ FragmentNr ][l];
+      if (j > RowCounter[MatrixCounter]) {
+        cerr << "Current hessian index " << j << " is greater than " << RowCounter[MatrixCounter] << ", where i=" << i << ", Order=" << Order << ", l=" << l << " and FragmentNr=" << FragmentNr << "!" << endl;
+        return false;
+      }
+      if (j != -1) {
+        for(int m=0;m<ColumnCounter[ FragmentNr ];m++) {
+          int k = Indices[ FragmentNr ][m];
+          if (k > ColumnCounter[MatrixCounter]) {
+            cerr << "Current hessian index " << k << " is greater than " << ColumnCounter[MatrixCounter] << ", where m=" << m << ", j=" << j << ", i=" << i << ", Order=" << Order << ", l=" << l << " and FragmentNr=" << FragmentNr << "!" << endl;
+            return false;
+          }
+          if (k != -1) {
+            //cout << "Adding " << sign*Fragments.Matrix[ FragmentNr ][l][m] << " from [" << l << "][" << m << "] onto [" << j << "][" << k << "]." << endl;
+            Matrix[MatrixCounter][j][k] += sign*Fragments.Matrix[ FragmentNr ][l][m];
+          }
+        }
+      }
+    }
+  }
+  return true;
+};
+
+/** Constructor for class HessianMatrix.
+ */
+HessianMatrix::HessianMatrix() : MatrixContainer() 
+{
+   IsSymmetric = true;
+}
+
+/** Sums the hessian entries with each factor and put into last element of \a ***Matrix.
+ * Sums over "E"-terms to create the "F"-terms
+ * \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 HessianMatrix::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 row 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 " << MatrixValues.Indices[ KeySet.OrderSet[Order][CurrentFragment] ][l] << "." << endl;
+                if (m == MatrixValues.Indices[ KeySet.OrderSet[Order][CurrentFragment] ][l]) {
+                  m = l;
+                  break;  
+                }
+              }
+              //cout << "Corresponding row index for " << k << " in CurrentFragment is " << m << "." << endl;
+              if (m > RowCounter[ KeySet.OrderSet[Order][CurrentFragment] ]) {
+                cerr << "In fragment No. " << KeySet.OrderSet[Order][CurrentFragment]   << " current row index " << m << " is greater than " << RowCounter[ KeySet.OrderSet[Order][CurrentFragment] ] << "!" << endl;
+                return false;
+              }
+              
+              for(int l=0;l<ColumnCounter[ KeySet.OrderSet[SubOrder][j] ];l++) { 
+                int n = MatrixValues.Indices[ KeySet.OrderSet[SubOrder][j] ][l];
+                //cout << "Current column index is " << l << "/" << n << "." << endl;
+                if (n != -1) { // if it's not an added hydrogen
+                  for (int p=0;p<ColumnCounter[ KeySet.OrderSet[Order][CurrentFragment] ];p++) { // look for the corresponding index in the current fragment
+                    //cout << "Comparing " << n << " with " << MatrixValues.Indices[ KeySet.OrderSet[Order][CurrentFragment] ][p] << "." << endl;
+                    if (n == MatrixValues.Indices[ KeySet.OrderSet[Order][CurrentFragment] ][p]) {
+                      n = p;
+                      break;  
+                    }
+                  }
+                  //cout << "Corresponding column index for " << l << " in CurrentFragment is " << n << "." << endl;
+                  if (n > ColumnCounter[ KeySet.OrderSet[Order][CurrentFragment] ]) {
+                    cerr << "In fragment No. " << KeySet.OrderSet[Order][CurrentFragment]   << " current column index " << n << " is greater than " << ColumnCounter[ KeySet.OrderSet[Order][CurrentFragment] ] << "!" << endl;
+                    return false;
+                  }
+                  if (Order == SubOrder) { // equal order is always copy from Energies
+                    //cout << "Adding " << MatrixValues.Matrix[ KeySet.OrderSet[SubOrder][j] ][k][l] << " from [" << k << "][" << l << "] onto [" << m << "][" << n << "]." << endl;
+                    Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][m][n] += MatrixValues.Matrix[ KeySet.OrderSet[SubOrder][j] ][k][l];
+                  } else {
+                    //cout << "Subtracting " << Matrix[ KeySet.OrderSet[SubOrder][j] ][k][l] << " from [" << k << "][" << l << "] onto [" << m << "][" << n << "]." << endl;
+                    Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][m][n] -= Matrix[ KeySet.OrderSet[SubOrder][j] ][k][l];
+                  }
+                }
+              }
+            }
+            //if ((ColumnCounter[ KeySet.OrderSet[SubOrder][j] ]>1) && (RowCounter[0]-1 >= 1))
+             //cout << "Fragments[ KeySet.OrderSet[" << Order << "][" << CurrentFragment << "]=" << KeySet.OrderSet[Order][CurrentFragment] << " ][" << RowCounter[0]-1 << "][" << 1 << "] = " <<  Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][RowCounter[0]-1][1] << endl;
+          }
+        } else {
+          //cout << "Fragment " << KeySet.OrderSet[SubOrder][j] << " is not contained in fragment " << KeySet.OrderSet[Order][CurrentFragment] << "." << endl;
+        }
+      }
+    }
+   //cout << "Final Fragments[ KeySet.OrderSet[" << Order << "][" << CurrentFragment << "]=" << KeySet.OrderSet[Order][CurrentFragment] << " ][" << KeySet.AtomCounter[0]-1 << "][" << 1 << "] = " <<  Matrix[ KeySet.OrderSet[Order][CurrentFragment] ][KeySet.AtomCounter[0]-1][1] << endl;
+  }
+  
+  return true;
+};
+
+/** Calls MatrixContainer::ParseFragmentMatrix() and additionally allocates last plus one matrix.
+ * \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 HessianMatrix::ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns)
+{
+  char filename[1023];
+  ifstream input;
+  stringstream file;
+  int nr;
+  bool status = MatrixContainer::ParseFragmentMatrix(name, prefix, suffix, skiplines, skipcolumns);
+
+  if (status) {
+    // count number of atoms for last plus one matrix
+    file << name << FRAGMENTPREFIX << KEYSETFILE;
+    input.open(file.str().c_str(), ios::in);
+    if (input == NULL) {
+      cout << endl << "Unable to open " << file.str() << ", is the directory correct?" << endl;
+      return false;
+    }
+    RowCounter[MatrixCounter] = 0;
+    ColumnCounter[MatrixCounter] = 0;
+    while (!input.eof()) {
+      input.getline(filename, 1023);
+      stringstream zeile(filename);
+      while (!zeile.eof()) {
+        zeile >> nr;
+        //cout << "Current index: " << nr << "." << endl;
+        if (nr > RowCounter[MatrixCounter]) {
+          RowCounter[MatrixCounter] = nr;
+          ColumnCounter[MatrixCounter] = nr;
+        }
+      }
+    }
+    RowCounter[MatrixCounter]++;    // nr start at 0, count starts at 1
+    ColumnCounter[MatrixCounter]++;    // nr start at 0, count starts at 1
+    input.close();
+  
+    // allocate last plus one matrix
+    cout << "Allocating last plus one matrix with " << (RowCounter[MatrixCounter]+1) << " rows and " << ColumnCounter[MatrixCounter] << " columns." << endl;
+    Matrix[MatrixCounter] = (double **) Malloc(sizeof(double *)*(RowCounter[MatrixCounter]+1), "MatrixContainer::ParseFragmentMatrix: **Matrix[]");
+    for(int j=0;j<=RowCounter[MatrixCounter];j++)
+      Matrix[MatrixCounter][j] = (double *) Malloc(sizeof(double)*ColumnCounter[MatrixCounter], "MatrixContainer::ParseFragmentMatrix: *Matrix[][]");
+
+    // try independently to parse global forcesuffix file if present
+    strncpy(filename, name, 1023);
+    strncat(filename, prefix, 1023-strlen(filename));
+    strncat(filename, suffix.c_str(), 1023-strlen(filename));
+    ParseMatrix(filename, skiplines, skipcolumns, MatrixCounter);
+  }
+
+
+  return status;
 };
 
@@ -678,10 +958,10 @@
  */
 KeySetsContainer::KeySetsContainer() {
-	KeySets = NULL;
-	AtomCounter = NULL;
-	FragmentCounter = 0;
-	Order = 0;
-	FragmentsPerOrder = 0;
-	OrderSet = NULL;
+  KeySets = NULL;
+  AtomCounter = NULL;
+  FragmentCounter = 0;
+  Order = 0;
+  FragmentsPerOrder = 0;
+  OrderSet = NULL;
 };
 
@@ -689,12 +969,12 @@
  */
 KeySetsContainer::~KeySetsContainer() {
-	for(int i=FragmentCounter;i--;)
-		Free((void **)&KeySets[i], "KeySetsContainer::~KeySetsContainer: *KeySets[]");
-	for(int 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");
+  for(int i=FragmentCounter;i--;)
+    Free((void **)&KeySets[i], "KeySetsContainer::~KeySetsContainer: *KeySets[]");
+  for(int 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");
 };
 
@@ -706,42 +986,42 @@
  */
 bool KeySetsContainer::ParseKeySets(const char *name, const int *ACounter, const int FCounter) {
-	ifstream input;
-	char *FragmentNumber = NULL;
-	stringstream file;
-	char filename[1023];
-
-	FragmentCounter = FCounter;
-	cout << "Parsing key sets." << endl;
-	KeySets = (int **) Malloc(sizeof(int *)*FragmentCounter, "KeySetsContainer::ParseKeySets: **KeySets");
-	for(int i=FragmentCounter;i--;)
-		KeySets[i] = NULL;
-	file << name << FRAGMENTPREFIX << KEYSETFILE;
-	input.open(file.str().c_str(), ios::in);
-	if (input == NULL) {
-		cout << endl << "Unable to open " << file.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[]");
-		for(int j=AtomCounter[i];j--;)
-			KeySets[i][j] = -1;
-		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;
+  ifstream input;
+  char *FragmentNumber = NULL;
+  stringstream file;
+  char filename[1023];
+
+  FragmentCounter = FCounter;
+  cout << "Parsing key sets." << endl;
+  KeySets = (int **) Malloc(sizeof(int *)*FragmentCounter, "KeySetsContainer::ParseKeySets: **KeySets");
+  for(int i=FragmentCounter;i--;)
+    KeySets[i] = NULL;
+  file << name << FRAGMENTPREFIX << KEYSETFILE;
+  input.open(file.str().c_str(), ios::in);
+  if (input == NULL) {
+    cout << endl << "Unable to open " << file.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[]");
+    for(int j=AtomCounter[i];j--;)
+      KeySets[i][j] = -1;
+    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;
 };
 
@@ -751,58 +1031,58 @@
 bool KeySetsContainer::ParseManyBodyTerms()
 {
-	int Counter;
-
-	cout << "Creating Fragment terms." << endl;
-	// scan through all to determine maximum order
-	Order=0;
-	for(int i=FragmentCounter;i--;) {
-		Counter=0;
-		for(int 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=Order;i--;)
-		FragmentsPerOrder[i] = 0;
-	for(int i=FragmentCounter;i--;) {
-		Counter=0;
-		for(int 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=Order;i--;)
-		OrderSet[i] = (int *) Malloc(sizeof(int)*FragmentsPerOrder[i], "KeySetsContainer::ParseManyBodyTermsKeySetsContainer::ParseManyBodyTerms: *OrderSet[]");
-	for(int i=Order;i--;)
-		FragmentsPerOrder[i] = 0;
-	for(int i=FragmentCounter;i--;) {
-		Counter=0;
-		for(int 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;
+  int Counter;
+
+  cout << "Creating Fragment terms." << endl;
+  // scan through all to determine maximum order
+  Order=0;
+  for(int i=FragmentCounter;i--;) {
+    Counter=0;
+    for(int 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=Order;i--;)
+    FragmentsPerOrder[i] = 0;
+  for(int i=FragmentCounter;i--;) {
+    Counter=0;
+    for(int 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=Order;i--;)
+    OrderSet[i] = (int *) Malloc(sizeof(int)*FragmentsPerOrder[i], "KeySetsContainer::ParseManyBodyTermsKeySetsContainer::ParseManyBodyTerms: *OrderSet[]");
+  for(int i=Order;i--;)
+    FragmentsPerOrder[i] = 0;
+  for(int i=FragmentCounter;i--;) {
+    Counter=0;
+    for(int 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;
 };
 
@@ -814,16 +1094,16 @@
 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=AtomCounter[SmallerSet];i--;) {
-		intermediate = false;
-		for (int j=AtomCounter[GreaterSet];j--;)
-			intermediate = (intermediate || ((KeySets[SmallerSet][i] == KeySets[GreaterSet][j]) || (KeySets[SmallerSet][i] == -1)));
-		result = result && intermediate;
-	}
-
-	return result;
+  bool result = true;
+  bool intermediate;
+  if ((GreaterSet < 0) || (SmallerSet < 0) || (GreaterSet > FragmentCounter) || (SmallerSet > FragmentCounter)) // index out of bounds
+    return false;
+  for(int i=AtomCounter[SmallerSet];i--;) {
+    intermediate = false;
+    for (int j=AtomCounter[GreaterSet];j--;)
+      intermediate = (intermediate || ((KeySets[SmallerSet][i] == KeySets[GreaterSet][j]) || (KeySets[SmallerSet][i] == -1)));
+    result = result && intermediate;
+  }
+
+  return result;
 };
 
Index: src/parser.hpp
===================================================================
--- src/parser.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/parser.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -19,15 +19,21 @@
 
 #define EnergySuffix ".energy.all"
+#define EnergyFragmentSuffix ".energyfragment.all"
+#define ForcesSuffix ".forces.all"
+#define ForceFragmentSuffix ".forcefragment.all"
 #define HcorrectionSuffix ".Hcorrection.all"
-#define ForcesSuffix ".forces.all"
+#define HcorrectionFragmentSuffix ".Hcorrectionfragment.all"
+#define HessianSuffix ".hessian_xx.all"
+#define HessianFragmentSuffix ".hessianfragment_xx.all"
+#define OrderSuffix ".Order"
 #define ShieldingSuffix ".sigma_all.csv"
 #define ShieldingPASSuffix ".sigma_all_PAS.csv"
 #define ShieldingFragmentSuffix ".sigma_all_fragment.all"
 #define ShieldingPASFragmentSuffix ".sigma_all_PAS_fragment.all"
+#define ChiSuffix ".chi_all.csv"
+#define ChiPASSuffix ".chi_all_PAS.csv"
+#define ChiFragmentSuffix ".chi_all_fragment.all"
+#define ChiPASFragmentSuffix ".chi_all_PAS_fragment.all"
 #define TimeSuffix ".speed"
-#define EnergyFragmentSuffix ".energyfragment.all"
-#define HcorrectionFragmentSuffix ".Hcorrectionfragment.all"
-#define ForceFragmentSuffix ".forcefragment.all"
-#define OrderSuffix ".Order"
 
 // ======================================= FUNCTIONS ==========================================
@@ -40,28 +46,29 @@
 
 class MatrixContainer {
-	public:
-		double ***Matrix;
-		int **Indices;
-		char *Header;
-		int MatrixCounter;
-		int *RowCounter;
-		int ColumnCounter;
-
-	MatrixContainer();
-	virtual ~MatrixContainer();
-
-	bool ParseMatrix(const char *name, int skiplines, int skipcolumns, int MatrixNr);
-	virtual bool ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns);
-	bool AllocateMatrix(const char *GivenHeader, int MCounter, int *RCounter, int CCounter);
-	bool ResetMatrix();
-	double FindMinValue();
-	double FindMaxValue();
-	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);
+  public:
+    double ***Matrix;
+    int **Indices;
+    char **Header;
+    int MatrixCounter;
+    int *RowCounter;
+    int *ColumnCounter;
+  
+  MatrixContainer();
+  ~MatrixContainer();
+  
+  bool InitialiseIndices(class MatrixContainer *Matrix = NULL);
+  bool ParseMatrix(const char *name, int skiplines, int skipcolumns, int MatrixNr);
+  virtual bool ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns);
+  bool AllocateMatrix(char **GivenHeader, int MCounter, int *RCounter, int *CCounter);
+  bool ResetMatrix();
+  double FindMinValue();
+  double FindMaxValue();
+  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);
 };
 
@@ -69,8 +76,8 @@
 
 class EnergyMatrix : public MatrixContainer {
-	public:
-		bool ParseIndices();
-		bool SumSubEnergy(class EnergyMatrix &Fragments, class EnergyMatrix *CorrectionFragments, class KeySetsContainer &KeySet, int Order, double sign);
-		bool ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns);
+  public:
+    bool ParseIndices();
+    bool SumSubEnergy(class EnergyMatrix &Fragments, class EnergyMatrix *CorrectionFragments, class KeySetsContainer &KeySet, int Order, double sign);
+    bool ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns);
 };
 
@@ -78,8 +85,22 @@
 
 class ForceMatrix : public MatrixContainer {
-	public:
-		bool ParseIndices(const char *name);
-		bool SumSubForces(class ForceMatrix &Fragments, class KeySetsContainer &KeySet, int Order, double sign);
-		bool ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns);
+  public:
+    bool ParseIndices(const char *name);
+    bool SumSubForces(class ForceMatrix &Fragments, class KeySetsContainer &KeySet, int Order, double sign);
+    bool ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns);
+};
+
+// ======================================= CLASS HessianMatrix =============================
+
+class HessianMatrix : public MatrixContainer { 
+  public: 
+    HessianMatrix();
+    //~HessianMatrix();
+    bool ParseIndices(char *name);
+    bool SumSubManyBodyTerms(class MatrixContainer &MatrixValues, class KeySetsContainer &KeySet, int Order);
+    bool SumSubHessians(class HessianMatrix &Fragments, class KeySetsContainer &KeySet, int Order, double sign);
+    bool ParseFragmentMatrix(const char *name, const char *prefix, string suffix, int skiplines, int skipcolumns);
+  private:
+    bool IsSymmetric;
 };
 
@@ -87,18 +108,18 @@
 
 class KeySetsContainer {
-	public:
-		int **KeySets;
-		int *AtomCounter;
-		int FragmentCounter;
-		int Order;
-		int *FragmentsPerOrder;
-		int **OrderSet;
+  public:
+    int **KeySets;
+    int *AtomCounter;
+    int FragmentCounter;
+    int Order;
+    int *FragmentsPerOrder;
+    int **OrderSet;
 
-	KeySetsContainer();
-	~KeySetsContainer();
+  KeySetsContainer();
+  ~KeySetsContainer();
 
-	bool ParseKeySets(const char *name, const int *ACounter, const int FCounter);
-	bool ParseManyBodyTerms();
-	bool Contains(const int GreaterSet, const int SmallerSet);
+  bool ParseKeySets(const char *name, const int *ACounter, const int FCounter);
+  bool ParseManyBodyTerms();
+  bool Contains(const int GreaterSet, const int SmallerSet);
 };
 
Index: src/periodentafel.cpp
===================================================================
--- src/periodentafel.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/periodentafel.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -16,10 +16,10 @@
 periodentafel::periodentafel()
 {
-	start = new element;
-	end = new element;
-	start->previous = NULL;
-	start->next = end;
-	end->previous = start;
-	end->next = NULL;
+  start = new element;
+  end = new element;
+  start->previous = NULL;
+  start->next = end;
+  end->previous = start;
+  end->next = NULL;
 };
 
@@ -29,7 +29,7 @@
 periodentafel::~periodentafel()
 {
-	CleanupPeriodtable();
-	delete(end);
-	delete(start);
+  CleanupPeriodtable();
+  delete(end);
+  delete(start);
 };
 
@@ -40,8 +40,8 @@
 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);
+  pointer->sort = &pointer->Z;
+  if (pointer->Z < 1 && pointer->Z >= MAX_ELEMENTS)
+    cout << Verbose(0) << "Invalid Z number!\n";
+  return add(pointer, end);
 };
 
@@ -52,5 +52,5 @@
 bool periodentafel::RemoveElement(element *pointer)
 {
-	return remove(pointer, start, end);
+  return remove(pointer, start, end);
 };
 
@@ -60,5 +60,5 @@
 bool periodentafel::CleanupPeriodtable()
 {
-	return cleanup(start,end);
+  return cleanup(start,end);
 };
 
@@ -70,19 +70,19 @@
 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);
+  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);
 };
 
@@ -94,11 +94,11 @@
 element * periodentafel::FindElement(const 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);
+  element *walker =  periodentafel::start;
+  while (walker->next != periodentafel::end) {
+    walker = walker->next;
+    if (strncmp(walker->symbol, shorthand, 3) == 0)
+      return(walker);
+  }
+  return (NULL);
 };
 
@@ -107,12 +107,12 @@
 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;
+  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;
 };
 
@@ -122,14 +122,14 @@
 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;
+  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;
 };
 
@@ -140,21 +140,21 @@
 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 ((walker != NULL) && (walker->Z > 0) && (walker->Z < MAX_ELEMENTS) && (checkliste[walker->Z])) {
-				walker->No = No;
-				result = result && walker->Checkout(output, No++, checkliste[walker->Z]);
-			}
-		}
-		return result;
-	} else
-		return false;
+  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 ((walker != NULL) && (walker->Z > 0) && (walker->Z < MAX_ELEMENTS) && (checkliste[walker->Z])) {
+        walker->No = No;
+        result = result && walker->Checkout(output, No++, checkliste[walker->Z]);
+      }
+    }
+    return result;
+  } else
+    return false;
 };
 
@@ -164,137 +164,137 @@
 bool periodentafel::LoadPeriodentafel(const char *path)
 {
-	ifstream infile;
-	double tmp;
-	element *ptr;
-	bool status = true;
-	bool otherstatus = true;
-	char filename[255];
-
-	// fill elements DB
-	strncpy(filename, path, MAXSTRINGSIZE);
-	strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
-	strncat(filename, STANDARDELEMENTSDB, MAXSTRINGSIZE-strlen(filename));
-	infile.open(filename);
-	if (infile != NULL) {
-		infile.getline(header1, MAXSTRINGSIZE);
-		infile.getline(header2, MAXSTRINGSIZE); // skip first two header lines
-		cout <<	"Parsed elements:";
-		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;
-			infile >> ws;
-			cout << " " << neues->symbol;
-			//neues->Output((ofstream *)&cout);
-			if ((neues->Z > 0) && (neues->Z < MAX_ELEMENTS))
-				periodentafel::AddElement(neues);
-			else {
-				cout << "Could not parse element: ";
-				neues->Output((ofstream *)&cout);
-			}
-		}
-		cout << endl;
-		infile.close();
-		infile.clear();
-	} else
-		status = false;
-
-	// fill valence DB per element
-	strncpy(filename, path, MAXSTRINGSIZE);
-	strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
-	strncat(filename, STANDARDVALENCEDB, MAXSTRINGSIZE-strlen(filename));
-	infile.open(filename);
-	if (infile != NULL) {
-		while (!infile.eof()) {
-			infile >> tmp;
-			infile >> ws;
-			infile >> FindElement((int)tmp)->Valence;
-			infile >> ws;
-			//cout << Verbose(3) << "Element " << (int)tmp << " has " << FindElement((int)tmp)->Valence << " valence electrons." << endl;
-		}
-		infile.close();
-		infile.clear();
-	} else
-		otherstatus = false;
-
-	// fill valence DB per element
-	strncpy(filename, path, MAXSTRINGSIZE);
-	strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
-	strncat(filename, STANDARDORBITALDB, MAXSTRINGSIZE-strlen(filename));
-	infile.open(filename);
-	if (infile != NULL) {
-		while (!infile.eof()) {
-			infile >> tmp;
-			infile >> ws;
-			infile >> FindElement((int)tmp)->NoValenceOrbitals;
-			infile >> ws;
-			//cout << Verbose(3) << "Element " << (int)tmp << " has " << FindElement((int)tmp)->NoValenceOrbitals << " number of singly occupied valence orbitals." << endl;
-		}
-		infile.close();
-		infile.clear();
-	} else
-		otherstatus = false;
-
-	// fill H-BondDistance DB per element
-	strncpy(filename, path, MAXSTRINGSIZE);
-	strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
-	strncat(filename, STANDARDHBONDDISTANCEDB, MAXSTRINGSIZE-strlen(filename));
-	infile.open(filename);
-	if (infile != NULL) {
-		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 " << FindElement((int)tmp)->HBondDistance[0] << " Angstrom typical distance to hydrogen." << endl;
-		}
-		infile.close();
-		infile.clear();
-	} else
-		otherstatus = false;
-
-	// fill H-BondAngle DB per element
-	strncpy(filename, path, MAXSTRINGSIZE);
-	strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
-	strncat(filename, STANDARDHBONDANGLEDB, MAXSTRINGSIZE-strlen(filename));
-	infile.open(filename);
-	if (infile != NULL) {
-		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();
-	} else
-		otherstatus = false;
-
-	if (!otherstatus)
-		cerr << "WARNING: Something went wrong while parsing the other databases!" << endl;
-
-	return status;
+  ifstream infile;
+  double tmp;
+  element *ptr;
+  bool status = true;
+  bool otherstatus = true;
+  char filename[255];
+
+  // fill elements DB
+  strncpy(filename, path, MAXSTRINGSIZE);
+  strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
+  strncat(filename, STANDARDELEMENTSDB, MAXSTRINGSIZE-strlen(filename));
+  infile.open(filename);
+  if (infile != NULL) {
+    infile.getline(header1, MAXSTRINGSIZE);
+    infile.getline(header2, MAXSTRINGSIZE); // skip first two header lines
+    cout <<  "Parsed elements:";
+    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;
+      infile >> ws;
+      cout << " " << neues->symbol;
+      //neues->Output((ofstream *)&cout);
+      if ((neues->Z > 0) && (neues->Z < MAX_ELEMENTS))
+        periodentafel::AddElement(neues);
+      else {
+        cout << "Could not parse element: ";
+        neues->Output((ofstream *)&cout);
+      }
+    }
+    cout << endl;
+    infile.close();
+    infile.clear();
+  } else
+    status = false;
+
+  // fill valence DB per element
+  strncpy(filename, path, MAXSTRINGSIZE);
+  strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
+  strncat(filename, STANDARDVALENCEDB, MAXSTRINGSIZE-strlen(filename));
+  infile.open(filename);
+  if (infile != NULL) {
+    while (!infile.eof()) {
+      infile >> tmp;
+      infile >> ws;
+      infile >> FindElement((int)tmp)->Valence;
+      infile >> ws;
+      //cout << Verbose(3) << "Element " << (int)tmp << " has " << FindElement((int)tmp)->Valence << " valence electrons." << endl;
+    }
+    infile.close();
+    infile.clear();
+  } else
+    otherstatus = false;
+
+  // fill valence DB per element
+  strncpy(filename, path, MAXSTRINGSIZE);
+  strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
+  strncat(filename, STANDARDORBITALDB, MAXSTRINGSIZE-strlen(filename));
+  infile.open(filename);
+  if (infile != NULL) {
+    while (!infile.eof()) {
+      infile >> tmp;
+      infile >> ws;
+      infile >> FindElement((int)tmp)->NoValenceOrbitals;
+      infile >> ws;
+      //cout << Verbose(3) << "Element " << (int)tmp << " has " << FindElement((int)tmp)->NoValenceOrbitals << " number of singly occupied valence orbitals." << endl;
+    }
+    infile.close();
+    infile.clear();
+  } else
+    otherstatus = false;
+
+  // fill H-BondDistance DB per element
+  strncpy(filename, path, MAXSTRINGSIZE);
+  strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
+  strncat(filename, STANDARDHBONDDISTANCEDB, MAXSTRINGSIZE-strlen(filename));
+  infile.open(filename);
+  if (infile != NULL) {
+    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 " << FindElement((int)tmp)->HBondDistance[0] << " Angstrom typical distance to hydrogen." << endl;
+    }
+    infile.close();
+    infile.clear();
+  } else
+    otherstatus = false;
+
+  // fill H-BondAngle DB per element
+  strncpy(filename, path, MAXSTRINGSIZE);
+  strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
+  strncat(filename, STANDARDHBONDANGLEDB, MAXSTRINGSIZE-strlen(filename));
+  infile.open(filename);
+  if (infile != NULL) {
+    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();
+  } else
+    otherstatus = false;
+
+  if (!otherstatus)
+    cerr << "WARNING: Something went wrong while parsing the other databases!" << endl;
+
+  return status;
 };
 
@@ -303,23 +303,23 @@
 bool periodentafel::StorePeriodentafel(const char *path) const
 {
-	bool result = true;
-	ofstream f;
-	char filename[MAXSTRINGSIZE];
-
-	strncpy(filename, path, MAXSTRINGSIZE);
-	strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
-	strncat(filename, STANDARDELEMENTSDB, MAXSTRINGSIZE-strlen(filename));
-	f.open(filename);
-	if (f != NULL) {
-		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();
-	} else
-		result = false;
-	return result;
-};
+  bool result = true;
+  ofstream f;
+  char filename[MAXSTRINGSIZE];
+
+  strncpy(filename, path, MAXSTRINGSIZE);
+  strncat(filename, "/", MAXSTRINGSIZE-strlen(filename));
+  strncat(filename, STANDARDELEMENTSDB, MAXSTRINGSIZE-strlen(filename));
+  f.open(filename);
+  if (f != NULL) {
+    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();
+  } else
+    result = false;
+  return result;
+};
Index: src/periodentafel.hpp
===================================================================
--- src/periodentafel.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/periodentafel.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -21,31 +21,31 @@
  */
 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)
+  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();
+  element();
+  ~element();
 
-	//> print element entries to screen
-	bool Output(ofstream *out) const;
-	bool Checkout(ofstream *out, const int No, const int NoOfAtoms) const;
+  //> print element entries to screen
+  bool Output(ofstream *out) const;
+  bool Checkout(ofstream *out, const int No, const int NoOfAtoms) const;
 
-	private:
+  private:
 };
 
@@ -53,25 +53,25 @@
  */
 class periodentafel {
-	public:
-		element *start; //!< start of element list
-		element *end;	 //!< end of element list
-		char header1[MAXSTRINGSIZE]; //!< store first header line
-		char header2[MAXSTRINGSIZE]; //!< store second header line
+  public:
+    element *start; //!< start of element list
+    element *end;   //!< end of element list
+    char header1[MAXSTRINGSIZE]; //!< store first header line
+    char header2[MAXSTRINGSIZE]; //!< store second header line
 
-	periodentafel();
-	~periodentafel();
+  periodentafel();
+  ~periodentafel();
 
-	bool AddElement(element *pointer);
-	bool RemoveElement(element *pointer);
-	bool CleanupPeriodtable();
-	element * FindElement(int Z);
-	element * FindElement(const char *shorthand) const;
-	element * AskElement();
-	bool Output(ofstream *output) const;
-	bool Checkout(ofstream *output, const int *checkliste) const;
-	bool LoadPeriodentafel(const char *path);
-	bool StorePeriodentafel(const char *path) const;
+  bool AddElement(element *pointer);
+  bool RemoveElement(element *pointer);
+  bool CleanupPeriodtable();
+  element * FindElement(int Z);
+  element * FindElement(const char *shorthand) const;
+  element * AskElement();
+  bool Output(ofstream *output) const;
+  bool Checkout(ofstream *output, const int *checkliste) const;
+  bool LoadPeriodentafel(const char *path);
+  bool StorePeriodentafel(const char *path) const;
 
-	private:
+  private:
 };
 
Index: src/stackclass.hpp
===================================================================
--- src/stackclass.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/stackclass.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -10,25 +10,25 @@
  */
 template <typename T> class StackClass {
-	public:
-	StackClass<T>(int dimension);
-	~StackClass<T>();
-
-	bool Push(T object);
-	T PopFirst();
-	T PopLast();
-	bool RemoveItem(T ptr);
-	void ClearStack();
-	bool IsEmpty();
-	bool IsFull();
-	int ItemCount();
-	void Output(ofstream *out) const;
-	void TestImplementation(ofstream *out, T test);
-
-	private:
-		T *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
+  public:
+  StackClass<T>(int dimension);
+  ~StackClass<T>();
+
+  bool Push(T object);
+  T PopFirst();
+  T PopLast();
+  bool RemoveItem(T ptr);
+  void ClearStack();
+  bool IsEmpty();
+  bool IsFull();
+  int ItemCount();
+  void Output(ofstream *out) const;
+  void TestImplementation(ofstream *out, T test);
+
+  private:
+    T *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
 };
 
@@ -37,9 +37,9 @@
 template <typename T> StackClass<T>::StackClass(int dimension)
 {
-	CurrentLastEntry = 0;
-	CurrentFirstEntry = 0;
-	NextFreeField = 0;
-	EntryCount = dimension;
-	StackList = (T *) Malloc(sizeof(T)*EntryCount, "StackClass::StackClass: **StackList");
+  CurrentLastEntry = 0;
+  CurrentFirstEntry = 0;
+  NextFreeField = 0;
+  EntryCount = dimension;
+  StackList = (T *) Malloc(sizeof(T)*EntryCount, "StackClass::StackClass: **StackList");
 };
 
@@ -48,5 +48,5 @@
 template <typename T> StackClass<T>::~StackClass()
 {
-	Free((void **)&StackList, "StackClass::StackClass: **StackList");
+  Free((void **)&StackList, "StackClass::StackClass: **StackList");
 };
 
@@ -57,13 +57,13 @@
 template <typename T> bool StackClass<T>::Push(T 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;
-	}
+  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;
+  }
 };
 
@@ -74,19 +74,19 @@
 template <typename T> T StackClass<T>::PopFirst()
 {
-	T 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;
+  T 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;
 };
 
@@ -97,17 +97,17 @@
 template <typename T> T StackClass<T>::PopLast()
 {
-	T 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;
+  T 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;
 };
 
@@ -120,33 +120,33 @@
 template <typename T> bool StackClass<T>::RemoveItem(T 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;
+  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;
 };
 
@@ -158,40 +158,40 @@
 template <typename T> void StackClass<T>::TestImplementation(ofstream *out, T test)
 {
-	T 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;
+  T 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;
 };
 
@@ -201,16 +201,16 @@
 template <typename T> void StackClass<T>::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;
+  *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;
 };
 
@@ -222,5 +222,5 @@
 template <typename T> bool StackClass<T>::IsEmpty()
 {
-	return((NextFreeField == CurrentFirstEntry) && (CurrentLastEntry == CurrentFirstEntry));
+  return((NextFreeField == CurrentFirstEntry) && (CurrentLastEntry == CurrentFirstEntry));
 };
 
@@ -232,5 +232,5 @@
 template <typename T> bool StackClass<T>::IsFull()
 {
-	return((NextFreeField == CurrentFirstEntry) && (CurrentLastEntry != CurrentFirstEntry));
+  return((NextFreeField == CurrentFirstEntry) && (CurrentLastEntry != CurrentFirstEntry));
 };
 
@@ -242,6 +242,6 @@
 template <typename T> int StackClass<T>::ItemCount()
 {
-	//cout << "Stack: CurrentLastEntry " << CurrentLastEntry<< "\tCurrentFirstEntry " << CurrentFirstEntry << "\tEntryCount " << EntryCount << "." << endl;
-	return((NextFreeField + (EntryCount - CurrentFirstEntry)) % EntryCount);
+  //cout << "Stack: CurrentLastEntry " << CurrentLastEntry<< "\tCurrentFirstEntry " << CurrentFirstEntry << "\tEntryCount " << EntryCount << "." << endl;
+  return((NextFreeField + (EntryCount - CurrentFirstEntry)) % EntryCount);
 };
 
@@ -251,9 +251,9 @@
 template <typename T> void StackClass<T>::ClearStack()
 {
-	for(int i=EntryCount; i--;)
-		StackList[i] = NULL;
-	CurrentFirstEntry = 0;
-	CurrentLastEntry = 0;
-	NextFreeField = 0;
+  for(int i=EntryCount; i--;)
+    StackList[i] = NULL;
+  CurrentFirstEntry = 0;
+  CurrentLastEntry = 0;
+  NextFreeField = 0;
 };
 
Index: src/vector.cpp
===================================================================
--- src/vector.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/vector.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -28,8 +28,8 @@
 double Vector::DistanceSquared(const Vector *y) const
 {
-	double res = 0.;
-	for (int i=NDIM;i--;)
-		res += (x[i]-y->x[i])*(x[i]-y->x[i]);
-	return (res);
+  double res = 0.;
+  for (int i=NDIM;i--;)
+    res += (x[i]-y->x[i])*(x[i]-y->x[i]);
+  return (res);
 };
 
@@ -40,8 +40,8 @@
 double Vector::Distance(const Vector *y) const
 {
-	double res = 0.;
-	for (int i=NDIM;i--;)
-		res += (x[i]-y->x[i])*(x[i]-y->x[i]);
-	return (sqrt(res));
+  double res = 0.;
+  for (int i=NDIM;i--;)
+    res += (x[i]-y->x[i])*(x[i]-y->x[i]);
+  return (sqrt(res));
 };
 
@@ -53,33 +53,33 @@
 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=NDIM;i--;)
-					TranslationVector.x[i] = (double)N[i];
-				TranslationVector.MatrixMultiplication(matrix);
-				// add onto the original vector to compare with
-				Shiftedy.CopyVector(y);
-				Shiftedy.AddVector(&TranslationVector);
-				// get distance and compare with minimum so far
-				tmp = Distance(&Shiftedy);
-				if (tmp < res) res = tmp;
-			}
-	return (res);
+  double res = Distance(y), tmp, matrix[NDIM*NDIM];
+  Vector Shiftedy, TranslationVector;
+  int N[NDIM];
+  matrix[0] = cell_size[0];
+  matrix[1] = cell_size[1];
+  matrix[2] = cell_size[3];
+  matrix[3] = cell_size[1];
+  matrix[4] = cell_size[2];
+  matrix[5] = cell_size[4];
+  matrix[6] = cell_size[3];
+  matrix[7] = cell_size[4];
+  matrix[8] = cell_size[5];
+  // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
+  for (N[0]=-1;N[0]<=1;N[0]++)
+    for (N[1]=-1;N[1]<=1;N[1]++)
+      for (N[2]=-1;N[2]<=1;N[2]++) {
+        // create the translation vector
+        TranslationVector.Zero();
+        for (int i=NDIM;i--;)
+          TranslationVector.x[i] = (double)N[i];
+        TranslationVector.MatrixMultiplication(matrix);
+        // add onto the original vector to compare with
+        Shiftedy.CopyVector(y);
+        Shiftedy.AddVector(&TranslationVector);
+        // get distance and compare with minimum so far
+        tmp = Distance(&Shiftedy);
+        if (tmp < res) res = tmp;
+      }
+  return (res);
 };
 
@@ -91,33 +91,33 @@
 double Vector::PeriodicDistanceSquared(const Vector *y, const double *cell_size) const
 {
-	double res = DistanceSquared(y), tmp, matrix[NDIM*NDIM];
-	Vector Shiftedy, TranslationVector;
-	int N[NDIM];
-	matrix[0] = cell_size[0];
-	matrix[1] = cell_size[1];
-	matrix[2] = cell_size[3];
-	matrix[3] = cell_size[1];
-	matrix[4] = cell_size[2];
-	matrix[5] = cell_size[4];
-	matrix[6] = cell_size[3];
-	matrix[7] = cell_size[4];
-	matrix[8] = cell_size[5];
-	// in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
-	for (N[0]=-1;N[0]<=1;N[0]++)
-		for (N[1]=-1;N[1]<=1;N[1]++)
-			for (N[2]=-1;N[2]<=1;N[2]++) {
-				// create the translation vector
-				TranslationVector.Zero();
-				for (int i=NDIM;i--;)
-					TranslationVector.x[i] = (double)N[i];
-				TranslationVector.MatrixMultiplication(matrix);
-				// add onto the original vector to compare with
-				Shiftedy.CopyVector(y);
-				Shiftedy.AddVector(&TranslationVector);
-				// get distance and compare with minimum so far
-				tmp = DistanceSquared(&Shiftedy);
-				if (tmp < res) res = tmp;
-			}
-	return (res);
+  double res = DistanceSquared(y), tmp, matrix[NDIM*NDIM];
+  Vector Shiftedy, TranslationVector;
+  int N[NDIM];
+  matrix[0] = cell_size[0];
+  matrix[1] = cell_size[1];
+  matrix[2] = cell_size[3];
+  matrix[3] = cell_size[1];
+  matrix[4] = cell_size[2];
+  matrix[5] = cell_size[4];
+  matrix[6] = cell_size[3];
+  matrix[7] = cell_size[4];
+  matrix[8] = cell_size[5];
+  // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
+  for (N[0]=-1;N[0]<=1;N[0]++)
+    for (N[1]=-1;N[1]<=1;N[1]++)
+      for (N[2]=-1;N[2]<=1;N[2]++) {
+        // create the translation vector
+        TranslationVector.Zero();
+        for (int i=NDIM;i--;)
+          TranslationVector.x[i] = (double)N[i];
+        TranslationVector.MatrixMultiplication(matrix);
+        // add onto the original vector to compare with
+        Shiftedy.CopyVector(y);
+        Shiftedy.AddVector(&TranslationVector);
+        // get distance and compare with minimum so far
+        tmp = DistanceSquared(&Shiftedy);
+        if (tmp < res) res = tmp;
+      }
+  return (res);
 };
 
@@ -128,27 +128,27 @@
 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=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;
+//  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=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;
 };
 
@@ -159,24 +159,24 @@
 double Vector::ScalarProduct(const Vector *y) const
 {
-	double res = 0.;
-	for (int i=NDIM;i--;)
-		res += x[i]*y->x[i];
-	return (res);
+  double res = 0.;
+  for (int i=NDIM;i--;)
+    res += x[i]*y->x[i];
+  return (res);
 };
 
 
 /** Calculates VectorProduct between this and another vector.
- *	-# returns the Product in place of vector from which it was initiated
- *	-# ATTENTION: Only three dim.
- *	\param *y array to vector with which to calculate crossproduct
- *	\return \f$ x \times y \f&
+ *  -# returns the Product in place of vector from which it was initiated
+ *  -# ATTENTION: Only three dim.
+ *  \param *y array to vector with which to calculate crossproduct
+ *  \return \f$ x \times y \f&
  */
 void Vector::VectorProduct(const Vector *y)
 {
-	Vector tmp;
-	tmp.x[0] = x[1]* (y->x[2]) - x[2]* (y->x[1]);
-	tmp.x[1] = x[2]* (y->x[0]) - x[0]* (y->x[2]);
-	tmp.x[2] = x[0]* (y->x[1]) - x[1]* (y->x[0]);
-	this->CopyVector(&tmp);
+  Vector tmp;
+  tmp.x[0] = x[1]* (y->x[2]) - x[2]* (y->x[1]);
+  tmp.x[1] = x[2]* (y->x[0]) - x[0]* (y->x[2]);
+  tmp.x[2] = x[0]* (y->x[1]) - x[1]* (y->x[0]);
+  this->CopyVector(&tmp);
 
 };
@@ -189,9 +189,96 @@
 void Vector::ProjectOntoPlane(const Vector *y)
 {
-	Vector tmp;
-	tmp.CopyVector(y);
-	tmp.Normalize();
-	tmp.Scale(ScalarProduct(&tmp));
-	this->SubtractVector(&tmp);
+  Vector tmp;
+  tmp.CopyVector(y);
+  tmp.Normalize();
+  tmp.Scale(ScalarProduct(&tmp));
+  this->SubtractVector(&tmp);
+};
+
+/** Calculates the intersection point between a line defined by \a *LineVector and \a *LineVector2 and a plane defined by \a *Normal and \a *PlaneOffset.
+ * According to [Bronstein] the vectorial plane equation is:
+ *   -# \f$\stackrel{r}{\rightarrow} \cdot \stackrel{N}{\rightarrow} + D = 0\f$,
+ * where \f$\stackrel{r}{\rightarrow}\f$ is the vector to be testet, \f$\stackrel{N}{\rightarrow}\f$ is the plane's normal vector and
+ * \f$D = - \stackrel{a}{\rightarrow} \stackrel{N}{\rightarrow}\f$, the offset with respect to origin, if \f$\stackrel{a}{\rightarrow}\f$,
+ * is an offset vector onto the plane. The line is parametrized by \f$\stackrel{x}{\rightarrow} + k \stackrel{t}{\rightarrow}\f$, where
+ * \f$\stackrel{x}{\rightarrow}\f$ is the offset and \f$\stackrel{t}{\rightarrow}\f$ the directional vector (NOTE: No need to normalize
+ * the latter). Inserting the parametrized form into the plane equation and solving for \f$k\f$, which we insert then into the parametrization
+ * of the line yields the intersection point on the plane.
+ * \param *out output stream for debugging
+ * \param *PlaneNormal Plane's normal vector
+ * \param *PlaneOffset Plane's offset vector
+ * \param *LineVector first vector of line
+ * \param *LineVector2 second vector of line
+ * \return true -  \a this contains intersection point on return, false - line is parallel to plane
+ */
+bool Vector::GetIntersectionWithPlane(ofstream *out, Vector *PlaneNormal, Vector *PlaneOffset, Vector *LineVector, Vector *LineVector2)
+{
+  double factor;
+  Vector Direction;
+
+  // find intersection of a line defined by Offset and Direction with a  plane defined by triangle
+  Direction.CopyVector(LineVector2);
+  Direction.SubtractVector(LineVector);
+  if (Direction.ScalarProduct(PlaneNormal) < MYEPSILON)
+    return false;
+  factor = LineVector->ScalarProduct(PlaneNormal)*(-PlaneOffset->ScalarProduct(PlaneNormal))/(Direction.ScalarProduct(PlaneNormal));
+  Direction.Scale(factor);
+  CopyVector(LineVector);
+  SubtractVector(&Direction);
+
+  // test whether resulting vector really is on plane
+  Direction.CopyVector(this);
+  Direction.SubtractVector(PlaneOffset);
+  if (Direction.ScalarProduct(PlaneNormal) > MYEPSILON)
+    return true;
+  else
+    return false;
+};
+
+/** Calculates the intersection of the two lines that are both on the same plane.
+ * Note that we do not check whether they are on the same plane.
+ * \param *out output stream for debugging
+ * \param *Line1a first vector of first line
+ * \param *Line1b second vector of first line
+ * \param *Line2a first vector of second line
+ * \param *Line2b second vector of second line
+ * \return true - \a this will contain the intersection on return, false - lines are parallel
+ */
+bool Vector::GetIntersectionOfTwoLinesOnPlane(ofstream *out, Vector *Line1a, Vector *Line1b, Vector *Line2a, Vector *Line2b)
+{
+  double k1,a1,h1,b1,k2,a2,h2,b2;
+  // equation for line 1
+  if (fabs(Line1a->x[0] - Line2a->x[0]) < MYEPSILON) {
+    k1 = 0;
+    h1 = 0;
+  } else {
+    k1 = (Line1a->x[1] - Line2a->x[1])/(Line1a->x[0] - Line2a->x[0]);
+    h1 = (Line1a->x[2] - Line2a->x[2])/(Line1a->x[0] - Line2a->x[0]);
+  }
+  a1 = 0.5*((Line1a->x[1] + Line2a->x[1]) - k1*(Line1a->x[0] + Line2a->x[0]));
+  b1 = 0.5*((Line1a->x[2] + Line2a->x[2]) - h1*(Line1a->x[0] + Line2a->x[0]));
+
+  // equation for line 2
+  if (fabs(Line2a->x[0] - Line2a->x[0]) < MYEPSILON) {
+    k1 = 0;
+    h1 = 0;
+  } else {
+    k1 = (Line2a->x[1] - Line2a->x[1])/(Line2a->x[0] - Line2a->x[0]);
+    h1 = (Line2a->x[2] - Line2a->x[2])/(Line2a->x[0] - Line2a->x[0]);
+  }
+  a1 = 0.5*((Line2a->x[1] + Line2a->x[1]) - k1*(Line2a->x[0] + Line2a->x[0]));
+  b1 = 0.5*((Line2a->x[2] + Line2a->x[2]) - h1*(Line2a->x[0] + Line2a->x[0]));
+
+  // calculate cross point
+  if (fabs((a1-a2)*(h1-h2) - (b1-b2)*(k1-k2)) < MYEPSILON) {
+    x[0] = (a2-a1)/(k1-k2);
+    x[1] = (k1*a2-k2*a1)/(k1-k2);
+    x[2] = (h1*b2-h2*b1)/(h1-h2);
+    *out << Verbose(4) << "Lines do intersect at " << this << "." << endl;
+    return true;
+  } else {
+    *out << Verbose(4) << "Lines do not intersect." << endl;
+    return false;
+  }
 };
 
@@ -202,5 +289,5 @@
 double Vector::Projection(const Vector *y) const
 {
-	return (ScalarProduct(y));
+  return (ScalarProduct(y));
 };
 
@@ -210,8 +297,16 @@
 double Vector::Norm() const
 {
-	double res = 0.;
-	for (int i=NDIM;i--;)
-		res += this->x[i]*this->x[i];
-	return (sqrt(res));
+  double res = 0.;
+  for (int i=NDIM;i--;)
+    res += this->x[i]*this->x[i];
+  return (sqrt(res));
+};
+
+/** Calculates squared norm of this vector.
+ * \return \f$|x|^2\f$
+ */
+double Vector::NormSquared() const
+{
+  return (ScalarProduct(this));
 };
 
@@ -220,10 +315,10 @@
 void Vector::Normalize()
 {
-	double res = 0.;
-	for (int i=NDIM;i--;)
-		res += this->x[i]*this->x[i];
-	if (fabs(res) > MYEPSILON)
-		res = 1./sqrt(res);
-	Scale(&res);
+  double res = 0.;
+  for (int i=NDIM;i--;)
+    res += this->x[i]*this->x[i];
+  if (fabs(res) > MYEPSILON)
+    res = 1./sqrt(res);
+  Scale(&res);
 };
 
@@ -232,6 +327,6 @@
 void Vector::Zero()
 {
-	for (int i=NDIM;i--;)
-		this->x[i] = 0.;
+  for (int i=NDIM;i--;)
+    this->x[i] = 0.;
 };
 
@@ -240,6 +335,6 @@
 void Vector::One(double one)
 {
-	for (int i=NDIM;i--;)
-		this->x[i] = one;
+  for (int i=NDIM;i--;)
+    this->x[i] = one;
 };
 
@@ -248,7 +343,7 @@
 void Vector::Init(double x1, double x2, double x3)
 {
-	x[0] = x1;
-	x[1] = x2;
-	x[2] = x3;
+  x[0] = x1;
+  x[1] = x2;
+  x[2] = x3;
 };
 
@@ -267,5 +362,8 @@
 double Vector::Angle(const Vector *y) const
 {
-  double angle = this->ScalarProduct(y)/Norm()/y->Norm();
+  double norm1 = Norm(), norm2 = y->Norm();
+  double angle = 1;
+  if ((fabs(norm1) > MYEPSILON) && (fabs(norm2) > MYEPSILON))
+    angle = this->ScalarProduct(y)/norm1/norm2;
   // -1-MYEPSILON occured due to numerical imprecision, catch ...
   //cout << Verbose(2) << "INFO: acos(-1) = " << acos(-1) << ", acos(-1+MYEPSILON) = " << acos(-1+MYEPSILON) << ", acos(-1-MYEPSILON) = " << acos(-1-MYEPSILON) << "." << endl;
@@ -274,5 +372,5 @@
   if (angle > 1)
     angle = 1;
-	return acos(angle);
+  return acos(angle);
 };
 
@@ -283,19 +381,19 @@
 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);
+  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);
 };
 
@@ -307,6 +405,6 @@
 Vector& operator+=(Vector& a, const Vector& b)
 {
-	a.AddVector(&b);
-	return a;
+  a.AddVector(&b);
+  return a;
 };
 /** factor each component of \a a times a double \a m.
@@ -317,9 +415,9 @@
 Vector& operator*=(Vector& a, const double m)
 {
-	a.Scale(m);
-	return a;
-};
-
-/** Sums two vectors \a	and \b component-wise.
+  a.Scale(m);
+  return a;
+};
+
+/** Sums two vectors \a  and \b component-wise.
  * \param a first vector
  * \param b second vector
@@ -328,8 +426,8 @@
 Vector& operator+(const Vector& a, const Vector& b)
 {
-	Vector *x = new Vector;
-	x->CopyVector(&a);
-	x->AddVector(&b);
-	return *x;
+  Vector *x = new Vector;
+  x->CopyVector(&a);
+  x->AddVector(&b);
+  return *x;
 };
 
@@ -341,8 +439,8 @@
 Vector& operator*(const Vector& a, const double m)
 {
-	Vector *x = new Vector;
-	x->CopyVector(&a);
-	x->Scale(m);
-	return *x;
+  Vector *x = new Vector;
+  x->CopyVector(&a);
+  x->Scale(m);
+  return *x;
 };
 
@@ -353,27 +451,27 @@
 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;
+  if (out != NULL) {
+    *out << "(";
+    for (int i=0;i<NDIM;i++) {
+      *out << x[i];
+      if (i != 2)
+        *out << ",";
+    }
+    *out << ")";
+    return true;
+  } else
+    return false;
 };
 
 ostream& operator<<(ostream& ost, const Vector& m)
 {
-	ost << "(";
-	for (int i=0;i<NDIM;i++) {
-		ost << m.x[i];
-		if (i != 2)
-			ost << ",";
-	}
-	ost << ")";
-	return ost;
+  ost << "(";
+  for (int i=0;i<NDIM;i++) {
+    ost << m.x[i];
+    if (i != 2)
+      ost << ",";
+  }
+  ost << ")";
+  return ost;
 };
 
@@ -383,18 +481,18 @@
 void Vector::Scale(double **factor)
 {
-	for (int i=NDIM;i--;)
-		x[i] *= (*factor)[i];
+  for (int i=NDIM;i--;)
+    x[i] *= (*factor)[i];
 };
 
 void Vector::Scale(double *factor)
 {
-	for (int i=NDIM;i--;)
-		x[i] *= *factor;
+  for (int i=NDIM;i--;)
+    x[i] *= *factor;
 };
 
 void Vector::Scale(double factor)
 {
-	for (int i=NDIM;i--;)
-		x[i] *= factor;
+  for (int i=NDIM;i--;)
+    x[i] *= factor;
 };
 
@@ -404,6 +502,6 @@
 void Vector::Translate(const Vector *trans)
 {
-	for (int i=NDIM;i--;)
-		x[i] += trans->x[i];
+  for (int i=NDIM;i--;)
+    x[i] += trans->x[i];
 };
 
@@ -413,47 +511,74 @@
 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=NDIM;i--;)
-		x[i] = C.x[i];
-};
-
-/** Do a matrix multiplication with \a *matrix' inverse.
+  Vector C;
+  // do the matrix multiplication
+  C.x[0] = M[0]*x[0]+M[3]*x[1]+M[6]*x[2];
+  C.x[1] = M[1]*x[0]+M[4]*x[1]+M[7]*x[2];
+  C.x[2] = M[2]*x[0]+M[5]*x[1]+M[8]*x[2];
+  // transfer the result into this
+  for (int i=NDIM;i--;)
+    x[i] = C.x[i];
+};
+
+/** Calculate the inverse of a 3x3 matrix.
  * \param *matrix NDIM_NDIM array
  */
+double * Vector::InverseMatrix(double *A)
+{
+  double *B = (double *) Malloc(sizeof(double)*NDIM*NDIM, "Vector::InverseMatrix: *B");
+  double detA = RDET3(A);
+  double detAReci;
+
+  for (int i=0;i<NDIM*NDIM;++i)
+    B[i] = 0.;
+  // 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
+  }
+  return B;
+};
+
+/** Do a matrix multiplication with the \a *A' 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=NDIM;i--;)
-			x[i] = C.x[i];
-	} else {
-		cerr << "ERROR: inverse of matrix does not exists!" << endl;
-	}
+  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=NDIM;i--;)
+      x[i] = C.x[i];
+  } else {
+    cerr << "ERROR: inverse of matrix does not exists: det A = " << detA << "." << endl;
+  }
 };
 
@@ -468,6 +593,6 @@
 void Vector::LinearCombinationOfVectors(const Vector *x1, const Vector *x2, const Vector *x3, double *factors)
 {
-	for(int i=NDIM;i--;)
-		x[i] = factors[0]*x1->x[i] + factors[1]*x2->x[i] + factors[2]*x3->x[i];
+  for(int i=NDIM;i--;)
+    x[i] = factors[0]*x1->x[i] + factors[1]*x2->x[i] + factors[2]*x3->x[i];
 };
 
@@ -477,15 +602,15 @@
 void Vector::Mirror(const Vector *n)
 {
-	double projection;
-	projection = ScalarProduct(n)/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=NDIM;i--;)
-		x[i] -= 2.*projection*n->x[i];
-	cout << "Projected vector: ";
-	Output((ofstream *)&cout);
-	cout << endl;
+  double projection;
+  projection = ScalarProduct(n)/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=NDIM;i--;)
+    x[i] -= 2.*projection*n->x[i];
+  cout << "Projected vector: ";
+  Output((ofstream *)&cout);
+  cout << endl;
 };
 
@@ -499,27 +624,27 @@
 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 ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
-		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;
+  Vector x1, x2;
+
+  x1.CopyVector(y1);
+  x1.SubtractVector(y2);
+  x2.CopyVector(y3);
+  x2.SubtractVector(y2);
+  if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
+    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;
 };
 
@@ -535,25 +660,25 @@
 bool Vector::MakeNormalVector(const Vector *y1, const Vector *y2)
 {
-	Vector x1,x2;
-	x1.CopyVector(y1);
-	x2.CopyVector(y2);
-	Zero();
-	if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
-		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;
+  Vector x1,x2;
+  x1.CopyVector(y1);
+  x2.CopyVector(y2);
+  Zero();
+  if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
+    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;
 };
 
@@ -565,13 +690,13 @@
 bool Vector::MakeNormalVector(const Vector *y1)
 {
-	bool result = false;
-	Vector x1;
-	x1.CopyVector(y1);
-	x1.Scale(x1.Projection(this));
-	SubtractVector(&x1);
-	for (int i=NDIM;i--;)
-		result = result || (fabs(x[i]) > MYEPSILON);
-
-	return result;
+  bool result = false;
+  Vector x1;
+  x1.CopyVector(y1);
+  x1.Scale(x1.Projection(this));
+  SubtractVector(&x1);
+  for (int i=NDIM;i--;)
+    result = result || (fabs(x[i]) > MYEPSILON);
+
+  return result;
 };
 
@@ -584,40 +709,40 @@
 bool Vector::GetOneNormalVector(const Vector *GivenVector)
 {
-	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);
-	GivenVector->Output((ofstream *)&cout);
-	cout << endl;
-	for (j=NDIM;j--;)
-		Components[j] = -1;
-	// find two components != 0
-	for (j=0;j<NDIM;j++)
-		if (fabs(GivenVector->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./(GivenVector->x[Components[1]]*GivenVector->x[Components[1]]) + 1./(GivenVector->x[Components[0]]*GivenVector->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./GivenVector->x[Components[1]] / norm;
-			x[Components[0]] = 1./GivenVector->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;
-	}
+  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);
+  GivenVector->Output((ofstream *)&cout);
+  cout << endl;
+  for (j=NDIM;j--;)
+    Components[j] = -1;
+  // find two components != 0
+  for (j=0;j<NDIM;j++)
+    if (fabs(GivenVector->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./(GivenVector->x[Components[1]]*GivenVector->x[Components[1]]) + 1./(GivenVector->x[Components[0]]*GivenVector->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./GivenVector->x[Components[1]] / norm;
+      x[Components[0]] = 1./GivenVector->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;
+  }
 };
 
@@ -630,10 +755,10 @@
 double Vector::CutsPlaneAt(Vector *A, Vector *B, Vector *C)
 {
-//	cout << Verbose(3) << "For comparison: ";
-//	cout << "A " << A->Projection(this) << "\t";
-//	cout << "B " << B->Projection(this) << "\t";
-//	cout << "C " << C->Projection(this) << "\t";
-//	cout << endl;
-	return A->Projection(this);
+//  cout << Verbose(3) << "For comparison: ";
+//  cout << "A " << A->Projection(this) << "\t";
+//  cout << "B " << B->Projection(this) << "\t";
+//  cout << "C " << C->Projection(this) << "\t";
+//  cout << endl;
+  return A->Projection(this);
 };
 
@@ -645,79 +770,79 @@
 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, *y;
-	 gsl_multimin_function minex_func;
-
-	 size_t iter = 0, i;
-	 int status;
-	 double size;
-
-	 /* Initial vertex size vector */
-	 ss = gsl_vector_alloc (np);
-	 y = gsl_vector_alloc (np);
-
-	 /* Set all step sizes to 1 */
-	 gsl_vector_set_all (ss, 1.0);
-
-	 /* Starting point */
-	 par.vectors = vectors;
-	 par.num = num;
-
-	 for (i=NDIM;i--;)
-		gsl_vector_set(y, i, (vectors[0]->x[i] - vectors[1]->x[i])/2.);
-
-	 /* Initialize method and iterate */
-	 minex_func.f = &LSQ;
-	 minex_func.n = np;
-	 minex_func.params = (void *)&par;
-
-	 s = gsl_multimin_fminimizer_alloc (T, np);
-	 gsl_multimin_fminimizer_set (s, &minex_func, y, ss);
-
-	 do
-		 {
-			 iter++;
-			 status = gsl_multimin_fminimizer_iterate(s);
-
-			 if (status)
-				 break;
-
-			 size = gsl_multimin_fminimizer_size (s);
-			 status = gsl_multimin_test_size (size, 1e-2);
-
-			 if (status == GSL_SUCCESS)
-				 {
-					 printf ("converged to minimum at\n");
-				 }
-
-			 printf ("%5d ", (int)iter);
-			 for (i = 0; i < (size_t)np; i++)
-				 {
-					 printf ("%10.3e ", gsl_vector_get (s->x, i));
-				 }
-			 printf ("f() = %7.3f size = %.3f\n", s->fval, size);
-		 }
-	 while (status == GSL_CONTINUE && iter < 100);
-
-	for (i=(size_t)np;i--;)
-		this->x[i] = gsl_vector_get(s->x, i);
-	 gsl_vector_free(y);
-	 gsl_vector_free(ss);
-	 gsl_multimin_fminimizer_free (s);
-
-	return true;
+  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, *y;
+   gsl_multimin_function minex_func;
+
+   size_t iter = 0, i;
+   int status;
+   double size;
+
+   /* Initial vertex size vector */
+   ss = gsl_vector_alloc (np);
+   y = gsl_vector_alloc (np);
+
+   /* Set all step sizes to 1 */
+   gsl_vector_set_all (ss, 1.0);
+
+   /* Starting point */
+   par.vectors = vectors;
+   par.num = num;
+
+   for (i=NDIM;i--;)
+    gsl_vector_set(y, i, (vectors[0]->x[i] - vectors[1]->x[i])/2.);
+
+   /* Initialize method and iterate */
+   minex_func.f = &LSQ;
+   minex_func.n = np;
+   minex_func.params = (void *)&par;
+
+   s = gsl_multimin_fminimizer_alloc (T, np);
+   gsl_multimin_fminimizer_set (s, &minex_func, y, ss);
+
+   do
+     {
+       iter++;
+       status = gsl_multimin_fminimizer_iterate(s);
+
+       if (status)
+         break;
+
+       size = gsl_multimin_fminimizer_size (s);
+       status = gsl_multimin_test_size (size, 1e-2);
+
+       if (status == GSL_SUCCESS)
+         {
+           printf ("converged to minimum at\n");
+         }
+
+       printf ("%5d ", (int)iter);
+       for (i = 0; i < (size_t)np; i++)
+         {
+           printf ("%10.3e ", gsl_vector_get (s->x, i));
+         }
+       printf ("f() = %7.3f size = %.3f\n", s->fval, size);
+     }
+   while (status == GSL_CONTINUE && iter < 100);
+
+  for (i=(size_t)np;i--;)
+    this->x[i] = gsl_vector_get(s->x, i);
+   gsl_vector_free(y);
+   gsl_vector_free(ss);
+   gsl_multimin_fminimizer_free (s);
+
+  return true;
 };
 
@@ -727,6 +852,6 @@
 void Vector::AddVector(const Vector *y)
 {
-	for (int i=NDIM;i--;)
-		this->x[i] += y->x[i];
+  for (int i=NDIM;i--;)
+    this->x[i] += y->x[i];
 }
 
@@ -736,6 +861,6 @@
 void Vector::SubtractVector(const Vector *y)
 {
-	for (int i=NDIM;i--;)
-		this->x[i] -= y->x[i];
+  for (int i=NDIM;i--;)
+    this->x[i] -= y->x[i];
 }
 
@@ -745,6 +870,6 @@
 void Vector::CopyVector(const Vector *y)
 {
-	for (int i=NDIM;i--;)
-		this->x[i] = y->x[i];
+  for (int i=NDIM;i--;)
+    this->x[i] = y->x[i];
 }
 
@@ -756,13 +881,13 @@
 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));
-	}
+  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));
+  }
 };
 
@@ -784,155 +909,155 @@
 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=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=NDIM;j--;)
-			x[j] *= sign[j];
-	}
-	return true;
-};
+  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=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=NDIM;j--;)
+      x[j] *= sign[j];
+  }
+  return true;
+};
Index: src/vector.hpp
===================================================================
--- src/vector.hpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/vector.hpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -8,50 +8,53 @@
  */
 class Vector {
-	public:
-		double x[NDIM];
+  public:
+    double x[NDIM];
 
-	Vector();
-	Vector(double x1, double x2, double x3);
-	~Vector();
+  Vector();
+  Vector(double x1, double x2, double x3);
+  ~Vector();
 
-	double Distance(const Vector *y) const;
-	double DistanceSquared(const Vector *y) const;
-	double PeriodicDistance(const Vector *y, const double *cell_size) const;
-	double PeriodicDistanceSquared(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(const Vector *y) const;
-	bool IsNull();
+  double Distance(const Vector *y) const;
+  double DistanceSquared(const Vector *y) const;
+  double PeriodicDistance(const Vector *y, const double *cell_size) const;
+  double PeriodicDistanceSquared(const Vector *y, const double *cell_size) const;
+  double ScalarProduct(const Vector *y) const;
+  double Projection(const Vector *y) const;
+  double Norm() const;
+  double NormSquared() const;
+  double Angle(const Vector *y) const;
+  bool IsNull();
 
-
-	void AddVector(const Vector *y);
-	void SubtractVector(const Vector *y);
-	void CopyVector(const Vector *y);
-	void RotateVector(const Vector *y, const double alpha);
-	void VectorProduct(const Vector *y);
-	void ProjectOntoPlane(const Vector *y);
-	void Zero();
-	void One(double one);
-	void Init(double x1, double x2, double x3);
-	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);
-	double CutsPlaneAt(Vector *A, Vector *B, Vector *C);
-	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;
+  void AddVector(const Vector *y);
+  void SubtractVector(const Vector *y);
+  void CopyVector(const Vector *y);
+  void RotateVector(const Vector *y, const double alpha);
+  void VectorProduct(const Vector *y);
+  void ProjectOntoPlane(const Vector *y);
+  void Zero();
+  void One(double one);
+  void Init(double x1, double x2, double x3);
+  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);
+  double * InverseMatrix(double *A);
+  void InverseMatrixMultiplication(double *M);
+  void KeepPeriodic(ofstream *out, double *matrix);
+  void LinearCombinationOfVectors(const Vector *x1, const Vector *x2, const Vector *x3, double *factors);
+  double CutsPlaneAt(Vector *A, Vector *B, Vector *C);
+  bool GetIntersectionWithPlane(ofstream *out, Vector *PlaneNormal, Vector *PlaneOffset, Vector *LineVector, Vector *LineVector2);
+  bool GetIntersectionOfTwoLinesOnPlane(ofstream *out, Vector *Line1a, Vector *Line1b, Vector *Line2a, Vector *Line2b);
+  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;
 };
 
Index: src/verbose.cpp
===================================================================
--- src/verbose.cpp	(revision 8c54a3b5f6bdf770309a91dff75fb62f47d91b6d)
+++ src/verbose.cpp	(revision 0dbddc24a89f547aa564634e7647f87ec8ce9700)
@@ -7,8 +7,8 @@
 ostream& Verbose::print (ostream &ost) const
 {
-	for (int i=Verbosity;i--;)
-		ost.put('\t');
-	//cout << "Verbose(.) called." << endl;
-	return ost;
+  for (int i=Verbosity;i--;)
+    ost.put('\t');
+  //cout << "Verbose(.) called." << endl;
+  return ost;
 };
 
@@ -22,5 +22,5 @@
 ostream& operator<<(ostream& ost,const Verbose& m)
 {
-	return m.print(ost);
+  return m.print(ost);
 };
 
@@ -33,16 +33,16 @@
 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;
+  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;
 };
 
@@ -56,4 +56,4 @@
 ostream& operator<<(ostream& ost,const Binary& m)
 {
-	return m.print(ost);
+  return m.print(ost);
 };
