Index: src/Fragmentation/Exporters/ExportGraph_ToFiles.cpp
===================================================================
--- src/Fragmentation/Exporters/ExportGraph_ToFiles.cpp	(revision de0af277f13a3ac53d2d96963e46ad3c1326ef1f)
+++ src/Fragmentation/Exporters/ExportGraph_ToFiles.cpp	(revision ca8bea22ad6c12313c02f7a53946becdc3eff35a)
@@ -37,8 +37,15 @@
 #include "ExportGraph_ToFiles.hpp"
 
+#include "CodePatterns/Info.hpp"
 #include "CodePatterns/Log.hpp"
+
+#include "Bond/bond.hpp"
+#include "Element/element.hpp"
 #include "Fragmentation/Graph.hpp"
 #include "Fragmentation/KeySet.hpp"
+#include "Graph/ListOfLocalAtoms.hpp"
+#include "molecule.hpp"
 #include "MoleculeListClass.hpp"
+#include "Parser/FormatParserStorage.hpp"
 #include "World.hpp"
 
@@ -46,14 +53,76 @@
  *
  * @param _graph instance of Graph containing keyset of each fragment
- */
-ExportGraph_ToFiles::ExportGraph_ToFiles(const Graph &_graph) :
-		ExportGraph(_graph)
+ * @param _mol molecule as reference
+ */
+ExportGraph_ToFiles::ExportGraph_ToFiles(const Graph &_graph, molecule *&_mol, const enum HydrogenSaturation _saturation) :
+		ExportGraph(_graph),
+		mol(_mol),
+		BondFragments(World::getPointer()),
+		saturation(_saturation)
 {}
 
+/** Destructor of class ExportGraph_ToFiles.
+ *
+ * We free all created molecules again and also removed their copied atoms.
+ */
+ExportGraph_ToFiles::~ExportGraph_ToFiles()
+{
+  // remove all create molecules again from the World including their atoms
+  for (MoleculeList::iterator iter = BondFragments.ListOfMolecules.begin();
+      !BondFragments.ListOfMolecules.empty();
+      iter = BondFragments.ListOfMolecules.begin()) {
+    // remove copied atoms and molecule again
+    molecule *mol = *iter;
+    mol->removeAtomsinMolecule();
+    World::getInstance().destroyMolecule(mol);
+    BondFragments.ListOfMolecules.erase(iter);
+  }
+}
+
 /** Actual implementation of the export to files function.
- *
- */
-void ExportGraph_ToFiles::operator ()()
-{
+ */
+void ExportGraph_ToFiles::operator()()
+{
+  if (BondFragments.ListOfMolecules.size() == 0)
+    prepareMolecule();
+
+  // ===== 9. Save fragments' configuration and keyset files et al to disk ===
+  // create the SortIndex from BFS labels to order in the config file
+  std::map<atomId_t, int> SortIndex;
+  CreateMappingLabelsToConfigSequence(SortIndex);
+
+  LOG(1, "Writing " << BondFragments.ListOfMolecules.size() << " possible bond fragmentation configs");
+  bool write_status = true;
+  for (std::vector<std::string>::const_iterator iter = typelist.begin();
+      iter != typelist.end();
+      ++iter) {
+    LOG(2, "INFO: Writing bond fragments for type " << (*iter) << ".");
+    write_status = write_status
+    && BondFragments.OutputConfigForListOfFragments(
+        prefix,
+        FormatParserStorage::getInstance().getTypeFromName(*iter));
+  }
+  if (write_status)
+    LOG(1, "All configs written.");
+  else
+    LOG(1, "Some config writing failed.");
+
+  // store force index reference file
+  BondFragments.StoreForcesFile(prefix, SortIndex);
+
+  // store keysets file
+  TotalGraph.StoreKeySetFile(prefix);
+
+  {
+    // store Adjacency file
+    std::string filename = prefix + ADJACENCYFILE;
+    mol->StoreAdjacencyToFile(filename);
+  }
+
+  // store Hydrogen saturation correction file
+  BondFragments.AddHydrogenCorrection(prefix);
+
+  // restore orbital and Stop values
+  //CalculateOrbitals(*configuration);
 }
 
@@ -63,15 +132,149 @@
 void ExportGraph_ToFiles::prepareMolecule()
 {
-  // allocate memory for the pointer array and transmorph graphs into full molecular fragments
-  MoleculeListClass *BondFragments = new MoleculeListClass(World::getPointer());
   size_t count = 0;
-  for(Graph::iterator runner = TotalGraph.begin(); runner != TotalGraph.end(); runner++) {
+  for(Graph::const_iterator runner = TotalGraph.begin(); runner != TotalGraph.end(); runner++) {
     KeySet test = (*runner).first;
     LOG(2, "DEBUG: Fragment No." << (*runner).second.first << " with TEFactor "
     		<< (*runner).second.second << ".");
-    BondFragments->insert(StoreFragmentFromKeySet(test, World::getInstance().getConfig()));
+    BondFragments.insert(StoreFragmentFromKeySet(mol, test, World::getInstance().getConfig()));
     ++count;
   }
-  LOG(1, "INFO: " << count << "/" << BondFragments->ListOfMolecules.size()
+  LOG(1, "INFO: " << count << "/" << BondFragments.ListOfMolecules.size()
   		<< " fragments generated from the keysets.");
 }
+
+/** Stores a fragment from \a KeySet into \a molecule.
+ * First creates the minimal set of atoms from the KeySet, then creates the bond structure from the complete
+ * molecule and adds missing hydrogen where bonds were cut.
+ * \param *mol reference molecule
+ * \param &Leaflet pointer to KeySet structure
+ * \param IsAngstroem whether we have Ansgtroem or bohrradius
+ * \return pointer to constructed molecule
+ */
+molecule * ExportGraph_ToFiles::StoreFragmentFromKeySet(molecule *mol, KeySet &Leaflet, bool IsAngstroem)
+{
+  Info info(__func__);
+  ListOfLocalAtoms_t SonList;
+  molecule *Leaf = World::getInstance().createMolecule();
+
+  StoreFragmentFromKeySet_Init(mol, Leaf, Leaflet, SonList);
+  // create the bonds between all: Make it an induced subgraph and add hydrogen
+//  LOG(2, "Creating bonds from father graph (i.e. induced subgraph creation).");
+  CreateInducedSubgraphOfFragment(mol, Leaf, SonList, IsAngstroem);
+
+  //Leaflet->Leaf->ScanForPeriodicCorrection(out);
+  return Leaf;
+}
+
+/** Initializes some value for putting fragment of \a *mol into \a *Leaf.
+ * \param *mol total molecule
+ * \param *Leaf fragment molecule
+ * \param &Leaflet pointer to KeySet structure
+ * \param SonList calloc'd list which atom of \a *Leaf is a son of which atom in \a *mol
+ * \return number of atoms in fragment
+ */
+int ExportGraph_ToFiles::StoreFragmentFromKeySet_Init(molecule *mol, molecule *Leaf, KeySet &Leaflet, ListOfLocalAtoms_t &SonList)
+{
+  atom *FatherOfRunner = NULL;
+
+  // first create the minimal set of atoms from the KeySet
+  int size = 0;
+  for(KeySet::const_iterator runner = Leaflet.begin(); runner != Leaflet.end(); runner++) {
+    FatherOfRunner = mol->FindAtom((*runner));  // find the id
+    SonList.insert( std::make_pair(FatherOfRunner->getNr(), Leaf->AddCopyAtom(FatherOfRunner) ) );
+    size++;
+  }
+  return size;
+}
+
+/** Creates an induced subgraph out of a fragmental key set, adding bonds and hydrogens (if treated specially).
+ * \param *out output stream for debugging messages
+ * \param *mol total molecule
+ * \param *Leaf fragment molecule
+ * \param IsAngstroem whether we have Ansgtroem or bohrradius
+ * \param SonList list which atom of \a *Leaf is a son of which atom in \a *mol
+ */
+void ExportGraph_ToFiles::CreateInducedSubgraphOfFragment(molecule *mol, molecule *Leaf, ListOfLocalAtoms_t &SonList, bool IsAngstroem)
+{
+  bool LonelyFlag = false;
+  atom *OtherFather = NULL;
+  atom *FatherOfRunner = NULL;
+
+  // we increment the iter just before skipping the hydrogen
+  // as we use AddBond, we cannot have a const_iterator here
+  for (molecule::iterator iter = Leaf->begin(); iter != Leaf->end();) {
+    LonelyFlag = true;
+    FatherOfRunner = (*iter)->father;
+    ASSERT(FatherOfRunner,"Atom without father found");
+    if (SonList.find(FatherOfRunner->getNr()) != SonList.end())  {  // check if this, our father, is present in list
+      // create all bonds
+      const BondList& ListOfBonds = FatherOfRunner->getListOfBonds();
+      for (BondList::const_iterator BondRunner = ListOfBonds.begin();
+          BondRunner != ListOfBonds.end();
+          ++BondRunner) {
+        OtherFather = (*BondRunner)->GetOtherAtom(FatherOfRunner);
+        if (SonList.find(OtherFather->getNr()) != SonList.end()) {
+//          LOG(2, "INFO: Father " << *FatherOfRunner << " of son " << *SonList[FatherOfRunner->getNr()]
+//              << " is bound to " << *OtherFather << ", whose son is "
+//              << *SonList[OtherFather->getNr()] << ".");
+          if (OtherFather->getNr() > FatherOfRunner->getNr()) { // add bond (Nr check is for adding only one of both variants: ab, ba)
+            std::stringstream output;
+//            output << "ACCEPT: Adding Bond: "
+            output << Leaf->AddBond((*iter), SonList[OtherFather->getNr()], (*BondRunner)->BondDegree);
+//            LOG(3, output.str());
+            //NumBonds[(*iter)->getNr()]++;
+          } else {
+//            LOG(3, "REJECY: Not adding bond, labels in wrong order.");
+          }
+          LonelyFlag = false;
+        } else {
+//          LOG(2, "INFO: Father " << *FatherOfRunner << " of son " << *SonList[FatherOfRunner->getNr()]
+//              << " is bound to " << *OtherFather << ", who has no son in this fragment molecule.");
+          if (saturation == DoSaturate) {
+//          LOG(3, "ACCEPT: Adding Hydrogen to " << (*iter)->Name << " and a bond in between.");
+            if (!Leaf->AddHydrogenReplacementAtom((*BondRunner), (*iter), FatherOfRunner, OtherFather, IsAngstroem))
+              exit(1);
+          }
+          //NumBonds[(*iter)->getNr()] += Binder->BondDegree;
+        }
+      }
+    } else {
+    ELOG(1, "Son " << (*iter)->getName() << " has father " << FatherOfRunner->getName() << " but its entry in SonList is " << SonList[FatherOfRunner->getNr()] << "!");
+    }
+    if ((LonelyFlag) && (Leaf->getAtomCount() > 1)) {
+      LOG(0, **iter << "has got bonds only to hydrogens!");
+    }
+    ++iter;
+    if (saturation == DoSaturate) {
+      while ((iter != Leaf->end()) && ((*iter)->getType()->getAtomicNumber() == 1)){ // skip added hydrogen
+        iter++;
+      }
+    }
+  }
+}
+
+/** Create a SortIndex to map from atomic labels to the sequence in which the atoms are given in the config file.
+ * \param &SortIndex Mapping array of size molecule::AtomCount
+ * \return true - success, false - failure of SortIndex alloc
+ */
+bool ExportGraph_ToFiles::CreateMappingLabelsToConfigSequence(std::map<atomId_t, int> &SortIndex)
+{
+  if (!SortIndex.empty()) {
+    LOG(1, "SortIndex has " << SortIndex.size() << " entries and is not empty as expected.");
+    return false;
+  }
+
+  int AtomNo = 0;
+  for(molecule::const_iterator iter=mol->begin();iter!=mol->end();++iter){
+    const int id = (*iter)->getNr();
+#ifndef NDEBUG
+      std::pair<std::map<atomId_t, int>::const_iterator, bool> inserter =
+#endif
+    SortIndex.insert( std::make_pair(id, AtomNo++) );
+    ASSERT( inserter.second ,
+        "ExportGraph_ToFiles::CreateMappingLabelsToConfigSequence() - same SortIndex set twice.");
+  }
+
+  return true;
+}
+
