Esempio n. 1
0
// 初始化命令行参数
BOOL CUpdaterApp::_InitCmdline(int argc, LPTSTR* args)
{
	BOOL bReturn(FALSE);
	CCmdLine cmder;
	if (cmder.SplitLine(__argc, __targv) >= 2)
	{
		if (cmder.HasSwitch(_T("-PID")) && cmder.HasSwitch(_T("-H")))
		{
			m_dwProcessId = (DWORD)_ttoi(cmder.GetSafeArgument(_T("-PID"), 0, _T("0")));
			m_hWindowCtrl = (HWND)_ttoi(cmder.GetSafeArgument(_T("-H"), 0, _T("0")));
			bReturn = TRUE;
		}
		else
		{
			LOG(_T("命令行参数错误!"));
		}
	}
	else
	{
		LOG(_T("未指定命令行参数"));
	}
	return bReturn;
}
void GameComponent::ParseCommandLine( LPTSTR lpCmdLine )
{
	m_CmdLineParse.clear();
	if( _tcscmp( "", lpCmdLine ) != 0 )
	{
		CCmdLine CmdLine;
		CmdLine.SplitLine( lpCmdLine );

		if( CmdLine.HasSwitch( "-multiplier" ) )
		{
			m_iMultiplier = _ttoi( CmdLine.GetSafeArgument( "-multiplier", 0, DEFAULT_Multiplier.c_str() ).c_str() );
			StdString parseLine = _T("Cmd line argument: multiplier\n");
			m_CmdLineParse.push_back(parseLine);
		}

		if( CmdLine.HasSwitch( "-creditstart" ) )
		{
			m_iCreditStart = _ttoi( CmdLine.GetSafeArgument( "-creditstart", 0, DEFAULT_CreditStart.c_str() ).c_str() );
			StdString parseLine = _T("Cmd line argument: creditstart\n");
			m_CmdLineParse.push_back(parseLine);
		}

		if( CmdLine.HasSwitch( "-creditcont" ) )
		{
			m_iCreditCont = _ttoi( CmdLine.GetSafeArgument( "-creditcont", 0, DEFAULT_CreditCont.c_str() ).c_str() );
			StdString parseLine = _T("Cmd line argument: creditcont\n");
			m_CmdLineParse.push_back(parseLine);
		}

		if( CmdLine.HasSwitch( "-freeplay" ) )
		{
			m_bFreeplay = !(DEFAULT_Freeplay);
			StdString parseLine = _T("Cmd line argument: freeplay\n");
			m_CmdLineParse.push_back(parseLine);
		}
		else
		{
			m_bFreeplay = DEFAULT_Freeplay;
		}

		if( CmdLine.HasSwitch( "-time" ) )
		{
			m_iPlayTime = _ttoi( CmdLine.GetSafeArgument( "-time", 0, DEFAULT_PlayTime.c_str() ).c_str() );
			StdString parseLine = _T("Cmd line argument: time\n");
			m_CmdLineParse.push_back(parseLine);
		}

		if( CmdLine.HasSwitch( "-contime" ) )
		{
			m_iContTime = _ttoi( CmdLine.GetSafeArgument( "-contime", 0, DEFAULT_ContTime.c_str() ).c_str() );
			StdString parseLine = _T("Cmd line argument: contime\n");
			m_CmdLineParse.push_back(parseLine);
		}

		if( CmdLine.HasSwitch( "-language" ) )
		{
			m_iLanguage = _ttoi( CmdLine.GetSafeArgument( "-language", 0, DEFAULT_ContTime.c_str() ).c_str() );
			StdString parseLine = _T("Cmd line argument: language\n");
			m_CmdLineParse.push_back(parseLine);
		}

		if( CmdLine.HasSwitch( "-violence" ) )
		{
			m_iViolence = _ttoi( CmdLine.GetSafeArgument( "-violence", 0, DEFAULT_Violence.c_str() ).c_str() );
			StdString parseLine = _T("Cmd line argument: violence\n");
			m_CmdLineParse.push_back(parseLine);
		}

		// in free play mode some things need to be zeroed out
		if (m_bFreeplay)
		{
			m_iCreditStart = 0;
			m_iCreditCont = 0;
			m_iMultiplier = 0;			
		}
	}
}
Esempio n. 3
0
int main(int argc, char**argv)
#endif
{
#if defined WIN32
#ifndef _DEBUG
    CreateMutexA(0, FALSE, "Local\\Domoticz");
    if(GetLastError() == ERROR_ALREADY_EXISTS) {
        MessageBox(HWND_DESKTOP,"Another instance of Domoticz is already running!","Domoticz",MB_OK);
        return 1;
    }
#endif //_DEBUG
    bool bStartWebBrowser = true;
    RedirectIOToConsole();
#endif //WIN32

    szStartupFolder = "";
    szWWWFolder = "";
    szWebRoot = "";

    CCmdLine cmdLine;

    // parse argc,argv
#if defined WIN32
    cmdLine.SplitLine(__argc, __argv);
#else
    cmdLine.SplitLine(argc, argv);
    //ignore pipe errors
    signal(SIGPIPE, SIG_IGN);
#endif

    if (cmdLine.HasSwitch("-log"))
    {
        if (cmdLine.GetArgumentCount("-log") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify an output log file");
            return 1;
        }
        logfile = cmdLine.GetSafeArgument("-log", 0, "domoticz.log");
        _log.SetOutputFile(logfile.c_str());
    }
    if (cmdLine.HasSwitch("-loglevel"))
    {
        if (cmdLine.GetArgumentCount("-loglevel") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify logfile output level (0=All, 1=Status+Error, 2=Error)");
            return 1;
        }
        int Level = atoi(cmdLine.GetSafeArgument("-loglevel", 0, "").c_str());
        _log.SetVerboseLevel((_eLogFileVerboseLevel)Level);
    }
    if (cmdLine.HasSwitch("-notimestamps"))
    {
        _log.EnableLogTimestamps(false);
    }

    if (cmdLine.HasSwitch("-approot"))
    {
        if (cmdLine.GetArgumentCount("-approot") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a APP root path");
            return 1;
        }
        std::string szroot = cmdLine.GetSafeArgument("-approot", 0, "");
        if (szroot.size() != 0)
            szStartupFolder = szroot;
    }

    if (szStartupFolder == "")
    {
#if !defined WIN32
        char szStartupPath[255];
        getExecutablePathName((char*)&szStartupPath,255);
        szStartupFolder=szStartupPath;
        if (szStartupFolder.find_last_of('/')!=std::string::npos)
            szStartupFolder=szStartupFolder.substr(0,szStartupFolder.find_last_of('/')+1);
#else
#ifndef _DEBUG
        char szStartupPath[255];
        char * p;
        GetModuleFileName(NULL, szStartupPath, sizeof(szStartupPath));
        p = szStartupPath + strlen(szStartupPath);

        while (p >= szStartupPath && *p != '\\')
            p--;

        if (++p >= szStartupPath)
            *p = 0;
        szStartupFolder=szStartupPath;
        size_t start_pos = szStartupFolder.find("\\Release\\");
        if(start_pos != std::string::npos) {
            szStartupFolder.replace(start_pos, 9, "\\domoticz\\");
            _log.Log(LOG_STATUS,"%s",szStartupFolder.c_str());
        }
#endif
#endif
    }
    GetAppVersion();
    _log.Log(LOG_STATUS, "Domoticz V%s (c)2012-%d GizMoCuz", szAppVersion.c_str(), ActYear);
    _log.Log(LOG_STATUS, "Build Hash: %s, Date: %s", szAppHash.c_str(), szAppDate.c_str());

#if !defined WIN32
    //Check if we are running on a RaspberryPi
    std::string sLine = "";
    std::ifstream infile;

    infile.open("/proc/cpuinfo");
    if (infile.is_open())
    {
        while (!infile.eof())
        {
            getline(infile, sLine);
            if (
                (sLine.find("BCM2708")!=std::string::npos)||
                (sLine.find("BCM2709")!=std::string::npos)
            )
            {
                //Core temperature of BCM2835 SoC
                _log.Log(LOG_STATUS,"System: Raspberry Pi");
                szInternalTemperatureCommand="/opt/vc/bin/vcgencmd measure_temp";
                bHasInternalTemperature=true;
                break;
            }
        }
        infile.close();
    }
    if (!bHasInternalTemperature)
    {
        if (file_exist("/sys/devices/platform/sunxi-i2c.0/i2c-0/0-0034/temp1_input"))
        {
            _log.Log(LOG_STATUS,"System: Cubieboard/Cubietruck");
            szInternalTemperatureCommand="cat /sys/devices/platform/sunxi-i2c.0/i2c-0/0-0034/temp1_input | awk '{ printf (\"temp=%0.2f\\n\",$1/1000); }'";
            bHasInternalTemperature = true;
        }
        else if (file_exist("/sys/devices/virtual/thermal/thermal_zone0/temp"))
        {
            //_log.Log(LOG_STATUS,"System: ODroid");
            szInternalTemperatureCommand="cat /sys/devices/virtual/thermal/thermal_zone0/temp | awk '{ printf (\"temp=%0.2f\\n\",$1/1000); }'";
            bHasInternalTemperature = true;
        }
    }
    if (file_exist("/sys/class/power_supply/ac/voltage_now"))
    {
        szInternalVoltageCommand = "cat /sys/class/power_supply/ac/voltage_now | awk '{ printf (\"volt=%0.2f\\n\",$1/1000000); }'";
        bHasInternalVoltage = true;
    }
    if (file_exist("/sys/class/power_supply/ac/current_now"))
    {
        szInternalCurrentCommand = "cat /sys/class/power_supply/ac/current_now | awk '{ printf (\"curr=%0.2f\\n\",$1/1000000); }'";
        bHasInternalCurrent = true;
    }
    _log.Log(LOG_STATUS,"Startup Path: %s", szStartupFolder.c_str());
#endif

    szWWWFolder = szStartupFolder + "www";

    if ((cmdLine.HasSwitch("-h")) || (cmdLine.HasSwitch("--help")) || (cmdLine.HasSwitch("/?")))
    {
        _log.Log(LOG_NORM, szHelp);
        return 0;
    }

    szUserDataFolder=szStartupFolder;
    if (cmdLine.HasSwitch("-userdata"))
    {
        if (cmdLine.GetArgumentCount("-userdata") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a path for user data to be stored");
            return 1;
        }
        std::string szroot = cmdLine.GetSafeArgument("-userdata", 0, "");
        if (szroot.size() != 0)
            szUserDataFolder = szroot;
    }

    if (cmdLine.HasSwitch("-startupdelay"))
    {
        if (cmdLine.GetArgumentCount("-startupdelay") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a startupdelay");
            return 1;
        }
        int DelaySeconds = atoi(cmdLine.GetSafeArgument("-startupdelay", 0, "").c_str());
        _log.Log(LOG_STATUS, "Startup delay... waiting %d seconds...", DelaySeconds);
        sleep_seconds(DelaySeconds);
    }

    if (cmdLine.HasSwitch("-wwwbind"))
    {
        if (cmdLine.GetArgumentCount("-wwwbind") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify an address");
            return 1;
        }
        std::string wwwbind = cmdLine.GetSafeArgument("-wwwbind", 0, "0.0.0.0");
        m_mainworker.SetWebserverAddress(wwwbind);
    }

    if (cmdLine.HasSwitch("-www"))
    {
        if (cmdLine.GetArgumentCount("-www") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a port");
            return 1;
        }
        std::string wwwport = cmdLine.GetSafeArgument("-www", 0, "8080");
        if (wwwport == "0")
            wwwport.clear();//HTTP server disabled
        m_mainworker.SetWebserverPort(wwwport);
    }
#ifdef NS_ENABLE_SSL
    if (cmdLine.HasSwitch("-sslwww"))
    {
        if (cmdLine.GetArgumentCount("-sslwww") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a port");
            return 1;
        }
        std::string wwwport = cmdLine.GetSafeArgument("-sslwww", 0, "443");
        if (wwwport == "0")
            wwwport.clear();//HTTPS server disabled
        m_mainworker.SetSecureWebserverPort(wwwport);
    }
    if (cmdLine.HasSwitch("-sslcert"))
    {
        if (cmdLine.GetArgumentCount("-sslcert") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify the file path");
            return 1;
        }
        std::string ca_cert = cmdLine.GetSafeArgument("-sslcert", 0, "./server_cert.pem");
        m_mainworker.SetSecureWebserverCert(ca_cert);
    }
    if (cmdLine.HasSwitch("-sslpass"))
    {
        if (cmdLine.GetArgumentCount("-sslpass") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a passphrase for your certificate file");
            return 1;
        }
        std::string ca_passphrase = cmdLine.GetSafeArgument("-sslpass", 0, "");
        m_mainworker.SetSecureWebserverPass(ca_passphrase);
    }
#endif
    if (cmdLine.HasSwitch("-nowwwpwd"))
    {
        m_mainworker.m_bIgnoreUsernamePassword = true;
    }
    if (cmdLine.HasSwitch("-nocache"))
    {
        g_bDontCacheWWW = true;
    }
    std::string dbasefile = szUserDataFolder + "domoticz.db";
#ifdef WIN32
#ifndef _DEBUG
    if (!IsUserAnAdmin())
    {
        char szPath[MAX_PATH];
        HRESULT hr = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
        if (SUCCEEDED(hr))
        {
            std::string sPath = szPath;
            sPath += "\\Domoticz";

            DWORD dwAttr = GetFileAttributes(sPath.c_str());
            BOOL bDirExists = (dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY));
            if (!bDirExists)
            {
                BOOL bRet = CreateDirectory(sPath.c_str(), NULL);
                if (bRet == FALSE) {
                    MessageBox(0, "Error creating Domoticz directory in program data folder (%ProgramData%)!!", "Error:", MB_OK);
                }
            }
            sPath += "\\domoticz.db";
            dbasefile = sPath;
        }
    }
#endif
#endif

    if (cmdLine.HasSwitch("-dbase"))
    {
        if (cmdLine.GetArgumentCount("-dbase") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a Database Name");
            return 1;
        }
        dbasefile = cmdLine.GetSafeArgument("-dbase", 0, "domoticz.db");
    }
    m_sql.SetDatabaseName(dbasefile);

    if (cmdLine.HasSwitch("-wwwroot"))
    {
        if (cmdLine.GetArgumentCount("-wwwroot") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a WWW root path");
            return 1;
        }
        std::string szroot = cmdLine.GetSafeArgument("-wwwroot", 0, "");
        if (szroot.size() != 0)
            szWWWFolder = szroot;
    }

    if (cmdLine.HasSwitch("-webroot"))
    {
        if (cmdLine.GetArgumentCount("-webroot") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a web root path");
            return 1;
        }
        std::string szroot = cmdLine.GetSafeArgument("-webroot", 0, "");
        if (szroot.size() != 0)
            szWebRoot = szroot;
    }

    if (cmdLine.HasSwitch("-verbose"))
    {
        if (cmdLine.GetArgumentCount("-verbose") != 1)
        {
            _log.Log(LOG_ERROR, "Please specify a verbose level");
            return 1;
        }
        int Level = atoi(cmdLine.GetSafeArgument("-verbose", 0, "").c_str());
        m_mainworker.SetVerboseLevel((eVerboseLevel)Level);
    }
#if defined WIN32
    if (cmdLine.HasSwitch("-nobrowser"))
    {
        bStartWebBrowser = false;
    }
    //Init WinSock
    WSADATA data;
    WORD version;

    version = (MAKEWORD(2, 2));
    int ret = WSAStartup(version, &data);
    if (ret != 0)
    {
        ret = WSAGetLastError();

        if (ret == WSANOTINITIALISED)
        {
            _log.Log(LOG_ERROR, "Error: Winsock could not be initialized!");
        }
    }
    CoInitializeEx(0, COINIT_MULTITHREADED);
    CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
#endif
#ifndef WIN32
    if (cmdLine.HasSwitch("-daemon"))
    {
        g_bRunAsDaemon = true;
    }

    std::string daemonname = DAEMON_NAME;
    if (cmdLine.HasSwitch("-daemonname"))
    {
        daemonname = cmdLine.GetSafeArgument("-daemonname", 0, DAEMON_NAME);
    }

    std::string pidfile = PID_FILE;
    if (cmdLine.HasSwitch("-pidfile"))
    {
        pidfile = cmdLine.GetSafeArgument("-pidfile", 0, PID_FILE);
    }

    if ((g_bRunAsDaemon)||(g_bUseSyslog))
    {
        setlogmask(LOG_UPTO(LOG_INFO));
        openlog(daemonname.c_str(), LOG_CONS | LOG_PERROR, LOG_USER);

        syslog(LOG_INFO, "Domoticz is starting up....");
    }

    if (g_bRunAsDaemon)
    {
        /* Deamonize */
        daemonize(szStartupFolder.c_str(), pidfile.c_str());
    }
    if ((g_bRunAsDaemon) || (g_bUseSyslog))
    {
        syslog(LOG_INFO, "Domoticz running...");
    }
#endif

    if (!g_bRunAsDaemon)
    {
        signal(SIGINT, signal_handler);
        signal(SIGTERM, signal_handler);
    }

    if (!m_mainworker.Start())
    {
        return 1;
    }
    m_StartTime = time(NULL);

    /* now, lets get into an infinite loop of doing nothing. */
#if defined WIN32
#ifndef _DEBUG
    RedirectIOToConsole();	//hide console
#endif
    InitWindowsHelper(hInstance, hPrevInstance, nShowCmd, m_mainworker.GetWebserverAddress(), atoi(m_mainworker.GetWebserverPort().c_str()), bStartWebBrowser);
    MSG Msg;
    while (!g_bStopApplication)
    {
        if (PeekMessage(&Msg, NULL, 0, 0, PM_NOREMOVE))
        {
            if (GetMessage(&Msg, NULL, 0, 0) > 0)
            {
                TranslateMessage(&Msg);
                DispatchMessage(&Msg);
            }
        }
        else
            sleep_milliseconds(100);
    }
    TrayMessage(NIM_DELETE, NULL);
#else
    while ( !g_bStopApplication )
    {
        sleep_seconds(1);
    }
#endif
    _log.Log(LOG_STATUS, "Closing application!...");
    fflush(stdout);
    _log.Log(LOG_STATUS, "Stopping worker...");
    try
    {
        m_mainworker.Stop();
    }
    catch (...)
    {

    }
#ifndef WIN32
    if (g_bRunAsDaemon)
    {
        syslog(LOG_INFO, "Domoticz stopped...");
        daemonShutdown();

        // Delete PID file
        remove(pidfile.c_str());
    }
#else
    // Release WinSock
    WSACleanup();
    CoUninitialize();
#endif
    return 0;
}
Esempio n. 4
0
/*! The main entrance to the program. */
int main(int argc, char * argv[])
{
	try
	{
		// Parse the command line arguments.
		CCmdLine cmdLine;
		if (cmdLine.SplitLine(argc, argv) < 1)
		{
			show_help();
			exit(-1);
		}

		string execId = cmdLine.GetArgument("-execid", 0);
		string celFile = cmdLine.GetSafeArgument("-cel", 0, "");
		string inFile = cmdLine.GetArgument("-in", 0);
		string outFile = cmdLine.GetArgument("-out", 0);
		string arrayType = cmdLine.GetArgument("-arrayType", 0);
		string algName = cmdLine.GetArgument("-algName", 0);
		string algVersion = cmdLine.GetArgument("-algVersion", 0);
		string programName = cmdLine.GetArgument("-programName", 0);
		string programVersion = cmdLine.GetArgument("-programVersion", 0);
		string programCompany = cmdLine.GetArgument("-programCompany", 0);

		vector<string> paramNames;
		int n = cmdLine.GetArgumentCount("-paramNames");
		for (int i=0; i<n; i++)
			paramNames.push_back(cmdLine.GetArgument("-paramNames", i));

		vector<string> paramValues;
		n = cmdLine.GetArgumentCount("-paramValues");
		for (int i=0; i<n; i++)
			paramValues.push_back(cmdLine.GetArgument("-paramValues", i));

		vector<string> sumNames;
		n = cmdLine.GetArgumentCount("-sumNames");
		for (int i=0; i<n; i++)
			sumNames.push_back(cmdLine.GetArgument("-sumNames", i));

		vector<string> sumValues;
		n = cmdLine.GetArgumentCount("-sumValues");
		for (int i=0; i<n; i++)
			sumValues.push_back(cmdLine.GetArgument("-sumValues", i));

		// Read the TSV input file
		list<string> names;
		list<float> quantifications;
		ReadData(inFile, names, quantifications);

		// Create the CHP file.
		CreateFileWithHeader(execId, celFile, outFile, names, algName, algVersion, arrayType,
			programName, programVersion, programCompany, paramNames, paramValues, sumNames, sumValues);
		UpdateQuantifications(outFile, quantifications);
	}
	catch (string s)
	{
		cout << s << endl;
		show_help();
	}
	catch (int e)
	{
		cout << "Invalid argument" << endl;
		show_help();
	}
	catch (...)
	{
		cout << "Unknown error" << endl;
		show_help();
	}
	return 0;
}
Esempio n. 5
0
int main(int argc, char**argv)
#endif
{
#if defined WIN32
	CreateMutexA(0, FALSE, "Local\\Domoticz"); 
    if(GetLastError() == ERROR_ALREADY_EXISTS) { 
		MessageBox(HWND_DESKTOP,"Another instance of Domoticz is already running!","Domoticz",MB_OK);
        return -1; 
	}
	bool bStartWebBrowser=true;
	RedirectIOToConsole();
#endif

	szStartupFolder="";
	szWWWFolder="";
#if !defined WIN32
	char szStartupPath[255];
	getExecutablePathName((char*)&szStartupPath,255);
	szStartupFolder=szStartupPath;
	if (szStartupFolder.find_last_of('/')!=std::string::npos)
		szStartupFolder=szStartupFolder.substr(0,szStartupFolder.find_last_of('/')+1);
#else
	#ifndef _DEBUG
		char szStartupPath[255];
		char * p;
		GetModuleFileName(NULL, szStartupPath, sizeof(szStartupPath));
		p = szStartupPath + strlen(szStartupPath);

		while(p >= szStartupPath && *p != '\\')
			p--;

		if(++p >= szStartupPath)
			*p = 0;
		szStartupFolder=szStartupPath;
		size_t start_pos = szStartupFolder.find("\\Release\\");
		if(start_pos != std::string::npos) {
			szStartupFolder.replace(start_pos, 9, "\\domoticz\\");
			_log.Log(LOG_NORM,"%s",szStartupFolder.c_str());
		}
	#endif
#endif
	GetAppVersion();
	_log.Log(LOG_NORM,"Domoticz V%s (c)2012-2014 GizMoCuz",szAppVersion.c_str());

#if !defined WIN32
	//Check if we are running on a RaspberryPi
	std::string sLine = "";
	std::ifstream infile;

	infile.open("/proc/cpuinfo");
	if (infile.is_open())
	{
		while (!infile.eof())
		{
			getline(infile, sLine);
			if (sLine.find("BCM2708")!=std::string::npos)
			{
				_log.Log(LOG_NORM,"System: Raspberry Pi");
				bIsRaspberryPi=true;
				break;
			}
		}
		infile.close();
	}
	_log.Log(LOG_NORM,"Startup Path: %s", szStartupFolder.c_str());
#endif

	szWWWFolder=szStartupFolder+"www";

	CCmdLine cmdLine;

	// parse argc,argv 
#if defined WIN32
	cmdLine.SplitLine(__argc, __argv);
#else
	cmdLine.SplitLine(argc, argv);
#endif

	if ((cmdLine.HasSwitch("-h"))||(cmdLine.HasSwitch("--help"))||(cmdLine.HasSwitch("/?")))
	{
		_log.Log(LOG_NORM,szHelp);
		return 0;
	}

	if (cmdLine.HasSwitch("-startupdelay"))
	{
		if (cmdLine.GetArgumentCount("-startupdelay")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a startupdelay");
			return 0;
		}
		int DelaySeconds=atoi(cmdLine.GetSafeArgument("-startupdelay",0,"").c_str());
		_log.Log(LOG_NORM,"Startup delay... waiting %d seconds...",DelaySeconds);
		sleep_seconds(DelaySeconds);
	}

	if (cmdLine.HasSwitch("-www"))
	{
		if (cmdLine.GetArgumentCount("-www")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a port");
			return 0;
		}
		std::string wwwport=cmdLine.GetSafeArgument("-www",0,"8080");
		_mainworker.SetWebserverPort(wwwport);
	}
	if (cmdLine.HasSwitch("-nowwwpwd"))
	{
		_mainworker.m_bIgnoreUsernamePassword=true;
	}

	std::string dbasefile=szStartupFolder + "domoticz.db";
#ifdef WIN32
	if (!IsUserAnAdmin())
	{
		char szPath[MAX_PATH];
		HRESULT hr = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
		if (SUCCEEDED(hr))
		{
			std::string sPath=szPath;
			sPath+="\\Domoticz";

			DWORD dwAttr = GetFileAttributes(sPath.c_str());
			BOOL bDirExists=(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY));
			if (!bDirExists)
			{
				BOOL bRet=CreateDirectory(sPath.c_str(),NULL);
				if (bRet==FALSE) {
					MessageBox(0,"Error creating Domoticz directory in program data folder (%ProgramData%)!!","Error:",MB_OK);
				}
			}
			sPath+="\\domoticz.db";
			dbasefile=sPath;
		}
	}
#endif

	if (cmdLine.HasSwitch("-dbase"))
	{
		if (cmdLine.GetArgumentCount("-dbase")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a Database Name");
			return 0;
		}
		dbasefile=cmdLine.GetSafeArgument("-dbase",0,"domoticz.db");
	}
	_mainworker.m_sql.SetDatabaseName(dbasefile);

	if (cmdLine.HasSwitch("-wwwroot"))
	{
		if (cmdLine.GetArgumentCount("-wwwroot")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a WWW root path");
			return 0;
		}
		std::string szroot=cmdLine.GetSafeArgument("-wwwroot",0,"");
		if (szroot.size()!=0)
			szWWWFolder=szroot;
	}

	if (cmdLine.HasSwitch("-verbose"))
	{
		if (cmdLine.GetArgumentCount("-verbose")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify a verbose level");
			return 0;
		}
		int Level=atoi(cmdLine.GetSafeArgument("-verbose",0,"").c_str());
		_mainworker.SetVerboseLevel((eVerboseLevel)Level);
	}
#if defined WIN32
	if (cmdLine.HasSwitch("-nobrowser"))
	{
		bStartWebBrowser=false;
	}
#endif
	if (cmdLine.HasSwitch("-log"))
	{
		if (cmdLine.GetArgumentCount("-log")!=1)
		{
			_log.Log(LOG_ERROR,"Please specify an output log file");
			return 0;
		}
		std::string logfile=cmdLine.GetSafeArgument("-log",0,"domoticz.log");
		_log.SetOutputFile(logfile.c_str());
	}

	if (!_mainworker.Start())
	{
		return 0;
	}

	signal(SIGINT, catch_intterm); 
	signal(SIGTERM,catch_intterm);
	
	/* now, lets get into an infinite loop of doing nothing. */

#if defined WIN32
#ifndef _DEBUG
	RedirectIOToConsole();	//hide console
#endif
	InitWindowsHelper(hInstance,hPrevInstance,nShowCmd,DQuitFunction,atoi(_mainworker.GetWebserverPort().c_str()),bStartWebBrowser);
	MSG Msg;
	while(GetMessage(&Msg, NULL, 0, 0) > 0)
	{
		TranslateMessage(&Msg);
		DispatchMessage(&Msg);
	}
#else
	for ( ;; )
		sleep_seconds(1);
#endif
	return 0;
}
/*! The main entrance to the program. */
int main(int argc, char * argv[])
{
	try
	{
		// Parse the command line arguments.
		CCmdLine cmdLine;
		if (cmdLine.SplitLine(argc, argv) < 1)
		{
			show_help();
			exit(-1);
		}

		string execId = cmdLine.GetArgument("-execid", 0);
		string celFile = cmdLine.GetSafeArgument("-cel", 0, "");
		string inFile = cmdLine.GetArgument("-in", 0);
		string outFile = cmdLine.GetArgument("-out", 0);
		string arrayType = cmdLine.GetArgument("-arrayType", 0);
		string algName = cmdLine.GetArgument("-algName", 0);
		string algVersion = cmdLine.GetArgument("-algVersion", 0);
		string programName = cmdLine.GetArgument("-programName", 0);
		string programVersion = cmdLine.GetArgument("-programVersion", 0);
		string programCompany = cmdLine.GetArgument("-programCompany", 0);

		vector<string> colNames;
		int n = cmdLine.GetArgumentCount("-colNames");
		for (int i=0; i<n; i++)
			colNames.push_back(cmdLine.GetArgument("-colNames", i));

		vector<string> colTypes;
		n = cmdLine.GetArgumentCount("-colTypes");
		for (int i=0; i<n; i++)
			colTypes.push_back(cmdLine.GetArgument("-colTypes", i));

		vector<string> paramNames;
		n = cmdLine.GetArgumentCount("-paramNames");
		for (int i=0; i<n; i++)
			paramNames.push_back(cmdLine.GetArgument("-paramNames", i));

		vector<string> paramValues;
		n = cmdLine.GetArgumentCount("-paramValues");
		for (int i=0; i<n; i++)
			paramValues.push_back(cmdLine.GetArgument("-paramValues", i));

		vector<string> sumNames;
		n = cmdLine.GetArgumentCount("-sumNames");
		for (int i=0; i<n; i++)
			sumNames.push_back(cmdLine.GetArgument("-sumNames", i));

		vector<string> sumValues;
		n = cmdLine.GetArgumentCount("-sumValues");
		for (int i=0; i<n; i++)
			sumValues.push_back(cmdLine.GetArgument("-sumValues", i));

		vector<string> extraNames;
		n = cmdLine.GetArgumentCount("-extraNames");
		for (int i=0; i<n; i++)
			extraNames.push_back(cmdLine.GetArgument("-extraNames", i));

		vector<string> extraValues;
		n = cmdLine.GetArgumentCount("-extraValues");
		for (int i=0; i<n; i++)
			extraValues.push_back(cmdLine.GetArgument("-extraValues", i));

		// Read the TSV input file
		int maxProbeSetNameLength = 0;

		// data collection is no longer used, so we have ReadData return the row count so that we can pass it into
		// CreateFileWithHeader call
		unsigned long rowCount = ReadData(inFile, maxProbeSetNameLength);

		// Create the CHP file.
		// Creates the header
		CreateFileWithHeader(execId, celFile, outFile, colNames, colTypes, rowCount, maxProbeSetNameLength,
			algName, algVersion, arrayType, programName, programVersion, programCompany, paramNames, paramValues,
			sumNames, sumValues, extraNames, extraValues);

		// add the body (data)
		AddFileBody(inFile,outFile, maxProbeSetNameLength, colTypes);
	}
	catch (string s)
	{
		cout << s << endl;
		show_help();
	}
	catch (int e)
	{
		cout << "Invalid argument" << endl;
		show_help();
	}
	catch (...)
	{
		cout << "Unknown error" << endl;
		show_help();
	}
	return 0;
}
int main(int argc, char* argv[])
{
        // Read in parameters from command line.
        CCmdLine cmdLine;

        if(cmdLine.SplitLine(argc, argv) < 3)
        {
                cerr << "Usage: ./gittar -m consensus_motif -e log_ratio_file -s promoter_sequence" << endl;
		cerr << "Additional parameters:" << endl;
		cerr << "[-mis] mismatches to consensus motif(Default=1)" << endl;
		cerr << "[-a] annotation file" << endl;
		cerr << "[-o] output(gene_and_other_info PSFM)" << endl;
		cerr << "[-v] verbose mode" << endl;
		cerr << "[-h] hyperprio parameters(hyper_samples=50 mu=2.0 sigma^2=1.0 flanking_length=7" << endl;
		cerr << "[-n] DO NOT use prio information(overide hyperprio parameters)" << endl;
		cerr << "[-g] Gibbs sampler parameters(starting_point=10 burn-in=100 window=100)" << endl;
		cerr << "[-misc] Miscellaneous parameters(stds_of_intial_target=4 skip_core_region=0 random_background=0 threshold_for_target=0.5 stds_enfore=1)" << endl;

                return 1;
        }

        string m, e, s;
        try
        {
                m = cmdLine.GetArgument("-m", 0);
                e = cmdLine.GetArgument("-e", 0);
                s = cmdLine.GetArgument("-s", 0);
        }
        catch(int)
        {
                cerr << "Wrong arguments!" << endl;
                return 1;
        }
	string mis = cmdLine.GetSafeArgument("-mis", 0, "1");	// mismatches.
	unsigned misallow = atoi(mis.data());
	string a = cmdLine.GetSafeArgument("-a", 0, "");	// gene annotation file.
	string o1 = cmdLine.GetSafeArgument("-o", 0, "");	// output gene and other information.
	string o2 = cmdLine.GetSafeArgument("-o", 1, "");	// output PSFM.
	
	// Hyper-prio parameters.
	HypePrio hypePrio;
	string v = cmdLine.GetSafeArgument("-h", 0, "50");
	hypePrio.V = atoi(v.data());
	string mu = cmdLine.GetSafeArgument("-h", 1, "2.0");
	hypePrio.MU = atof(mu.data());
	string sigma2 = cmdLine.GetSafeArgument("-h", 2, "1.0");
	hypePrio.SIGMA_2 = atof(sigma2.data());
	string flanking = cmdLine.GetSafeArgument("-h", 3, "7");
	hypePrio.FLANKING = atoi(flanking.data());

	// DO NOT use prior information? 
	if(cmdLine.HasSwitch("-n"))
		hypePrio.V = 1;

	// Gibbs-sampler parameters.
	string sta_pnt = cmdLine.GetSafeArgument("-g", 0, "10");
	STA_PNT = atoi(sta_pnt.data());
	string burn_in = cmdLine.GetSafeArgument("-g", 1, "100");
	BURN_IN = atoi(burn_in.data());
	string window = cmdLine.GetSafeArgument("-g", 2, "100");
	WINDOW = atoi(window.data());
 
	// Miscellaneous parameters.
	string iniv = cmdLine.GetSafeArgument("-misc", 0, "4");
	INIV = atoi(iniv.data());
	string skipcore	= cmdLine.GetSafeArgument("-misc", 1, "0");
	SKIPCORE = atoi(skipcore.data());
	string randbg = cmdLine.GetSafeArgument("-misc", 2, "0");
	RANDBG = atoi(randbg.data());
	VERBOSE = cmdLine.HasSwitch("-v");	// verbose mode switch.


	// Load data into memory.
	string motifSeq; // string of motif sequence.
	Expr expr; // hash table of expression values.
	Seq seq; // hash table of sequences.
	GeneAnno geneAnno; // hash table of gene annotation info.

	if(VERBOSE)
		cout << "Loading...motif...expression...sequence..." << endl;
	if(load_data(m, e, s, a, motifSeq, expr, seq, geneAnno)) // load data.
	{
		cerr << "Error occurs during data loading!" << endl;
		return 1;
	}
	if(VERBOSE)
		cout << "Data load complete!" << endl;

	// Normalize expression levels.
	double bkm = mean(expr);
	double bkstd = stnd(expr, bkm);
	if(VERBOSE)
		cout << "All gene mean: " << bkm << ", standard deviation: " << bkstd << endl;

	// Find all genes containing the motif with mismatch.
	VGene vGene;
	motifgene(motifSeq, hypePrio.FLANKING, expr, seq, misallow, vGene);
	if(VERBOSE)
		cout << "Total genes identified: " << vGene.size() << endl;
		
	// Calculate pseudo-count for DNA bases among all sequences.
	double dnaPor[4];
	sudocnt(seq, dnaPor);
	if(VERBOSE)
	{
		cout << "DNA bases portion in all sequences." << endl;
		cout << "A: " << dnaPor[0] << endl;
		cout << "C: " << dnaPor[1] << endl;
		cout << "G: " << dnaPor[2] << endl;
		cout << "T: " << dnaPor[3] << endl;
	}
				
	// Gibbs sampler starts from here...
	double tPSFM[4][40], nPSFM[4][40]; // target and non-target PSFM.
	double mTarget, s2Target;
	SST eLen = motifSeq.length() + 2*hypePrio.FLANKING;
	setzero(tPSFM, 4, (unsigned)eLen);
	setzero(nPSFM, 4, (unsigned)eLen);
	mTarget = s2Target = 0.0;
	for(unsigned i = 0; i < STA_PNT; i++)
	{
		// Generate candidate genes' initial labels.
		genlbl(vGene, bkm, bkstd);

		// Use Gibbs Sampler to calculate the estimated labels.
		if(VERBOSE)
			cout << "Gibbs sampler starting..." << endl;
		double mTarget_, s2Target_;
		double tPSFM_[4][40], nPSFM_[4][40];
		/*	
			Here go the parameters information: 
			vGene: Information about all genes that contain motif.
			dnaPor: DNA pseudo-count.
			seq: Promoter sequences for all genes.
			mVal: background expression mean.
			sVal: background expression std.
		*/
		int iter;
		iter = gsamp(vGene, mTarget_, s2Target_, tPSFM_, nPSFM_, misallow, dnaPor, motifSeq, seq, bkm, bkstd, hypePrio);
		if(VERBOSE)
			cout << "Gibbs sampler stops with " << iter << " iterations." << endl;
		mTarget += mTarget_;
		s2Target += s2Target_;
		add2mat(tPSFM, tPSFM, tPSFM_, (unsigned)eLen);
		add2mat(nPSFM, nPSFM, nPSFM_, (unsigned)eLen);
		if(VERBOSE)
		{
			cout << "Target genes in last iteration: " << ntar(vGene) << endl;
			cout << "Non-target genes in last iteration: " << nnon(vGene) << endl;
		}
		sum_iter(i, vGene);
	}
	// Summarize the results from different starting points.
	avg_iter(vGene);
	unsigned nTar = ntar(vGene, true);
	unsigned nNon = nnon(vGene, true);
	mTarget /= STA_PNT;
	s2Target /= STA_PNT;
	normat(tPSFM, (unsigned)eLen, STA_PNT);
	normat(nPSFM, (unsigned)eLen, STA_PNT);
		
	// Write results into files.
	if(VERBOSE)
		cout << "Writing results into files..." << endl;
	time_t time_tag = time(NULL);
	if(o2 == "")
	{
		ostringstream logstream;
		logstream << time_tag << "_" << motifSeq << "_mis" << misallow << ".log";
		o2 = logstream.str();
	}

	// PSFMs and profile ratios.	
	if(write_log(o2, (unsigned)eLen, tPSFM, nPSFM) != 0)
		cerr << "Writing matrices information failed!" << endl;
	else if(VERBOSE)
		cout << "PSFMs and profile ratios write complete!" << endl;

	// Re-calculate binding site according to the averaged PSFM.
	map<string, string> mbindloc;	// A map to store all binding sites of each gene.
	for(unsigned i = 0; i < vGene.size(); i++)
		mbindloc[vGene[i].name] = bindsite(vGene[i], vGene[i].target, seq[vGene[i].name], tPSFM, nPSFM, hypePrio.FLANKING);

	// Write genes information.
	// Sort genes according to their probabilities and expression values.
	sort(vGene.begin(), vGene.end(), cmp);
	if(o1 == "")
	{
		ostringstream infostream;
		infostream << time_tag << "_" << motifSeq << "_mis" << misallow << ".info";
		o1 = infostream.str();
	}
	if(write_info(o1, vGene, geneAnno, mTarget, sqrt(s2Target), bkm, bkstd, 
		(unsigned)seq.size(), nTar, nNon, hypePrio, motifSeq, mbindloc) != 0)
		cerr << "Writing genes information failed!" << endl;
	else if(VERBOSE)
	{
		cout << "Genes information write complete!" << endl;
		cout << "Finished!" << endl;
	}
	
	return 0;

}
Esempio n. 8
0
int
P300ClassifierMain( int argc, char **argv, QApplication& app )
{
  ConfigDialog dialog;

  CCmdLine    cmdLine;
  QString     arg_TrainingDataFiles;
  QString     arg_TestingDataFiles;
  QString     arg_inicfg;
  QStringList arg_TrainingDataFilesList;
  QStringList arg_TestingDataFilesList;
  bool        barg_TrainingDataFiles;
  bool        barg_TestingDataFiles;
  bool        barg_inicfg;

  cmdLine.SplitLine(argc, argv);

  barg_TrainingDataFiles     =cmdLine.HasSwitch("-TrainingDataFiles");
  barg_TestingDataFiles      =cmdLine.HasSwitch("-TestingDataFiles");
  barg_inicfg                =cmdLine.HasSwitch("-inicfg");

  //int co = cmdLine.GetArgumentCount("-TrainingDataFiles");
  if (barg_TrainingDataFiles)
  {
    for (int i=0; i<cmdLine.GetArgumentCount("-TrainingDataFiles"); i++)
    {
        arg_TrainingDataFiles = arg_TrainingDataFiles.fromStdString(cmdLine.GetArgument("-TrainingDataFiles",i));
        arg_TrainingDataFilesList.insert(i, arg_TrainingDataFiles);
    }
  }
  else
  {
      arg_TrainingDataFiles = "";
  }


  if (barg_TestingDataFiles)
  {
   for (int i=0; i<cmdLine.GetArgumentCount("-TestingDataFiles"); i++)
   {
       arg_TestingDataFiles = arg_TestingDataFiles.fromStdString(cmdLine.GetArgument("-TestingDataFiles",i));
       arg_TestingDataFilesList.insert(i, arg_TestingDataFiles);
   }
  }
  else
  {
    arg_TestingDataFiles = "";
  }

  if (barg_inicfg)
  {
    arg_inicfg = arg_inicfg.fromStdString(cmdLine.GetArgument("-inicfg",0));
  }
  else
  {
    arg_inicfg = "";
  }

  QString classifierOutputFile = cmdLine.GetSafeArgument( "-ClassifierOutputFile", 0, "" ).c_str();
  dialog.SetFiles(arg_TrainingDataFilesList, arg_TestingDataFilesList, arg_inicfg, classifierOutputFile);

  return dialog.exec();
}
Esempio n. 9
0
BOOL COngTVApp::InitInstance()
{
    // customisation des barres d'outils non autorisée
    CMFCToolBar::SetCustomizeMode(FALSE);
#ifdef SCINTILLA_DLL
    // Chargement de la DLL Scintilla : on va la chercher dans le repertoire de l'exe et nul part ailleurs
    // recuperation du path de l'exe
    char lpFilename[255];
    memset(lpFilename,0,255);
    GetModuleFileName(NULL ,lpFilename, 255);
    std::string strSciLexerDllName = CPathMgr::ExtractPath(lpFilename);
    strSciLexerDllName = strSciLexerDllName + "\\SciLexer.dll";
    m_hSciDLL = LoadLibrary(strSciLexerDllName.c_str());
    if (NULL == m_hSciDLL)
    {
        // DLL scintilla non disponible => on ne pourra pas editer de scrip LUA
    }
    else
    {
        CVersion versionSciDLL(strSciLexerDllName);
        if (versionSciDLL.GetProductVersion() < std::string(EXPECTED_SCINTILLA_VERSION))
        {
            // version de la DLL inferieur a la version attendue => on ne pourra pas editer de scrip LUA
            FreeLibrary(m_hSciDLL);
            m_hSciDLL = NULL;
            std::string strMsgError = "Dll min expected version : "EXPECTED_SCINTILLA_VERSION" obtained : ";
            strMsgError += versionSciDLL.GetProductVersion();
            MessageBox(NULL, strMsgError.c_str(), "Unable to load SciLexer.dll", MB_ICONEXCLAMATION);
        }
    }
#endif

#ifdef TEST_ENGLISH
    // Pour forcer une langue
    ::SetThreadLocale(MAKELCID(MAKELANGID(LANG_ENGLISH,
                       SUBLANG_DEFAULT),SORT_DEFAULT));
#endif

    // nettoyage des clefs de registres de la version precedente
    // si la version qui s'execute n'est pas identique a celle enregistree dans la base de registres
    // MFCFP = MFC Feature Pack => pour pouvoir faire cohabiter sur un même PC des versions antérieures à la 1.6.0 et des versions postérieures
    // a la 1.6.0
    // avant la 1.6.0 => IHM basée sur UltimateToolbox et sauvegarde des caractéristiques des fenêtres à plat dans la base de registre
    // à partir de 1.6.0 => IHM basée sur MFC Feature Pack et sauvegarde des caractéristiques des fenêtres dans une arborescence de clefs
    // dans la base de registres
    // le nettoyage de la base de registres plantait si on essaiyait de revenir à une version < 1.6.0 => on différencie la clef de base

    std::string strReg = "\\CurrentUser\\Software\\" + m_versionInfos.GetCompanyName() + "\\" + m_versionInfos.GetProductName() + "MFCFP\\";
    g_Registry.SetFullRegistryItem(strReg.c_str());
    CString sVersion=g_Registry.GetStringValue(REGISTRY_KEY_VERSION);
    CString sProductVersion(m_versionInfos.GetProductVersion().c_str());
    if (sVersion != sProductVersion)
    {
        DeleteRegTree(&g_Registry);
    }
    g_Registry.Close();

    // Pour utilisation de RichEditCtrl
    AfxEnableControlContainer();
    AfxInitRichEdit();
    // InitCommonControlsEx() est requis sur Windows XP si le manifeste de l'application
    // spécifie l'utilisation de ComCtl32.dll version 6 ou ultérieure pour activer les
    // styles visuels.  Dans le cas contraire, la création de fenêtres échouera.
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    // À définir pour inclure toutes les classes de contrôles communs à utiliser
    // dans votre application.
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    InitContextMenuManager();
    InitShellManager();
    InitKeyboardManager();
    InitTooltipManager();
    CMFCToolTipInfo ttParams;
    ttParams.m_bVislManagerTheme = TRUE;
    GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);

    // enregistrement Scintilla
#ifndef SCINTILLA_DLL
    Scintilla_RegisterClasses(AfxGetInstanceHandle());
    Scintilla_LinkLexers();
#endif

// Supprime pour la gestion multi-lingues
//    CWinAppEx::InitInstance();


    // Initialisation standard
    // Si vous n'utilisez pas ces fonctionnalités et que vous souhaitez réduire la taille
    // de votre exécutable final, vous devez supprimer ci-dessous
    // les routines d'initialisation spécifiques dont vous n'avez pas besoin.
    // Changez la clé de Registre sous laquelle nos paramètres sont enregistrés
    // TODO : modifiez cette chaîne avec des informations appropriées,
    // telles que le nom de votre société ou organisation
    SetRegistryKey(m_versionInfos.GetCompanyName().c_str());

    //First free the string allocated by MFC at CWinApp startup.
    //The string is allocated before InitInstance is called.
    free((void*)m_pszProfileName);
    //Change the name of the .INI file.
    //The CWinApp destructor will free the memory.
    // Ce nom est utilise pour la sauvegarde des parametres
    strReg = m_versionInfos.GetProductName() + "MFCFP";
    m_pszProfileName = _tcsdup(strReg.c_str());

    LoadStdProfileSettings(4);  // Charge les options de fichier INI standard (y compris les derniers fichiers utilisés)
    // Inscrire les modèles de document de l'application. Ces modèles
    //  lient les documents, fenêtres frame et vues entre eux
    
    // creation du manager de doc specifique afin de gerer specifiquement les repertoires
    // de sauvegarde des diffents documents.
    // cf http://www.codeguru.com/cpp/w-d/dislog/commondialogs/article.php/c1967
    m_pDocManager = new COngTVDocManager;

    // Creation doc template pour les scripts LUA (uniquement si DLL scintilla disponible)
    if (NULL != m_hSciDLL)
    {
        m_pNewLuaDocTemplate = new CMultiDocTemplate( IDR_LUATYPE
                                                    , RUNTIME_CLASS(CLuaDoc)
                                                    , RUNTIME_CLASS(CLuaChildFrame)
                                                    , RUNTIME_CLASS(CLuaView)
                                                    );
        if (!m_pNewLuaDocTemplate)
            return FALSE;
        AddDocTemplate(m_pNewLuaDocTemplate);
    }

    // Installe la police DINA
    HRSRC hRes   = FindResource(NULL, MAKEINTRESOURCE(IDR_DINA), _T("DINA"));
    PVOID lpFont = LockResource(LoadResource(NULL, hRes)); 
    DWORD dwSize = SizeofResource(NULL, hRes), cFonts = 0;
    m_hDinaFont = AddFontMemResourceEx(lpFont, dwSize, NULL, &cFonts);
    ASSERT(cFonts > 0);

    // crée la fenêtre frame MDI principale
    CMainFrame* pMainFrame = new CMainFrame;
    // On parse la ligne de commande
    CCmdLine cmdLine;
    cmdLine.SplitLine(__argc, __argv);
    // On indique le fichier de configuration ("" par defaut)
    std::string configFileName = cmdLine.GetSafeArgument("-cnx", 0, "");
    pMainFrame->SetConfigFile(configFileName);

    m_pMainWnd = pMainFrame;
    if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
    {
        delete pMainFrame;
        return FALSE;
    }

    // La fenêtre principale a été initialisée et peut donc être affichée et mise à jour
    pMainFrame->ShowWindow(m_nCmdShow);
    pMainFrame->UpdateWindow();

    return TRUE;
}
int main(int argc, char* argv[])
{
	// Read parameters from console.
	CCmdLine cmdLine;

	if(cmdLine.SplitLine(argc, argv) < 5)
	{
		cerr << "Usage: ./bbnet -s score_file -n node -b bkg -f func_depth -o output" << endl;
		cerr << endl << "Additional parameter:" << endl;
		cerr << "-k\tPenalty parameter(logK, Default = 5.0)" << endl;
		cerr << "-c\tnumber of candidate motifs (Default=50)" << endl;
		cerr << "-d\tpositive negative (for prediction using BN)" << endl;
		cerr << "-l\toutput of all training samples' information." << endl;
		cerr << "-t\ttranslational(transcriptional) start sites.(Default = right end)" << endl;
		cerr << "-rb\tbit-string to determine which rules to include.(Default = 111110)" << endl;
		cerr << "-i\tUse mutual information instead of Bayesian score" << endl;
		cerr << endl << "Contact: \"Li Shen\"<*****@*****.**>" << endl;
		return 1;
	}

	string s, n, b, f, o;
	try
	{
		s = cmdLine.GetArgument("-s", 0);	// score file.
		n = cmdLine.GetArgument("-n", 0);	// node gene list file.
		b = cmdLine.GetArgument("-b", 0);	// bkg gene list file.
		f = cmdLine.GetArgument("-f", 0);	// func depth folder.
		o = cmdLine.GetArgument("-o", 0);	// results output file.
	}
	catch(int)
	{
		cerr << "Wrong arguments!" << endl;
		return 1;
	}

	if(cmdLine.HasSwitch("-i"))
		itag = true;

	//itag = true;
	//string s = "../gbnet/data/Beer/scor_test.list";
	//string n = "../gbnet/data/Beer/node.list";
	//string b = "../gbnet/data/Beer/bkg.list";
	//string f = "../gbnet/data/Beer/func";
	//string k = "0.015";
	//logK = atof(k.data());
	//string o = "../gbnet/data/Beer/bb_res_test2.txt";

	string k;	// Penalty parameter; logK value.
	if(!itag)
		k = cmdLine.GetSafeArgument("-k", 0, "5.0");
	else
		k = cmdLine.GetSafeArgument("-k", 0, "0.015");
	logK = atof(k.data());

	string c = cmdLine.GetSafeArgument("-c", 0, "50");	// number of candidate motifs. default = 50.
	motifcand = atoi(c.data());

	// Use prior counts for some motifs if specified.
	string p = cmdLine.GetSafeArgument("-p", 0, "0");	// prior counts.
	pricnt = atoi(p.data());
	if(pricnt > 0)	// read preferred motifs list from file.
	{
		prior = 1;
		string fPrim = cmdLine.GetSafeArgument("-p", 1, "primot.txt");
		vector<string> primv;
		if(get1stcol(fPrim, primv) < 0)
			return 1;
		for(size_t i = 0; i < primv.size(); i++)
			primo.insert(primv[i]);
	}

	// File names for positive, negative and left-out testing lists.
	string pos = cmdLine.GetSafeArgument("-d", 0, "");	// positive testing cases.
	string neg = cmdLine.GetSafeArgument("-d", 1, "");	// negative testing cases.
	string res = cmdLine.GetSafeArgument("-d", 2, "");	// left-out testing cases.
	vector<string> plst, nlst, rlst;	// positive, negative and left-out lists.
	if(pos != "" && neg != "")
	{
		if(get1stcol(pos, plst) < 0)
			return 1;
		if(get1stcol(neg, nlst) < 0)
			return 1;
	}
	if(res != "")
	{
		if(get1stcol(res, rlst) < 0)
			return 1;
	}

	// File for output of all training samples' information.
	string finfo = cmdLine.GetSafeArgument("-l", 0, "");

	// File to store all genes' translational/transcriptional start sites.
	string ftss = cmdLine.GetSafeArgument("-t", 0, "");
	if(ftss != "")
		loadtss(ftss, mtss);

	// A bit-string to determine which rules to include.
	rb = cmdLine.GetSafeArgument("-rb", 0, "111110");

	string bp = cmdLine.GetSafeArgument("-bp", 0, "");	// Output each gene's probability like in Beer's prediction.
	
	// Load motif Bayesian score file.
	if(loadscor(mscor, s) != 0)
	{
		cerr << "Load motif scores eror!" << endl;
		return 1;
	}
	else
	{
#ifdef VERBOSE
		cout << "Display candidate motifs that are loaded:" << endl;
		dispscor(mscor);
#endif
	}
	vector<MotifScore> oscor = mscor;	// Save an original copy of motif scores.

	// Load gene list.
	vector<Case> tlst, blst, genlst;
	set<string> genset;
	if(loadgene(tlst, blst, n, b) != 0)
	{
		cerr << "Load gene lists error!" << endl;
		return 1;
	}
	else
	{
		genlst.insert(genlst.end(), tlst.begin(), tlst.end());
		genlst.insert(genlst.end(), blst.begin(), blst.end());
#ifdef VERBOSE
		cout << "Load gene list completed!" << endl;
#endif
		// All training and testing gene names are put into genmap.
		for(size_t i = 0; i < genlst.size(); i++)
			genset.insert(genlst[i].name);
		for(size_t i = 0; i < plst.size(); i++)
			genset.insert(plst[i]);
		for(size_t i = 0; i < nlst.size(); i++)
			genset.insert(nlst[i]);
		for(size_t i = 0; i < rlst.size(); i++)
			genset.insert(rlst[i]);
	}

	// Load motif binding information of genes in genmap.
	if(loadbind(allbind, mscor, genset, f) != 0)
	{
		cerr << "Load binding information error!" << endl;
		return 1;
	}
	else
	{
#ifdef VERBOSE
		cout << "Load binding information completed!" << endl;
#endif
	}

	// File for output.
	ofstream hOut(o.data());
	if(!hOut)
	{
		cerr << "Can't open " << o << endl;
		return 1;
	}
	hOut << "Number of genes in category 1: " << tlst.size() << endl;
	hOut << "Number of genes in category 0: " << blst.size() << endl << endl;

#ifdef VERBOSE
	cout << endl << "Running on original data." << endl;
#endif
	vector<Constraint> cons;
	vector<CPTRow> cpt;
	clock_t start = clock();
	double scor = bbnet(cons, cpt, genlst);
	clock_t finish = clock();
	if(outbayes(hOut, scor, cons, cpt, oscor, tlst.size(), blst.size()) != 0)
	{
		cerr << "Output Bayesian network results error!" << endl;
		return 1;
	}
	if(finfo != "")
	{
		if(outgene(finfo, tlst, blst, cons) != 0)
			cerr << "Output training samples' information error!" << endl;
		return 1;
	}
	if(pos != "" && neg != "")
	{
		Pred d = predict(cons, cpt, plst, nlst);
		outpred(hOut, d, n, b, pos, neg);
		if(bp != "")	// output each gene's probability being in this cluster if output file is specified.
		{
			ofstream hbp(bp.data());
			if(!hbp)
			{
				cerr << "Can't open " << bp << endl;
				return 1;
			}
			vector<BPred> trnbp = predict(cons, cpt, genlst, 0);	// probabilities for training genes.
			outpred(hbp, trnbp);
			vector<string> tstlst;	// probabilities for testing genes.
			tstlst.insert(tstlst.end(), plst.begin(), plst.end());	// positive testings.
			tstlst.insert(tstlst.end(), nlst.begin(), nlst.end());	// negative testings.
			vector<BPred> tstbp = predict(cons, cpt, tstlst, 1);
			outpred(hbp, tstbp);
			if(res != "")	// probabilities for left-out genes if the left-out file is specified.
			{
				vector<BPred> lefbp = predict(cons, cpt, rlst, -1);
				outpred(hbp, lefbp);
			}
			hbp.close();
		}
	}
	hOut << endl << "Bayesian network occupied CPU " << (double)(finish-start)/CLOCKS_PER_SEC << " seconds." << endl;
	hOut.close();

	return 0;
}