Sort all includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / commandline / cmdlinemodulemanager.cpp
index 9be10392f905354ffe9bafd8efe7afdd03445de1..8fee8aa10e28ca0cef593bdd1b1d1a8ffc6410e5 100644 (file)
@@ -1,10 +1,10 @@
 /*
  * This file is part of the GROMACS molecular simulation package.
  *
- * Copyright (c) 2012,2013, by the GROMACS development team, led by
- * David van der Spoel, Berk Hess, Erik Lindahl, and including many
- * others, as listed in the AUTHORS file in the top-level source
- * directory and at http://www.gromacs.org.
+ * Copyright (c) 2012,2013,2014, by the GROMACS development team, led by
+ * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
+ * and including many others, as listed in the AUTHORS file in the
+ * top-level source directory and at http://www.gromacs.org.
  *
  * GROMACS is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public License
  * \author Teemu Murtola <teemu.murtola@gmail.com>
  * \ingroup module_commandline
  */
+#include "gmxpre.h"
+
 #include "cmdlinemodulemanager.h"
 
+#include "config.h"
+
 #include <cstdio>
 
-#include <map>
 #include <string>
 #include <utility>
 
-#include "gromacs/legacyheaders/copyrite.h"
-#include "gromacs/legacyheaders/network.h"
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
 
+#include "gromacs/commandline/cmdlinehelpcontext.h"
+#include "gromacs/commandline/cmdlineinit.h"
 #include "gromacs/commandline/cmdlinemodule.h"
 #include "gromacs/commandline/cmdlineparser.h"
-#include "gromacs/onlinehelp/helpformat.h"
-#include "gromacs/onlinehelp/helpmanager.h"
-#include "gromacs/onlinehelp/helptopic.h"
-#include "gromacs/onlinehelp/helpwritercontext.h"
+#include "gromacs/commandline/cmdlineprogramcontext.h"
+#include "gromacs/legacyheaders/copyrite.h"
 #include "gromacs/options/basicoptions.h"
 #include "gromacs/options/options.h"
+#include "gromacs/utility/basenetwork.h"
 #include "gromacs/utility/exceptions.h"
-#include "gromacs/utility/file.h"
+#include "gromacs/utility/fatalerror.h"
 #include "gromacs/utility/gmxassert.h"
-#include "gromacs/utility/init.h"
-#include "gromacs/utility/programinfo.h"
 #include "gromacs/utility/stringutil.h"
 
+#include "cmdlinehelpmodule.h"
+#include "cmdlinemodulemanager-impl.h"
+
 namespace gmx
 {
 
-//! Container type for mapping module names to module objects.
-typedef std::map<std::string, CommandLineModulePointer> CommandLineModuleMap;
-
 namespace
 {
 
-/********************************************************************
- * RootHelpTopic
- */
-
-struct RootHelpText
-{
-    static const char        name[];
-    static const char        title[];
-    static const char *const text[];
-};
-
-// The first two are not used.
-const char        RootHelpText::name[]  = "";
-const char        RootHelpText::title[] = "";
-const char *const RootHelpText::text[]  = {
-    "Usage: [PROGRAM] <command> [<args>]",
-};
-
-/*! \internal \brief
- * Help topic that forms the root of the help tree for the help subcommand.
- *
- * \ingroup module_commandline
- */
-class RootHelpTopic : public CompositeHelpTopic<RootHelpText>
-{
-    public:
-        /*! \brief
-         * Creates a root help topic.
-         *
-         * \param[in] modules  List of modules for to use for module listings.
-         *
-         * Does not throw.
-         */
-        explicit RootHelpTopic(const CommandLineModuleMap &modules)
-            : modules_(modules)
-        {
-        }
-
-        virtual void writeHelp(const HelpWriterContext &context) const;
-
-    private:
-        void printModuleList(const HelpWriterContext &context) const;
-
-        const CommandLineModuleMap &modules_;
-
-        GMX_DISALLOW_COPY_AND_ASSIGN(RootHelpTopic);
-};
-
-void RootHelpTopic::writeHelp(const HelpWriterContext &context) const
-{
-    if (context.outputFormat() != eHelpOutputFormat_Console)
-    {
-        // TODO: Implement once the situation with Redmine issue #969 is more
-        // clear.
-        GMX_THROW(NotImplementedError(
-                          "Root help is not implemented for this output format"));
-    }
-    writeBasicHelpTopic(context, *this, helpText());
-    // TODO: If/when this list becomes long, it may be better to only print
-    // "common" commands here, and have a separate topic (e.g.,
-    // "help commands") that prints the full list.
-    printModuleList(context);
-    context.writeTextBlock(
-            "For additional help on a command, use '[PROGRAM] help <command>'");
-    writeSubTopicList(context,
-                      "\nAdditional help is available on the following topics:");
-    context.writeTextBlock(
-            "To access the help, use '[PROGRAM] help <topic>'.");
-}
-
-void RootHelpTopic::printModuleList(const HelpWriterContext &context) const
-{
-    if (context.outputFormat() != eHelpOutputFormat_Console)
-    {
-        // TODO: Implement once the situation with Redmine issue #969 is more
-        // clear.
-        GMX_THROW(NotImplementedError(
-                          "Module list is not implemented for this output format"));
-    }
-    int maxNameLength = 0;
-    CommandLineModuleMap::const_iterator module;
-    for (module = modules_.begin(); module != modules_.end(); ++module)
-    {
-        int nameLength = static_cast<int>(module->first.length());
-        if (module->second->shortDescription() != NULL
-            && nameLength > maxNameLength)
-        {
-            maxNameLength = nameLength;
-        }
-    }
-    File              &file = context.outputFile();
-    TextTableFormatter formatter;
-    formatter.addColumn(NULL, maxNameLength + 1, false);
-    formatter.addColumn(NULL, 72 - maxNameLength, true);
-    formatter.setFirstColumnIndent(4);
-    file.writeLine();
-    file.writeLine("Available commands:");
-    for (module = modules_.begin(); module != modules_.end(); ++module)
-    {
-        const char *name        = module->first.c_str();
-        const char *description = module->second->shortDescription();
-        if (description != NULL)
-        {
-            formatter.clear();
-            formatter.addColumnLine(0, name);
-            formatter.addColumnLine(1, description);
-            file.writeString(formatter.formatRow());
-        }
-    }
-}
-
-/********************************************************************
- * ModuleHelpTopic
- */
-
-/*! \internal \brief
- * Help topic wrapper for a command-line module.
- *
- * This class implements HelpTopicInterface such that it wraps a
- * CommandLineModuleInterface, allowing subcommand "help <command>"
- * to produce the help for "<command>".
- *
- * \ingroup module_commandline
- */
-class ModuleHelpTopic : public HelpTopicInterface
-{
-    public:
-        //! Constructs a help topic for a specific module.
-        explicit ModuleHelpTopic(const CommandLineModuleInterface &module)
-            : module_(module)
-        {
-        }
-
-        virtual const char *name() const { return module_.name(); }
-        virtual const char *title() const { return NULL; }
-        virtual bool hasSubTopics() const { return false; }
-        virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
-        {
-            return NULL;
-        }
-        virtual void writeHelp(const HelpWriterContext &context) const;
-
-    private:
-        const CommandLineModuleInterface &module_;
-
-        GMX_DISALLOW_COPY_AND_ASSIGN(ModuleHelpTopic);
-};
-
-void ModuleHelpTopic::writeHelp(const HelpWriterContext &context) const
-{
-    module_.writeHelp(context);
-}
-
-}   // namespace
-
-/********************************************************************
- * CommandLineHelpModule
- */
-
-/*! \internal \brief
- * Command-line module for producing help.
- *
- * This module implements the 'help' subcommand that is automatically added by
- * CommandLineModuleManager.
- *
- * \ingroup module_commandline
- */
-class CommandLineHelpModule : public CommandLineModuleInterface
-{
-    public:
-        /*! \brief
-         * Creates a command-line help module.
-         *
-         * \param[in] modules  List of modules for to use for module listings.
-         * \throws    std::bad_alloc if out of memory.
-         */
-        explicit CommandLineHelpModule(const CommandLineModuleMap &modules);
-
-        /*! \brief
-         * Adds a top-level help topic.
-         *
-         * \param[in] topic  Help topic to add.
-         * \throws    std::bad_alloc if out of memory.
-         */
-        void addTopic(HelpTopicPointer topic);
-
-        virtual const char *name() const { return "help"; }
-        virtual const char *shortDescription() const
-        {
-            return "Print help information";
-        }
-
-        virtual int run(int argc, char *argv[]);
-        virtual void writeHelp(const HelpWriterContext &context) const;
-
-    private:
-        CompositeHelpTopicPointer   rootTopic_;
-
-        GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineHelpModule);
-};
-
-CommandLineHelpModule::CommandLineHelpModule(const CommandLineModuleMap &modules)
-    : rootTopic_(new RootHelpTopic(modules))
-{
-}
-
-void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
-{
-    rootTopic_->addSubTopic(move(topic));
-}
-
-int CommandLineHelpModule::run(int argc, char *argv[])
-{
-    HelpWriterContext context(&File::standardOutput(),
-                              eHelpOutputFormat_Console);
-    HelpManager       helpManager(*rootTopic_, context);
-    try
-    {
-        for (int i = 1; i < argc; ++i)
-        {
-            helpManager.enterTopic(argv[i]);
-        }
-    }
-    catch (const InvalidInputError &ex)
-    {
-        fprintf(stderr, "%s\n", ex.what());
-        return 2;
-    }
-    helpManager.writeCurrentTopic();
-    return 0;
-}
-
-void CommandLineHelpModule::writeHelp(const HelpWriterContext &context) const
-{
-    context.writeTextBlock(
-            "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
-    // TODO: More information.
-}
-
-namespace
-{
+//! \addtogroup module_commandline
+//! \{
 
 /********************************************************************
  * CMainCommandLineModule
  */
 
-/*! \internal \brief
+/*! \brief
  * Implements a CommandLineModuleInterface, given a function with C/C++ main()
  * signature.
- *
- * \ingroup module_commandline
  */
 class CMainCommandLineModule : public CommandLineModuleInterface
 {
@@ -358,32 +120,83 @@ class CMainCommandLineModule : public CommandLineModuleInterface
             return shortDescription_;
         }
 
+        virtual void init(CommandLineModuleSettings * /*settings*/)
+        {
+        }
         virtual int run(int argc, char *argv[])
         {
             return mainFunction_(argc, argv);
         }
-        virtual void writeHelp(const HelpWriterContext &context) const
+        virtual void writeHelp(const CommandLineHelpContext &context) const
         {
-            if (context.outputFormat() != eHelpOutputFormat_Console)
-            {
-                GMX_THROW(NotImplementedError(
-                                  "Command-line help is not implemented for this output format"));
-            }
-            char *argv[2];
-            // TODO: The constness should not be cast away.
-            argv[0] = const_cast<char *>(name_);
-            argv[1] = const_cast<char *>("-h");
-            mainFunction_(2, argv);
+            writeCommandLineHelpCMain(context, name_, mainFunction_);
         }
 
     private:
         const char             *name_;
         const char             *shortDescription_;
         CMainFunction           mainFunction_;
-
 };
 
-} // namespace
+//! \}
+
+}   // namespace
+
+/********************************************************************
+ * CommandLineCommonOptionsHolder
+ */
+
+CommandLineCommonOptionsHolder::CommandLineCommonOptionsHolder()
+    : options_(NULL, NULL), bHelp_(false), bHidden_(false),
+      bQuiet_(false), bVersion_(false), bCopyright_(true),
+      niceLevel_(19), debugLevel_(0)
+{
+    binaryInfoSettings_.copyright(true);
+}
+
+CommandLineCommonOptionsHolder::~CommandLineCommonOptionsHolder()
+{
+}
+
+void CommandLineCommonOptionsHolder::initOptions()
+{
+    options_.addOption(BooleanOption("h").store(&bHelp_)
+                           .description("Print help and quit"));
+    options_.addOption(BooleanOption("hidden").store(&bHidden_)
+                           .hidden()
+                           .description("Show hidden options in help"));
+    options_.addOption(BooleanOption("quiet").store(&bQuiet_)
+                           .description("Do not print common startup info or quotes"));
+    options_.addOption(BooleanOption("version").store(&bVersion_)
+                           .description("Print extended version information and quit"));
+    options_.addOption(BooleanOption("copyright").store(&bCopyright_)
+                           .description("Print copyright information on startup"));
+    options_.addOption(IntegerOption("nice").store(&niceLevel_)
+                           .description("Set the nicelevel (default depends on command)"));
+    options_.addOption(IntegerOption("debug").store(&debugLevel_)
+                           .hidden().defaultValueIfSet(1)
+                           .description("Write file with debug information, "
+                                        "1: short (default), 2: also x and f"));
+}
+
+bool CommandLineCommonOptionsHolder::finishOptions()
+{
+    options_.finish();
+    binaryInfoSettings_.extendedInfo(bVersion_);
+    // The latter condition suppresses the copyright with
+    // -quiet -version.
+    binaryInfoSettings_.copyright(bCopyright_ && !bQuiet_);
+    return !bVersion_;
+}
+
+void CommandLineCommonOptionsHolder::adjustFromSettings(
+        const CommandLineModuleSettings &settings)
+{
+    if (!options_.isSet("nice"))
+    {
+        niceLevel_ = settings.defaultNiceLevel();
+    }
+}
 
 /********************************************************************
  * CommandLineModuleManager::Impl
@@ -400,9 +213,26 @@ class CommandLineModuleManager::Impl
         /*! \brief
          * Initializes the implementation class.
          *
-         * \param     programInfo  Program information for the running binary.
+         * \param[in] binaryName     Name of the running binary
+         *     (without Gromacs binary suffix or .exe on Windows).
+         * \param     programContext Program information for the running binary.
+         */
+        Impl(const char *binaryName, CommandLineProgramContext *programContext);
+
+        /*! \brief
+         * Helper method that adds a given module to the module manager.
+         *
+         * \throws    std::bad_alloc if out of memory.
+         */
+        void addModule(CommandLineModulePointer module);
+        /*! \brief
+         * Creates the help module if it does not yet exist.
+         *
+         * \throws    std::bad_alloc if out of memory.
+         *
+         * This method should be called before accessing \a helpModule_.
          */
-        explicit Impl(ProgramInfo *programInfo);
+        void ensureHelpModuleExists();
 
         /*! \brief
          * Finds a module that matches a name.
@@ -418,28 +248,29 @@ class CommandLineModuleManager::Impl
         /*! \brief
          * Finds a module that the name of the binary.
          *
-         * \param[in] programInfo  Program information object to use.
+         * \param[in] invokedName  Name by which the program was invoked.
          * \throws    std::bad_alloc if out of memory.
          * \returns   Iterator to the found module, or
          *      \c modules_.end() if not found.
          *
          * Checks whether the program is invoked through a symlink whose name
-         * is different from ProgramInfo::realBinaryName(), and if so, checks
+         * is different from \a binaryName_, and if so, checks
          * if a module name matches the name of the symlink.
          *
-         * Note that the \p programInfo parameter is currently not necessary
-         * (as the program info object is also contained as a member), but it
-         * clarifies the control flow.
+         * Note that the \p invokedName parameter is currently not necessary
+         * (as the program context object is also available and provides this
+         * value), but it clarifies the control flow.
          */
         CommandLineModuleMap::const_iterator
-        findModuleFromBinaryName(const ProgramInfo &programInfo) const;
+        findModuleFromBinaryName(const char *invokedName) const;
 
         /*! \brief
          * Processes command-line options for the wrapper binary.
          *
-         * \param[in,out] argc On input, argc passed to run().
+         * \param[in,out] optionsHolder Common options.
+         * \param[in,out] argc          On input, argc passed to run().
          *     On output, argc to be passed to the module.
-         * \param[in,out] argv On input, argv passed to run().
+         * \param[in,out] argv          On input, argv passed to run().
          *     On output, argv to be passed to the module.
          * \throws    InvalidInputError if there are invalid options.
          * \returns   The module that should be run.
@@ -450,7 +281,8 @@ class CommandLineModuleManager::Impl
          * arguments that should be passed to it.
          */
         CommandLineModuleInterface *
-        processCommonOptions(int *argc, char ***argv);
+        processCommonOptions(CommandLineCommonOptionsHolder *optionsHolder,
+                             int *argc, char ***argv);
 
         /*! \brief
          * Maps module names to module objects.
@@ -458,31 +290,63 @@ class CommandLineModuleManager::Impl
          * Owns the contained modules.
          */
         CommandLineModuleMap         modules_;
+        /*! \brief
+         * List of groupings for modules for help output.
+         *
+         * Owns the contained module group data objects.
+         * CommandLineModuleGroup objects point to the data objects contained
+         * here.
+         */
+        CommandLineModuleGroupList   moduleGroups_;
         //! Information about the currently running program.
-        ProgramInfo                 &programInfo_;
+        CommandLineProgramContext   &programContext_;
+        //! Name of the binary.
+        std::string                  binaryName_;
         /*! \brief
          * Module that implements help for the binary.
          *
          * The pointed module is owned by the \a modules_ container.
          */
         CommandLineHelpModule       *helpModule_;
-        //! Settings for what to write in the startup header.
-        BinaryInformationSettings    binaryInfoSettings_;
         //! If non-NULL, run this module in single-module mode.
         CommandLineModuleInterface  *singleModule_;
-        //! Whether all stderr output should be suppressed.
+        //! Stores the value set with setQuiet().
         bool                         bQuiet_;
-        //! Whether to write the startup information to stdout iso stderr.
-        bool                         bStdOutInfo_;
 
     private:
         GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
 };
 
-CommandLineModuleManager::Impl::Impl(ProgramInfo *programInfo)
-    : programInfo_(*programInfo), helpModule_(NULL), singleModule_(NULL),
-      bQuiet_(false), bStdOutInfo_(false)
+CommandLineModuleManager::Impl::Impl(const char                *binaryName,
+                                     CommandLineProgramContext *programContext)
+    : programContext_(*programContext),
+      binaryName_(binaryName != NULL ? binaryName : ""),
+      helpModule_(NULL), singleModule_(NULL),
+      bQuiet_(false)
 {
+    GMX_RELEASE_ASSERT(binaryName_.find('-') == std::string::npos,
+                       "Help export does not currently work with binary names with dashes");
+}
+
+void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
+{
+    GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
+               "Attempted to register a duplicate module name");
+    ensureHelpModuleExists();
+    HelpTopicPointer helpTopic(helpModule_->createModuleHelpTopic(*module));
+    modules_.insert(std::make_pair(std::string(module->name()),
+                                   move(module)));
+    helpModule_->addTopic(move(helpTopic));
+}
+
+void CommandLineModuleManager::Impl::ensureHelpModuleExists()
+{
+    if (helpModule_ == NULL)
+    {
+        helpModule_ = new CommandLineHelpModule(programContext_, binaryName_,
+                                                modules_, moduleGroups_);
+        addModule(CommandLineModulePointer(helpModule_));
+    }
 }
 
 CommandLineModuleMap::const_iterator
@@ -494,22 +358,30 @@ CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
 
 CommandLineModuleMap::const_iterator
 CommandLineModuleManager::Impl::findModuleFromBinaryName(
-        const ProgramInfo &programInfo) const
+        const char *invokedName) const
 {
-    std::string binaryName = programInfo.invariantProgramName();
-    if (binaryName == programInfo.realBinaryName())
+    std::string moduleName = invokedName;
+#ifdef GMX_BINARY_SUFFIX
+    moduleName = stripSuffixIfPresent(moduleName, GMX_BINARY_SUFFIX);
+#endif
+    if (moduleName == binaryName_)
     {
         return modules_.end();
     }
-    if (binaryName.compare(0, 2, "g_") == 0)
+    if (startsWith(moduleName, "g_"))
     {
-        binaryName.erase(0, 2);
+        moduleName.erase(0, 2);
     }
-    return findModuleByName(binaryName);
+    if (startsWith(moduleName, "gmx"))
+    {
+        moduleName.erase(0, 3);
+    }
+    return findModuleByName(moduleName);
 }
 
 CommandLineModuleInterface *
-CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
+CommandLineModuleManager::Impl::processCommonOptions(
+        CommandLineCommonOptionsHolder *optionsHolder, int *argc, char ***argv)
 {
     // Check if we are directly invoking a certain module.
     CommandLineModuleInterface *module = singleModule_;
@@ -517,34 +389,15 @@ CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
     {
         // Also check for invokation through named symlinks.
         CommandLineModuleMap::const_iterator moduleIter
-            = findModuleFromBinaryName(programInfo_);
+            = findModuleFromBinaryName(programContext_.programName());
         if (moduleIter != modules_.end())
         {
             module = moduleIter->second.get();
         }
     }
 
-    bool bHelp      = false;
-    bool bVersion   = false;
-    bool bCopyright = false;
-    // TODO: Print the common options into the help.
     // TODO: It would be nice to propagate at least the -quiet option to
     // the modules so that they can also be quiet in response to this.
-    // TODO: Consider handling -h and related options here instead of in the
-    // modules (also -hidden needs to be transfered here to make that work).
-    // That would mean that with -h, all module-specific options would get
-    // ignored.  This means that the help output would not depend on the
-    // command line, but would always show the default values (making it
-    // possible to simplify it further), but also that mdrun -h could not be
-    // used for option validation in g_tune_pme.
-    Options options(NULL, NULL);
-    if (module == NULL)
-    {
-        options.addOption(BooleanOption("h").store(&bHelp));
-    }
-    options.addOption(BooleanOption("quiet").store(&bQuiet_));
-    options.addOption(BooleanOption("version").store(&bVersion));
-    options.addOption(BooleanOption("copyright").store(&bCopyright));
 
     if (module == NULL)
     {
@@ -557,10 +410,11 @@ CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
         }
         if (argcForWrapper > 1)
         {
-            CommandLineParser(&options).parse(&argcForWrapper, *argv);
+            CommandLineParser(optionsHolder->options())
+                .parse(&argcForWrapper, *argv);
         }
         // If no action requested and there is a module specified, process it.
-        if (argcForWrapper < *argc && !bHelp && !bVersion && !bCopyright)
+        if (argcForWrapper < *argc && !optionsHolder->shouldIgnoreActualModule())
         {
             const char *moduleName = (*argv)[argcForWrapper];
             CommandLineModuleMap::const_iterator moduleIter
@@ -572,35 +426,43 @@ CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
                 GMX_THROW(InvalidInputError(message));
             }
             module = moduleIter->second.get();
-            programInfo_.setDisplayName(
-                    programInfo_.realBinaryName() + "-" + moduleIter->first);
             *argc -= argcForWrapper;
             *argv += argcForWrapper;
             // After this point, argc and argv are the same independent of
             // which path is taken: (*argv)[0] is the module name.
         }
     }
-    else
+    if (module != NULL)
     {
-        // In single-module mode, recognize the common options also after the
-        // module name.
-        CommandLineParser(&options).skipUnknown(true).parse(argc, *argv);
+        if (singleModule_ == NULL)
+        {
+            programContext_.setDisplayName(binaryName_ + " " + module->name());
+        }
+        // Recognize the common options also after the module name.
+        // TODO: It could be nicer to only recognize -h/-hidden if module is not
+        // null.
+        CommandLineParser(optionsHolder->options())
+            .skipUnknown(true).parse(argc, *argv);
     }
-    options.finish();
-    binaryInfoSettings_.extendedInfo(bVersion);
-    binaryInfoSettings_.copyright(bCopyright);
-    if (bVersion || bCopyright)
+    if (!optionsHolder->finishOptions())
     {
-        bQuiet_      = false;
-        bStdOutInfo_ = true;
         return NULL;
     }
     // If no module specified and no other action, show the help.
     // Also explicitly specifying -h for the wrapper binary goes here.
-    if (module == NULL)
+    if (module == NULL || optionsHolder->shouldShowHelp())
     {
-        *argc = 1;
-        return helpModule_;
+        ensureHelpModuleExists();
+        if (module != NULL)
+        {
+            helpModule_->setModuleOverride(*module);
+        }
+        *argc  = 1;
+        module = helpModule_;
+    }
+    if (module == helpModule_)
+    {
+        helpModule_->setShowHidden(optionsHolder->shouldShowHidden());
     }
     return module;
 }
@@ -609,8 +471,9 @@ CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
  * CommandLineModuleManager
  */
 
-CommandLineModuleManager::CommandLineModuleManager(ProgramInfo *programInfo)
-    : impl_(new Impl(programInfo))
+CommandLineModuleManager::CommandLineModuleManager(
+        const char *binaryName, CommandLineProgramContext *programContext)
+    : impl_(new Impl(binaryName, programContext))
 {
 }
 
@@ -623,14 +486,20 @@ void CommandLineModuleManager::setQuiet(bool bQuiet)
     impl_->bQuiet_ = bQuiet;
 }
 
+void CommandLineModuleManager::setOutputRedirect(File *output)
+{
+    impl_->ensureHelpModuleExists();
+    impl_->helpModule_->setOutputRedirect(output);
+}
+
+void CommandLineModuleManager::setSingleModule(CommandLineModuleInterface *module)
+{
+    impl_->singleModule_ = module;
+}
+
 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
 {
-    GMX_ASSERT(impl_->modules_.find(module->name()) == impl_->modules_.end(),
-               "Attempted to register a duplicate module name");
-    HelpTopicPointer helpTopic(new ModuleHelpTopic(*module));
-    impl_->modules_.insert(std::make_pair(std::string(module->name()),
-                                          move(module)));
-    addHelpTopic(move(helpTopic));
+    impl_->addModule(move(module));
 }
 
 void CommandLineModuleManager::addModuleCMain(
@@ -642,49 +511,95 @@ void CommandLineModuleManager::addModuleCMain(
     addModule(move(module));
 }
 
+CommandLineModuleGroup CommandLineModuleManager::addModuleGroup(
+        const char *title)
+{
+    const char *const                 binaryName = impl_->binaryName_.c_str();
+    CommandLineModuleGroupDataPointer group(
+            new CommandLineModuleGroupData(impl_->modules_, binaryName, title));
+    impl_->moduleGroups_.push_back(move(group));
+    return CommandLineModuleGroup(impl_->moduleGroups_.back().get());
+}
+
 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
 {
-    if (impl_->helpModule_ == NULL)
-    {
-        impl_->helpModule_ = new CommandLineHelpModule(impl_->modules_);
-        addModule(CommandLineModulePointer(impl_->helpModule_));
-    }
+    impl_->ensureHelpModuleExists();
     impl_->helpModule_->addTopic(move(topic));
 }
 
 int CommandLineModuleManager::run(int argc, char *argv[])
 {
-    CommandLineModuleInterface *module;
-    const bool bMaster = (!gmx_mpi_initialized() || gmx_node_rank() == 0);
+    CommandLineModuleInterface    *module;
+    const bool                     bMaster = (gmx_node_rank() == 0);
+    bool                           bQuiet  = impl_->bQuiet_ || !bMaster;
+    CommandLineCommonOptionsHolder optionsHolder;
     try
     {
-        module = impl_->processCommonOptions(&argc, &argv);
+        optionsHolder.initOptions();
+        module = impl_->processCommonOptions(&optionsHolder, &argc, &argv);
     }
     catch (const std::exception &)
     {
-        if (bMaster && !impl_->bQuiet_)
+        bQuiet |= optionsHolder.shouldBeQuiet();
+        if (!bQuiet)
         {
-            printBinaryInformation(stderr, impl_->programInfo_);
+            printBinaryInformation(stderr, impl_->programContext_,
+                                   optionsHolder.binaryInfoSettings());
         }
         throw;
     }
-    if (!bMaster)
-    {
-        impl_->bQuiet_ = true;
-    }
-    if (!impl_->bQuiet_)
+    bQuiet |= optionsHolder.shouldBeQuiet();
+    if (!bQuiet)
     {
-        FILE *out = (impl_->bStdOutInfo_ ? stdout : stderr);
-        printBinaryInformation(out, impl_->programInfo_,
-                               impl_->binaryInfoSettings_);
+        FILE *out = optionsHolder.startupInfoFile();
+        printBinaryInformation(out, impl_->programContext_,
+                               optionsHolder.binaryInfoSettings());
         fprintf(out, "\n");
     }
     if (module == NULL)
     {
         return 0;
     }
-    int rc = module->run(argc, argv);
-    if (!impl_->bQuiet_)
+
+    CommandLineModuleSettings settings;
+    module->init(&settings);
+    optionsHolder.adjustFromSettings(settings);
+
+    // Open the debug file.
+    if (optionsHolder.debugLevel() > 0)
+    {
+        std::string filename(impl_->programContext_.programName());
+        if (gmx_node_num() > 1)
+        {
+            filename.append(formatString("%d", gmx_node_rank()));
+        }
+        filename.append(".debug");
+
+        fprintf(stderr, "Will write debug log file: %s\n", filename.c_str());
+        gmx_init_debug(optionsHolder.debugLevel(), filename.c_str());
+    }
+#if defined(HAVE_UNISTD_H) && !defined(GMX_NO_NICE) && !defined(__MINGW32__)
+    // Set the nice level unless disabled in the configuration.
+    if (optionsHolder.niceLevel() != 0)
+    {
+        static bool bNiceSet = false; // Only set it once.
+        if (!bNiceSet)
+        {
+            if (nice(optionsHolder.niceLevel()) == -1)
+            {
+                // Do nothing, but use the return value to avoid warnings.
+            }
+            bNiceSet = true;
+        }
+    }
+#endif
+
+    int rc = 0;
+    if (!(module == impl_->helpModule_ && !bMaster))
+    {
+        rc = module->run(argc, argv);
+    }
+    if (!bQuiet)
     {
         gmx_thanx(stderr);
     }
@@ -695,13 +610,13 @@ int CommandLineModuleManager::run(int argc, char *argv[])
 int CommandLineModuleManager::runAsMainSingleModule(
         int argc, char *argv[], CommandLineModuleInterface *module)
 {
-    ProgramInfo &programInfo = gmx::init(&argc, &argv);
+    CommandLineProgramContext &programContext = gmx::initForCommandLine(&argc, &argv);
     try
     {
-        CommandLineModuleManager manager(&programInfo);
-        manager.impl_->singleModule_ = module;
+        CommandLineModuleManager manager(NULL, &programContext);
+        manager.setSingleModule(module);
         int rc = manager.run(argc, argv);
-        gmx::finalize();
+        gmx::finalizeForCommandLine();
         return rc;
     }
     catch (const std::exception &ex)
@@ -719,4 +634,39 @@ int CommandLineModuleManager::runAsMainCMain(
     return runAsMainSingleModule(argc, argv, &module);
 }
 
+/********************************************************************
+ * CommandLineModuleGroupData
+ */
+
+void CommandLineModuleGroupData::addModule(const char *name,
+                                           const char *description)
+{
+    CommandLineModuleMap::const_iterator moduleIter = allModules_.find(name);
+    GMX_RELEASE_ASSERT(moduleIter != allModules_.end(),
+                       "Non-existent module added to a group");
+    if (description == NULL)
+    {
+        description = moduleIter->second->shortDescription();
+        GMX_RELEASE_ASSERT(description != NULL,
+                           "Module without a description added to a group");
+    }
+    std::string       tag(formatString("%s-%s", binaryName_, name));
+    modules_.push_back(std::make_pair(tag, description));
+}
+
+/********************************************************************
+ * CommandLineModuleGroup
+ */
+
+void CommandLineModuleGroup::addModule(const char *name)
+{
+    impl_->addModule(name, NULL);
+}
+
+void CommandLineModuleGroup::addModuleWithDescription(const char *name,
+                                                      const char *description)
+{
+    impl_->addModule(name, description);
+}
+
 } // namespace gmx