/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2010-2012 University of Bonn. All rights reserved.
 * Copyright (C)  2013 Frederik Heber. All rights reserved.
 * 
 *
 *   This file is part of MoleCuilder.
 *
 *    MoleCuilder is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    MoleCuilder is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoleCuilder.  If not, see .
 */
/*
 * cleanUp.cpp
 *
 *  Created on: Oct 28, 2011
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include 
#include 
#include "CodePatterns/MemDebug.hpp"
#include "cleanUp.hpp"
#include "Atom/AtomObserver.hpp"
#include "CodePatterns/Chronos.hpp"
#include "CodePatterns/errorlogger.hpp"
#include "CodePatterns/logger.hpp"
#include "CodePatterns/Observer/ObserverLog.hpp"
#include "Actions/ActionHistory.hpp"
#include "Actions/ActionRegistry.hpp"
#include "Actions/OptionRegistry.hpp"
#include "RandomNumbers/RandomNumberDistributionFactory.hpp"
#include "RandomNumbers/RandomNumberEngineFactory.hpp"
#include "RandomNumbers/RandomNumberGeneratorFactory.hpp"
#include "Parser/ChangeTracker.hpp"
#include "Parser/FormatParserStorage.hpp"
#include "Parser/XmlParser.hpp"
#include "Shapes/ShapeFactory.hpp"
#include "Shapes/ShapeRegistry.hpp"
#include "UIElements/CommandLineUI/CommandLineParser.hpp"
#include "UIElements/Menu/MenuDescription.hpp"
#include "UIElements/UIFactory.hpp"
#include "World.hpp"
#include "WorldTime.hpp"
/** In this function all dynamicly allocated member variables to static/global
 * variables are added to the ignore list of Memory/MemDebug.
 *
 * Use this to prevent their listing in the Memory::getState() at the end of the
 * program. Check with valgrind that truely no memory leak occurs!
 */
void AddStaticEntitiestoIgnoreList()
{
  // zeroVec and unitVec are global variables (on the stack) but vectorContent
  // within is situated on the heap and has to be ignored
  Memory::ignore(zeroVec.get());
  Memory::ignore(unitVec[0].get());
  Memory::ignore(unitVec[1].get());
  Memory::ignore(unitVec[2].get());
  // XmlParser has static instance that uses vectorContent as well
  Memory::ignore(FormatParser< xml >::defaultAtomInfo.field.get());
}
/** purges all static (singleton) instances in correct order of dependency.
 *
 */
void purgeStaticInstances()
{
  Chronos::purgeInstance();
  RandomNumberDistributionFactory::purgeInstance();
  RandomNumberEngineFactory::purgeInstance();
  RandomNumberGeneratorFactory::purgeInstance();
  ShapeFactory::purgeInstance();
  ShapeRegistry::purgeInstance();
  FormatParserStorage::purgeInstance();
  ChangeTracker::purgeInstance();
  World::purgeInstance();
  AtomObserver::purgeInstance();
  MenuDescription::purgeInstance();
  UIFactory::purgeInstance();
  CommandLineParser::purgeInstance();
  MoleCuilder::ActionRegistry::purgeInstance();
  MoleCuilder::OptionRegistry::purgeInstance();
  MoleCuilder::ActionHistory::purgeInstance();
  logger::purgeInstance();
  errorLogger::purgeInstance();
  WorldTime::purgeInstance();
}
/** Cleans all singleton instances in an orderly fashion.
 * C++ does not guarantee any specific sequence of removal of single instances
 * which have static/global variables. Some singletons depend on others hence we
 * acertain a specific ordering here, which is is used via the atexit() hook.
 */
void cleanUp()
{
  // give timings per Action
  printTimings();
  // purge static instances from memory
  purgeStaticInstances(); 
  // put some static variables' dynamic contents on the Memory::ignore map to avoid their
  // admonishing lateron
  AddStaticEntitiestoIgnoreList();
#ifdef LOG_OBSERVER
  cout << observerLog().getLog();
#endif
#ifndef NDEBUG
  // CodePatterns always initializes observerLog except with NDEBUG
  ObserverLog::purgeInstance();
#endif
  Memory::getState();
}
/** We give a list of all times per action and a total time.
 *
 */
void printTimings()
{
  const MoleCuilder::ActionRegistry &AR = MoleCuilder::ActionRegistry::getInstance();
  const Chronos &Chron = Chronos::getInstance();
  if (!DoLog(2)) {
    std::cout << "(Non-zero) Times used per Action [seconds]:" << std::endl;
    for (MoleCuilder::ActionRegistry::const_iterator iter = AR.getBeginIter(); iter != AR.getEndIter(); ++iter)
      if (Chron.getTime(iter->first) != 0.) { // dont give if action has not been used
        std::cout << "  " << setiosflags(ios::left) << setw(24) << setfill('.') << iter->first;
        std::cout << setiosflags(ios::left)
#ifdef HAVE_SYS_TIMES_H
              << setprecision(3)
#else
              << setprecision(9)
#endif
              << fixed << Chron.getTime(iter->first) << std::endl;
      }
  } else {
    std::cout << "Measured times [seconds]:" << std::endl;
    const Chronos::TimekeepingMap &timemap = Chron.getTimekeepingMap();
    for (Chronos::TimekeepingMap::const_iterator iter = timemap.begin();
        iter != timemap.end();
        ++iter) {
      std::cout << "  " << setiosflags(ios::left) << setw(24) << setfill('.') << iter->first;
      std::cout << setiosflags(ios::left)
#ifdef HAVE_SYS_TIMES_H
          << setprecision(3)
#else
          << setprecision(9)
#endif
          << fixed << iter->second << std::endl;
    }
  }
  std::cout << "Total Time: " << Chron.SumUpTotalTime() << " seconds" << std::endl;
  std::cout << "Total Actions called: " << Chron.SumUpTotalFunctions() << std::endl;
}
/** Dump current memory chunks.
 *
 */
void dumpMemory()
{
  ofstream ost("molecuilder.memdump");
  Memory::dumpMemory(ost);
}
/** Save the current World to output files and exit.
 *
 * @return retrieved from World::getExitFlag()
 */
int saveAll()
{
  FormatParserStorage::getInstance().SaveAll();
  ChangeTracker::getInstance().saveStatus();
  int ExitFlag = World::getInstance().getExitFlag();
  return (ExitFlag == 1 ? 0 : ExitFlag);
}