int SC_TerminalClient::run(int argc, char** argv)
{
	Options& opt = mOptions;

	if (!parseOptions(argc, argv, opt)) {
		return mReturnCode;
	}

	// finish argv processing
	const char* codeFile = 0;

	if (argc > 0) {
		codeFile = argv[0];
		opt.mDaemon = true;
		argv++; argc--;
	}

	opt.mArgc = argc;
	opt.mArgv = argv;

	// read library configuration file
	if (opt.mLibraryConfigFile) {
		int argLength = strlen(opt.mLibraryConfigFile);
		SC_LanguageConfig::readLibraryConfigYAML(opt.mLibraryConfigFile);
	} else
		SC_LanguageConfig::readDefaultLibraryConfig();

	// initialize runtime
	initRuntime(opt);

	// startup library
	mShouldBeRunning = true;
	compileLibrary();

	// enter main loop
	if (codeFile) executeFile(codeFile);
	if (opt.mCallRun) runMain();

	if (opt.mDaemon) {
		daemonLoop();
	}
	else {
		initInput();
		if( shouldBeRunning() ) startInput();
		if( shouldBeRunning() ) commandLoop();
		endInput();
		cleanupInput();
	}

	if (opt.mCallStop) stopMain();

	// shutdown library
	shutdownLibrary();
	flush();

	shutdownRuntime();

	return mReturnCode;
}
static void setup_signals()
{
	struct sigaction sigact = {
		.sa_handler = terminate,
		.sa_flags = 0
	};
	sigemptyset(&sigact.sa_mask);
	sigaction(SIGTERM, &sigact, 0);
	sigaction(SIGINT, &sigact, 0);

	signal(SIGHUP, SIG_IGN);
	signal(SIGPIPE,SIG_IGN);
}

// main function
int main()
{
	if (!ensure_singleton(SINGLETON_LOCKFILE))
		return 1;

	if (initialize_log() != 0) {
		LOGE("Init log failed. uninit\n");
		terminate0();
		LOGE("Daemon terminated\n");
		exit(0);
	}

	LOGI("da_started\n");
	atexit(terminate0);


	//for terminal exit
	setup_signals();
	daemon(0, 1);
	LOGI("--- daemonized (pid %d) ---\n", getpid());

	FILE *portfile = fopen(PORTFILE, "w");
	if (!portfile) {
		LOGE("cannot create portfile");
		return 1;
	}

	int err = initializeManager(portfile);
	fclose(portfile);
	if (err)
		return 1;

	//init all file descriptors
	init_system_file_descriptors();
	//daemon work
	//FIX ME remove samplingThread it is only for debug
	//samplingThread(NULL);
	daemonLoop();
	LOGI("daemon loop finished\n");
	stop_all();
	finalizeManager();

	close_system_file_descriptors();

	//DO NOT USE THIS FUNCTION FOR RELEASE IT IS TOO SLOW
#ifdef MALLOC_DEBUG_LEVEL
	msg_swap_free_all_data(&prof_session.user_space_inst);
#endif

	LOGI("main finished\n");
	print_malloc_list(NULL, 0);
	return 0;
}