#include "miwm_framework.h"

#include <stdlib.h> // getenv()
#include <sys/stat.h> // mkdir()
#include <sys/types.h> // mkdir()

#include "EPathFinder.h"

namespace miwm {


        std::string homePath( const std::string & append )
        {
                const char * hp = ::getenv( "HOME" );
                static string abspath = string(hp) + EPathFinder::getDirectorySeparator() + ".miwm";
                if( ! EPathFinder::isAccessible( abspath ) )
                {
                        if( 0 != ::mkdir( abspath.c_str(), 0700 ) )
                        {
                                CERR << __FILE__<<":"<<__LINE__<<" error: could not create miwm home directory ["<<abspath<<"]." << std::endl;
                                hp = ::getenv( "TEMP" );
                                abspath = hp ? std::string(hp) : "/";
                        }
                }
                return abspath + append;
        }

        EPropertyList & config()
        {
                static EPropertyList meyers;
                static bool donethat = false;
                if( ! donethat && (donethat=true) )
                {
                        string fname = miwm::homePath() + "/miwm.config";
                        meyers.load( fname );
                        meyers.saveAtDestruction(true);
                        CERR << "config file = ["<<fname<<"]"<<std::endl;
                }
                return meyers;
        }

        ESimpleCLParser & args()
        {
                static ESimpleCLParser meyers;
                return meyers;
        }

        void show_help()
        {
                std::ostream & os = std::cout;

                os << "Command-line arguments:\n" << miwm::args().dumpHelp();
                os << endl;

                return;
        }

        int init( int argc, char ** argv )
        {
                ESimpleCLParser & a = miwm::args();
                a.setHelp( "memcheck", "Integer in the range (1..3), enables memory leak checks." );
                int argcount = a.setArgs( argc, argv );
                return argcount;
        }


}; // namespace miwm
