Example #1
0
int main (int argc, char **argv) {

  void *argtable[] = {
    help = arg_lit0("h","help","print this screen"),
    verbose = arg_lit0("v","verbose","tell me everything"),
    fsyslog = arg_lit0(NULL,"syslog","use syslog"),
    cachepath = arg_file1(NULL,NULL,"cachepath","directory or .cdb database file"),
    netaddress0 = arg_file1(NULL,NULL,"read_address","zmq read network address"),
    netaddress1 = arg_file1(NULL,NULL,"write_address","zmq write network address"),
    end = arg_end(20),
  };
  
  int32_t nerrors = arg_parse(argc,argv,argtable);
  
  if (help->count) {
    
    fprintf(stdout,"tmpcache %s - version 0\n",__FUNCTION__);
    arg_print_syntaxv(stdout,argtable,"\n\n");
    arg_print_glossary (stdout,argtable,"%-25s %s\n");
   
    goto finish;
  }

  if (verbose->count) {

    fprintf(stdout,"tmpcache host - version 0\n");
    int32_t major,minor,patch;
    zmq_version (&major,&minor,&patch);
    fprintf(stdout,"compiled with zmq support %d.%d.%d\n",major,minor,patch);

    goto finish;
  }

  if (nerrors) {
    
    arg_print_errors (stdout,end,"");
    arg_print_syntaxv(stdout,argtable,"\n\n");
    goto finish;
  }

 
  u_term = 0;
  signal (SIGINT,signalhandler);
  signal (SIGTERM,signalhandler);

  if (fsyslog->count)
    openlog (NULL,LOG_PID|LOG_NDELAY,LOG_USER);

  void *read (void *arg) {

    tc_readconfig_t *config = (tc_readconfig_t *)arg;

    if (fsyslog->count)
      syslog (LOG_INFO,"reading cache from %s @ %s",btocstr(config->cachepath),btocstr(config->address));
    
    tc_readfromcache (config);
    
    if (fsyslog->count)
      syslog (LOG_INFO,"closing cache %s @ %s for reading",btocstr(config->cachepath),btocstr(config->address));     
  }
Example #2
0
int main(int argc, char* argv[])
{
    // Setup.
    AppLib::Logging::setApplicationName(std::string("apputil"));
    struct arg_file *script = arg_file1(NULL, NULL, "script", "the path of the script to execute");
    struct arg_end *end = arg_end(20);
    void *argtable[] = { script, end };
    script->filename[0] = NULL;

    // Check to see if the argument definitions were allocated
    // correctly.
    if (arg_nullcheck(argtable))
    {
        AppLib::Logging::showErrorW("Insufficient memory.");
        return 1;
    }

    // Now parse the arguments.
    int nerrors = arg_parse(argc, argv, argtable);

    // Check to see if there were errors.
    if (nerrors > 0 && script->filename[0] == NULL)
    {
        printf("Usage: apputil");
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, "apputil");
        
        printf("AppUtil - The application scripting utility.\n\n");
        arg_print_glossary(stdout, argtable, "    %-25s %s\n");
        return 1;
    }

    // Execute.
    return runPython(script->filename[0], argc, argv);
}
Example #3
0
/*
 * All code below is "unimportant", it's only argument and file handling
 */
int main(int argc, char *argv[]) {
	struct arg_file *ifile = arg_file1("i", "input-file", "INPUT_FILE", "Set Input File");
	struct arg_file *ofile = arg_file0("o", "output-file", "OUTPUT_FILE", "Set Output File");
	struct arg_str *pass = arg_str0("p", "password", "PASSWORD", "Set Encryption Password");
	struct arg_int *pas = arg_int0("c", "passes", "PASSES", "Set number of passes (To decrypt you'll need the same number of passes)");
	struct arg_int *buf = arg_int0("b", "buffer-size", "BUFFER_SIZE", "Set Buffer Size");
	struct arg_end *end = arg_end(20);
	void *argtable[] = {
	ifile, ofile, pass, pas, buf, end};
	int nerrors = arg_parse(argc, argv, argtable);
	
	if (nerrors > 0) {
		arg_print_errors(stdout, end, "rxe");
		printf("\nUsage: rxe");
		arg_print_syntax(stdout, argtable, "\n");
		arg_print_glossary(stdout, argtable, "  %-10s %s\n");
	} else {
		if (buf->count > 0) {
			BUFFER_SIZE = buf->ival[0];
		}
		FILE *outfile, *infile = fopen(ifile->filename[0], "rb");
		if (ofile->count > 0) outfile = fopen(ofile->filename[0], "wb");
		else {
			char farr[2048];
			char *ptr;
			strcpy(farr, ifile->filename[0]);
			if ((ptr = strstr(farr, ".rxe")) != NULL) {
				farr[0] = '\0';
				farr[1] = '\0';
				farr[2] = '\0';
				farr[3] = '\0';
			} else strcat(farr, ".rxe");
			outfile = fopen(farr, "wb");
		}
		if(pas->count > 0) PASSES = pas->ival[0];
		if(pass->count > 0) RXE_Main(infile, outfile, (char *)pass->sval[0]);
		else RXE_Main(infile, outfile, "DEFAULT");
		fclose(outfile);
		fclose(infile);
	}
	return 0;
}
Example #4
0
void test_argfile_basic_003(CuTest* tc) {
    struct arg_file* a = arg_file1(NULL, NULL, "<file>", "filename to test");
    struct arg_end* end = arg_end(20);
    void* argtable[] = {a, end};
    int nerrors;

    char* argv[] = {"program", "./foo.bar", NULL};
    int argc = sizeof(argv) / sizeof(char*) - 1;

    CuAssertTrue(tc, arg_nullcheck(argtable) == 0);
    nerrors = arg_parse(argc, argv, argtable);

    CuAssertTrue(tc, nerrors == 0);
    CuAssertTrue(tc, a->count == 1);
    CuAssertStrEquals(tc, a->filename[0], "./foo.bar");
    CuAssertStrEquals(tc, a->basename[0], "foo.bar");
    CuAssertStrEquals(tc, a->extension[0], ".bar");

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
}
Example #5
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int 
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

int Rslt;
bool bSkipFirst;			// true if first line contains header and should be skipped
int iMinLength;				// core elements must be of at least this length
int iMaxLength;				// and no longer than this length
char szInLociFile[_MAX_PATH];	// input element loci from this file
char szInSeqFile[_MAX_PATH];	// input bioseq file containing assembly
char szRsltsFile[_MAX_PATH];	// output stats to this file


// command line args
struct arg_lit  *help    = arg_lit0("hH","help",                "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_int *ScreenLogLevel=arg_int0("S", "ScreenLogLevel",	"<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_file *InLociFile = arg_file1("i","inloci","<file>",	"element loci CSV file");
struct arg_file *InSeqFile = arg_file1("I","assembly","<file>",	"genome assembly bioseq file");
struct arg_file *RsltsFile = arg_file1("o","output","<file>",	"output file");
struct arg_lit  *SkipFirst    = arg_lit0("x","skipfirst",       "skip first line of CSV - header line");
struct arg_int  *MinLength = arg_int0("l","minlength","<int>",	"minimum element length (default 10)");
struct arg_int  *MaxLength = arg_int0("L","maxlength","<int>",	"maximum element length (default 1000000000)");
struct arg_end *end = arg_end(20);

void *argtable[] = {help,version,FileLogLevel,ScreenLogLevel,LogFile,
					InLociFile,InSeqFile,RsltsFile,SkipFirst,MinLength,MaxLength,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

    /* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s csv2stats, Version %s\nOptions ---\n", gszProcName,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s @myparams.txt\n\n",gszProcName);
		exit(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s Version %s\n",gszProcName,cpszProgVer);
		exit(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}
	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	bSkipFirst = SkipFirst->count ? true : false;

	iMinLength = MinLength->count ? MinLength->ival[0] : cDfltMinLengthRange;
	if(iMinLength < 1 || iMinLength > cMaxLengthRange)
		{
		printf("Error: Mininum element length '-l%d' is not in range 1..%d",iMinLength,cMaxLengthRange);
		exit(1);
		}

	iMaxLength = MaxLength->count ? MaxLength->ival[0] : cMaxLengthRange;
	if(iMaxLength < iMinLength || iMaxLength > cMaxLengthRange)
		{
		printf("Error: Maximum element length '-L%d' is not in range %d..%d",iMaxLength,iMinLength,cMaxLengthRange);
		exit(1);
		}

	strncpy(szInLociFile,InLociFile->filename[0],_MAX_PATH);
	szInLociFile[_MAX_PATH-1] = '\0';
	strncpy(szInSeqFile,InSeqFile->filename[0],_MAX_PATH);
	szInSeqFile[_MAX_PATH-1] = '\0';
	strncpy(szRsltsFile,RsltsFile->filename[0],_MAX_PATH);
	szRsltsFile[_MAX_PATH-1] = '\0';

		// now that command parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem.");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile);
		exit(1);
		}
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s Processing parameters:",cpszProgVer);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input CSV element loci file: '%s'",szInLociFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input bioseq genome assembly file: '%s'",szInSeqFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output to file: '%s'",szRsltsFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"First line contains header: %s",bSkipFirst ? "yes" : "no");
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum element length: %d",iMinLength);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum element length: %d",iMaxLength);

#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	// processing here...
	Rslt = Process(bSkipFirst,iMinLength,iMaxLength,szInLociFile,szInSeqFile,szRsltsFile);

	gStopWatch.Stop();
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	printf("\n%s csv2stats, Version %s\n",gszProcName,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
}
Example #6
0
int genkmarkers(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
genkmarkers(int argc, char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file
int Rslt = 0;   			// function result code >= 0 represents success, < 0 on failure

int NumberOfProcessors;		// number of installed CPUs
int NumThreads;				// number of threads (0 defaults to number of CPUs)

int PMode;					// processing mode
int KMerLen;				// this length K-mers
int PrefixLen;				// inter-cultivar shared prefix length
int SuffixLen;				// cultivar specific suffix length
int MinWithPrefix;			// minimum number of cultivars required to have the shared prefix
int MinHamming;				// must be at least this Hamming away from any other K-mer in other species
char szCultivarName[cMaxDatasetSpeciesChrom+1];		// cultivar name
char szPartialCultivarsList[(cMaxDatasetSpeciesChrom + 10) * cMaxTargCultivarChroms];		// individual species parsed from this comma/tab/space separated list
int NumPartialCultivars;	// there are this many pseudo chromosomes for targeted cultivar for which K-mer markers are required
char *pszPartialCultivars[cMaxTargCultivarChroms+1];	// pseudo chromosome names which identify targeted cultivar
char szSfxPseudoGenome[_MAX_PATH];		// contains assembly + suffix array over all psuedo-chromosomes for all cultivars
char szMarkerFile[_MAX_PATH];			// output potential markers to this file
char szMarkerReadsFile[_MAX_PATH];		// output reads containing potential markers to this file


char szSQLiteDatabase[_MAX_PATH];	// results summaries to this SQLite file
char szExperimentName[cMaxDatasetSpeciesChrom+1];			// experiment name
char szExperimentDescr[1000];		// describes experiment

// command line args
struct arg_lit  *help    = arg_lit0("h","help",                 "Print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"Print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to screen and logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"Diagnostics log file");

struct arg_int *pmode = arg_int0("m","mode","<int>",			"Processing mode : 0 - default with K-mer extension, 1 - no K-mer extension, 2 - inter-cultivar shared prefix sequences ");
struct arg_int *kmerlen = arg_int0("k","kmer","<int>",			"Cultivar specific K-mers of this length (default 50, range 25..100)");

struct arg_int *prefixlen = arg_int0("p","prefixlen","<int>",	"Cultivar specific K-mers to contain inter-cultivar shared prefix sequences of this length (Mode 2 only");
struct arg_int *minwithprefix = arg_int0("s","minshared","<int>","Inter-cultivar shared prefix sequences must be present in this many cultivars (Mode 2 only, default all)");

struct arg_int *minhamming = arg_int0("K","minhamming","<int>", "Minimum Hamming separation distance in other non-target cultivars (default 2, range 1..5)");
struct arg_str *cultivar = arg_str1("c","cultivar","<str>",		"Cultivar name to associate with identified marker K-mers");
struct arg_str *chromnames = arg_str1("C","chromnames","<str>",	"Comma/space separated list of pseudo-chrom names specific to cultivar for which markers are required");
struct arg_file *infile = arg_file1("i","in","<file>",		    "Use this suffix indexed pseudo-chromosomes file");
struct arg_file *outfile = arg_file1("o","markers","<file>",		"Output accepted marker K-mer sequences to this multifasta file");
struct arg_file *outreadsfile = arg_file0("O","markerreads","<file>",	"Output reads containing accepted marker K-mers to this multifasta file");
struct arg_int *numthreads = arg_int0("T","threads","<int>",		"number of processing threads 0..128 (defaults to 0 which sets threads to number of CPU cores)");

struct arg_file *summrslts = arg_file0("q","sumrslts","<file>",		"Output results summary to this SQLite3 database file");
struct arg_str *experimentname = arg_str0("w","experimentname","<str>",		"experiment name SQLite3 database file");
struct arg_str *experimentdescr = arg_str0("W","experimentdescr","<str>",	"experiment description SQLite3 database file");
struct arg_end *end = arg_end(200);

void *argtable[] = {help,version,FileLogLevel,LogFile,
					summrslts,experimentname,experimentdescr,
	                pmode,kmerlen,prefixlen,minwithprefix,minhamming,cultivar,chromnames,infile,outfile,outreadsfile,
					numthreads,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s %s %s, Version %s\nOptions ---\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s %s @myparams.txt\n",gszProcName,gpszSubProcess->pszName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		return(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s %s Version %s\n",gszProcName,gpszSubProcess->pszName,cpszProgVer);
		return(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>\n'",FileLogLevel->ival[0]);
		return(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d\n",iFileLogLevel,eDLNone,eDLDebug);
		return(1);
		}

	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	// now that log parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem\n");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created\n",szLogFile);
		return(1);
		}
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Subprocess %s Version %s starting",gpszSubProcess->pszName,cpszProgVer);

	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentName[0] = '\0';
	szExperimentDescr[0] = '\0';

	if(experimentname->count)
		{
		strncpy(szExperimentName,experimentname->sval[0],sizeof(szExperimentName));
		szExperimentName[sizeof(szExperimentName)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szExperimentName);
		CUtility::ReduceWhitespace(szExperimentName);
		}
	else
		szExperimentName[0] = '\0';

	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentDescr[0] = '\0';
	if(summrslts->count)
		{
		strncpy(szSQLiteDatabase,summrslts->filename[0],sizeof(szSQLiteDatabase)-1);
		szSQLiteDatabase[sizeof(szSQLiteDatabase)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szSQLiteDatabase);
		if(strlen(szSQLiteDatabase) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite database specified with '-q<filespec>' option");
			return(1);
			}

		if(strlen(szExperimentName) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment name specified with '-w<str>' option");
			return(1);
			}
		if(experimentdescr->count)
			{
			strncpy(szExperimentDescr,experimentdescr->sval[0],sizeof(szExperimentDescr)-1);
			szExperimentDescr[sizeof(szExperimentDescr)-1] = '\0';
			CUtility::TrimQuotedWhitespcExtd(szExperimentDescr);
			}
		if(strlen(szExperimentDescr) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment description specified with '-W<str>' option");
			return(1);
			}

		gExperimentID = gSQLiteSummaries.StartExperiment(szSQLiteDatabase,false,true,szExperimentName,szExperimentName,szExperimentDescr);
		if(gExperimentID < 1)
			return(1);
		gProcessID = gSQLiteSummaries.AddProcess((char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszFullDescr);
		if(gProcessID < 1)
			return(1);
		gProcessingID = gSQLiteSummaries.StartProcessing(gExperimentID,gProcessID,(char *)cpszProgVer);
		if(gProcessingID < 1)
			return(1);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Initialised SQLite database '%s' for results summary collection",szSQLiteDatabase);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database experiment identifier for '%s' is %d",szExperimentName,gExperimentID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database process identifier for '%s' is %d",(char *)gpszSubProcess->pszName,gProcessID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database processing instance identifier is %d",gProcessingID);
		}
	else
		{
		szSQLiteDatabase[0] = '\0';
		szExperimentDescr[0] = '\0';
		}

// show user current resource limits
#ifndef _WIN32
	gDiagnostics.DiagOut(eDLInfo, gszProcName, "Resources: %s",CUtility::ReportResourceLimits());
#endif

#ifdef _WIN32
	SYSTEM_INFO SystemInfo;
	GetSystemInfo(&SystemInfo);
	NumberOfProcessors = SystemInfo.dwNumberOfProcessors;
#else
	NumberOfProcessors = sysconf(_SC_NPROCESSORS_CONF);
#endif
	int MaxAllowedThreads = min(cMaxWorkerThreads,NumberOfProcessors);	// limit to be at most cMaxWorkerThreads
	if((NumThreads = numthreads->count ? numthreads->ival[0] : MaxAllowedThreads)==0)
		NumThreads = MaxAllowedThreads;
	if(NumThreads < 0 || NumThreads > MaxAllowedThreads)
		{
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Number of threads '-T%d' specified was outside of range %d..%d",NumThreads,1,MaxAllowedThreads);
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Defaulting number of threads to %d",MaxAllowedThreads);
		NumThreads = MaxAllowedThreads;
		}


	PMode = (etPMode)(pmode->count ? pmode->ival[0] : ePMExtdKMers);
	if(PMode < ePMExtdKMers || PMode >= ePMplaceholder)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Processing mode '-m%d' specified outside of range %d..%d\n",PMode,ePMExtdKMers,(int)ePMplaceholder-1);
		exit(1);
		}

	KMerLen = kmerlen->count ? kmerlen->ival[0] : cDfltKMerLen;
	if(KMerLen < cMinKMerLen || KMerLen > cMaxKMerLen)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: K-mer core length '-k%d' must be in range %d..%d",KMerLen,cMinKMerLen,cMaxKMerLen);
		return(1);
		}

	if(PMode == 2)
		{
		PrefixLen = prefixlen->count ? prefixlen->ival[0] : KMerLen/2;
		if(PrefixLen < cMinKMerLen/2 || PrefixLen > KMerLen-(cMinKMerLen/2))
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Prefix length '-p%d' must be in range %d..%d",KMerLen,cMinKMerLen/2,KMerLen-(cMinKMerLen/2));
			return(1);
			}
		SuffixLen = KMerLen - PrefixLen;
		MinWithPrefix = minwithprefix->count ? minwithprefix->ival[0] : 0;
		if(MinWithPrefix != 0 && MinWithPrefix < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum cultivars sharing prefix sequence '-s%d' must be either 0 (all) or at least 1",MinWithPrefix);
			return(1);
			}
		}

	MinHamming = minhamming->count ? minhamming->ival[0] : cDfltHamming;
	if(MinHamming < cMinHamming || MinHamming > cMaxHamming)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum Hamming separation '-K%d' must be in range %d..%d",MinHamming,cMinHamming,cMaxHamming);
		return(1);
		}

	strncpy(szCultivarName,cultivar->sval[0],cMaxDatasetSpeciesChrom);
	szCultivarName[cMaxDatasetSpeciesChrom]= '\0';
	CUtility::TrimQuotedWhitespcExtd(szCultivarName);
	if(strlen(szCultivarName) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected cultivar name '-c<name>' is empty");
		return(1);
		}

	strncpy(szPartialCultivarsList,chromnames->sval[0],sizeof(szPartialCultivarsList));
	szPartialCultivarsList[sizeof(szPartialCultivarsList)-1] = '\0';
	CUtility::TrimQuotedWhitespcExtd(szPartialCultivarsList);
	CUtility::ReduceWhitespace(szPartialCultivarsList);
	char *pChr = szPartialCultivarsList;
	char *pStartChr;
	char Chr;
	int CurSpeciesLen;
	NumPartialCultivars=0;
	CurSpeciesLen = 0;
	pStartChr = pChr;
	while((Chr = *pChr++) != '\0')
		{
		if(Chr == ' ' || Chr == '\t' || Chr == ',')	// treat any of these as delimiters
			{
			pChr[-1] = '\0';
			if(CurSpeciesLen != 0)
				{
				pszPartialCultivars[NumPartialCultivars++] = pStartChr;
				CurSpeciesLen = 0;
				}
			pStartChr = pChr;
			continue;
			}
		CurSpeciesLen += 1;
		}
	if(CurSpeciesLen)
		pszPartialCultivars[NumPartialCultivars++] = pStartChr;

	if(!NumPartialCultivars)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected at least one ('-C<names>') targeted cultivar chromosme name");
		return(1);
		}

	strcpy(szSfxPseudoGenome,infile->filename[0]);
	CUtility::TrimQuotedWhitespcExtd(szSfxPseudoGenome);
	if(strlen(szSfxPseudoGenome) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected input pseudo-genome suffix array filename '-i<name>' is empty");
		return(1);
		}

	strcpy(szMarkerFile,outfile->filename[0]);
	CUtility::TrimQuotedWhitespcExtd(szMarkerFile);
	if(strlen(szMarkerFile) < 1)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected marker file to generate filename '-o<name>' is empty");
		return(1);
		}

	if(outreadsfile->count)
		{
		strcpy(szMarkerReadsFile,outreadsfile->filename[0]);
		CUtility::TrimQuotedWhitespcExtd(szMarkerReadsFile);
		if(strlen(szMarkerReadsFile) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Reads containing markers filename '-O<name>' is empty");
			return(1);
			}
		}
	else
		szMarkerReadsFile[0] = '\0';

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing parameters:");
	const char *pszDescr;
	switch(PMode) {
		case ePMExtdKMers:
			pszDescr = "Extended K-mer markers";
			break;
		case ePMNoExtdKMers:
			pszDescr = "Non-extended K-mer markers";
			break;
		case ePMPrefixKMers:
			pszDescr = "K-mers to share prefix sequence with other cultivars";
			break;
		}

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode is : '%s'",pszDescr);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Targeted cultivar name : '%s'",szCultivarName);

	for(int Idx = 0; Idx < NumPartialCultivars; Idx++)
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Targeted cultivar chromosome name (%d) : '%s'", Idx + 1,pszPartialCultivars[Idx]);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Core K-mer length : %d",KMerLen);
	if(PMode == ePMPrefixKMers)
		{
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Inter-cultivar shared prefix sequence length : %d",PrefixLen);
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Cultivar specific suffix sequence length : %d",SuffixLen);
		if(MinWithPrefix)
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Min number cultivars sharing prefix : %d",MinWithPrefix);
		else
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Min number cultivars sharing prefix : 'All'");
		}
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum Hamming separation : %d",MinHamming);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input indexed pseudo-genome file: '%s'",szSfxPseudoGenome);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Write marker K-mers to file: '%s'",szMarkerFile);
	if(szMarkerReadsFile[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Write marker containing reads to file: '%s'",szMarkerReadsFile);

	if(szExperimentName[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"This processing reference: %s",szExperimentName);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Number of processing threads: %d",NumThreads);

	if(gExperimentID > 0)
		{
		int ParamID;

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szLogFile),"log",szLogFile);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(PMode),"mode",&PMode);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(KMerLen),"kmer",&KMerLen);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(PrefixLen),"prefixlen",&PrefixLen);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(SuffixLen),"suffixlen",&SuffixLen);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(MinWithPrefix),"minwithprefix",&MinWithPrefix);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(MinHamming),"minhamming",&MinHamming);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumThreads),"threads",&NumThreads);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumberOfProcessors),"cpus",&NumberOfProcessors);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szCultivarName),"cultivar",szCultivarName);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(NumPartialCultivars),"NumPartialCultivars",&NumPartialCultivars);
		for(int Idx = 0; Idx < NumPartialCultivars; Idx++)
			ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(pszPartialCultivars[Idx]),"chromnames",pszPartialCultivars[Idx]);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szSfxPseudoGenome),"in",szSfxPseudoGenome);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szMarkerFile),"markers",szMarkerFile);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szMarkerReadsFile),"markerreads",szMarkerReadsFile);

		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szSQLiteDatabase),"sumrslts",szSQLiteDatabase);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szExperimentName),"experimentname",szExperimentName);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szExperimentDescr),"experimentdescr",szExperimentDescr);
		}


#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	gStopWatch.Start();
	Rslt = LocMarkers((etPMode)PMode,KMerLen,PrefixLen,SuffixLen,MinWithPrefix,MinHamming,szCultivarName,NumPartialCultivars,pszPartialCultivars,szSfxPseudoGenome,szMarkerFile,szMarkerReadsFile,NumThreads);
	Rslt = Rslt >=0 ? 0 : 1;
	if(gExperimentID > 0)
		{
		if(gProcessingID)
			gSQLiteSummaries.EndProcessing(gProcessingID,Rslt);
		gSQLiteSummaries.EndExperiment(gExperimentID);
		}
	gStopWatch.Stop();
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	return(Rslt);
	}
else
	{
    printf("\n%s %s %s, Version %s\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	return(1);
	}
return 0;
}
Example #7
0
int main(int argc, char *argv[]) {
    int retcode = 1;
    int nerrors = 0;
    streamer_t streamer;
    memset(&streamer, 0, sizeof(streamer_t));

    // Signal handlers
    signal(SIGINT, sig_fn);
    signal(SIGTERM, sig_fn);

    // Initialize SDL2
    if (SDL_Init(SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "%s\n", SDL_GetError());
        return 1;
    }

    // Defaults
    streamer.freq = 44100;
    streamer.n_channels = 2;
    streamer.bits = 16;
    streamer.volume = 1.0f;
    streamer.quality = DUMB_RQ_CUBIC;

    // commandline argument parser options
    struct arg_lit *arg_help =
        arg_lit0("h", "help", "print this help and exits");
    struct arg_dbl *arg_volume =
        arg_dbl0("v", "volume", "<volume",
                 "sets the output volume (-8.0 to +8.0, default 1.0)");
    struct arg_int *arg_samplerate = arg_int0(
        "s", "samplerate", "<freq>", "sets the sampling rate (default 44100)");
    struct arg_int *arg_quality = arg_int0(
        "r", "quality", "<quality>", "specify the resampling quality to use");
    struct arg_lit *arg_mono =
        arg_lit0("m", "mono", "generate mono output instead of stereo");
    struct arg_lit *arg_eight =
        arg_lit0("8", "eight", "generate 8-bit instead of 16-bit");
    struct arg_lit *arg_noprogress =
        arg_lit0("n", "noprogress", "hide progress bar");
    struct arg_file *arg_output =
        arg_file0("o", "output", "<file>", "output file");
    struct arg_file *arg_input =
        arg_file1(NULL, NULL, "<file>", "input module file");
    struct arg_end *arg_fend = arg_end(20);
    void *argtable[] = {arg_help,       arg_input,      arg_volume,
                        arg_samplerate, arg_quality,    arg_mono,
                        arg_eight,      arg_noprogress, arg_fend};
    const char *progname = "dumbplay";

    // Make sure everything got allocated
    if (arg_nullcheck(argtable) != 0) {
        fprintf(stderr, "%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse inputs
    nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if (arg_help->count > 0) {
        fprintf(stderr, "Usage: %s", progname);
        arg_print_syntax(stderr, argtable, "\n");
        fprintf(stderr, "\nArguments:\n");
        arg_print_glossary(stderr, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle libargtable errors
    if (nerrors > 0) {
        arg_print_errors(stderr, arg_fend, progname);
        fprintf(stderr, "Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Handle the switch options
    streamer.input = arg_input->filename[0];
    if (arg_eight->count > 0) {
        streamer.bits = 8;
    }
    if (arg_mono->count > 0) {
        streamer.n_channels = 1;
    }
    if (arg_noprogress->count > 0) {
        streamer.no_progress = true;
    }

    if (arg_volume->count > 0) {
        streamer.volume = arg_volume->dval[0];
        if (streamer.volume < -8.0f || streamer.volume > 8.0f) {
            fprintf(stderr, "Volume must be between -8.0f and 8.0f.\n");
            goto exit_0;
        }
    }

    if (arg_samplerate->count > 0) {
        streamer.freq = arg_samplerate->ival[0];
        if (streamer.freq < 1 || streamer.freq > 96000) {
            fprintf(stderr, "Sampling rate must be between 1 and 96000.\n");
            goto exit_0;
        }
    }

    if (arg_quality->count > 0) {
        streamer.quality = arg_quality->ival[0];
        if (streamer.quality < 0 || streamer.quality >= DUMB_RQ_N_LEVELS) {
            fprintf(stderr, "Quality must be between %d and %d.\n", 0,
                    DUMB_RQ_N_LEVELS - 1);
            goto exit_0;
        }
    }

    // Load source file.
    dumb_register_stdfiles();
    streamer.src = dumb_load_any(streamer.input, 0, 0);
    if (!streamer.src) {
        fprintf(stderr, "Unable to load file %s for playback!\n",
                streamer.input);
        goto exit_0;
    }

    // Set up playback
    streamer.renderer =
        duh_start_sigrenderer(streamer.src, 0, streamer.n_channels, 0);
    streamer.delta = 65536.0f / streamer.freq;
    streamer.sbytes = (streamer.bits / 8) * streamer.n_channels;
    streamer.ssize = duh_get_length(streamer.src);

    // Stop producing samples on module end
    DUMB_IT_SIGRENDERER *itsr = duh_get_it_sigrenderer(streamer.renderer);
    dumb_it_set_loop_callback(itsr, &dumb_it_callback_terminate, NULL);
    dumb_it_set_xm_speed_zero_callback(itsr, &dumb_it_callback_terminate, NULL);
    dumb_it_set_resampling_quality(itsr, streamer.quality);

    // Set up the SDL2 format we want for playback.
    SDL_AudioSpec want;
    SDL_zero(want);
    want.freq = streamer.freq;
    want.format = (streamer.bits == 16) ? AUDIO_S16 : AUDIO_S8;
    want.channels = streamer.n_channels;
    want.samples = SAMPLES;
    want.callback = stream_audio;
    want.userdata = &streamer;

    // Find SDL2 audio device, and request the format we just set up.
    // SDL2 will tell us what we got in the "have" struct.
    SDL_AudioSpec have;
    streamer.dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0);
    if (streamer.dev == 0) {
        fprintf(stderr, "%s\n", SDL_GetError());
        goto exit_1;
    }

    // Make sure we got the format we wanted. If not, stop here.
    if (have.format != want.format) {
        fprintf(stderr, "Could not get correct playback format.\n");
        goto exit_2;
    }

    // Play file
    SDL_PauseAudioDevice(streamer.dev, 0);

    // Show initial state of the progress bar (if it is enabled)
    int time_start = SDL_GetTicks();
    float seek = 0.0f;
    int ms_played = 0;
    if (!streamer.no_progress) {
        show_progress(PROGRESSBAR_LENGTH, seek, ms_played);
    }

    // Loop while dumb is still giving data. Update progressbar if enabled.
    while (!stop_signal && !streamer.ended) {
        if (!streamer.no_progress) {
            seek = ((float)streamer.spos) / ((float)streamer.ssize);
            ms_played = SDL_GetTicks() - time_start;
            show_progress(PROGRESSBAR_LENGTH, seek, ms_played);
        }
        SDL_Delay(100);
    }

    // We made it this far without crashing, so let's just exit with no error :)
    retcode = 0;

    // Free up resources and exit.
    if (streamer.sig_samples) {
        destroy_sample_buffer(streamer.sig_samples);
    }

exit_2:
    SDL_CloseAudioDevice(streamer.dev);

exit_1:
    if (streamer.renderer) {
        duh_end_sigrenderer(streamer.renderer);
    }
    if (streamer.src) {
        unload_duh(streamer.src);
    }

exit_0:
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    SDL_Quit();
    return retcode;
}
Example #8
0
int main(int argc, char* argv[]) {
    // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "font file");
    struct arg_int *fh = arg_int1("g", "height", "<value>", "font height in pixels (6 or 8)");
    struct arg_str *text = arg_str0("t", "text", "<value>", "text to show");
    struct arg_int *scale = arg_int0("s", "scale", "<value>", "scaling for the window");
    struct arg_file *export = arg_file0("e", "export", "<file>", "Export the full font to a PNG file");
    struct arg_lit *split = arg_lit0(NULL, "split", "Split to separate PNG files (set path in -e).");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,fh,text,scale,export,split,end};
    const char* progname = "fonttool";

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 Font file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2013 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Requite either export or text
    if(export->count <= 0 && text->count <= 0) {
        printf("Use either --export or --text arguments!\n");
        goto exit_0;
    }

    // Font size
    int _fs = fh->ival[0];
    if(_fs < 6 || _fs > 8 || _fs == 7) {
        printf("Only valid values for fontsize are 6 and 8.\n");
        goto exit_0;
    }

    // Load fonts
    sd_font font;
    sd_font_create(&font);
    int ret = sd_font_load(&font, file->filename[0], _fs);
    if(ret != SD_SUCCESS) {
        printf("Couldn't load small font file! Error [%d] %s.\n", ret, sd_get_error(ret));
        goto exit_1;
    }

    // Export or display
    if(export->count > 0) {
        export_to(&font, export->filename[0], (split->count > 0));
    } else {
Example #9
0
int main(int argc, char **argv)
    {
    /* SYNTAX 1: insert [-nvR] <file> [file]...  -o <file> */
    struct arg_rex  *cmd1     = arg_rex1(NULL,  NULL,  "insert", NULL, REG_ICASE, NULL);
    struct arg_lit  *noact1   = arg_lit0("n",   NULL,  "take no action");
    struct arg_lit  *verbose1 = arg_lit0("v", "verbose", "verbose messages");
    struct arg_lit  *recurse1 = arg_lit0("R",   NULL,  "recurse through subdirectories");
    struct arg_file *infiles1 = arg_filen(NULL, NULL,  NULL, 1,argc+2, "input file(s)");
    struct arg_file *outfile1 = arg_file0("o",  NULL,  "<output>", "output file (default is \"-\")");
    struct arg_end  *end1     = arg_end(20);
    void* argtable1[] = {cmd1,noact1,verbose1,recurse1,infiles1,outfile1,end1};
    int nerrors1;

    /* SYNTAX 2: remove [-nv] <file> */
    struct arg_rex  *cmd2     = arg_rex1(NULL, NULL, "remove", NULL, REG_ICASE, NULL);
    struct arg_lit  *noact2   = arg_lit0("n",  NULL, NULL);
    struct arg_lit  *verbose2 = arg_lit0("v",  "verbose", NULL);
    struct arg_file *infiles2 = arg_file1(NULL, NULL, NULL, NULL);
    struct arg_end  *end2     = arg_end(20);
    void* argtable2[] = {cmd2,noact2,verbose2,infiles2,end2};
    int nerrors2;

    /* SYNTAX 3: search [-v] <pattern> [-o <file>] [--help] [--version] */
    struct arg_rex  *cmd3     = arg_rex1(NULL, NULL, "search", NULL, REG_ICASE, NULL);
    struct arg_lit  *verbose3 = arg_lit0("v",  "verbose", NULL);
    struct arg_str  *pattern3 = arg_str1(NULL, NULL, "<pattern>", "search string");
    struct arg_file *outfile3 = arg_file0("o", NULL, "<output>", NULL);
    struct arg_end  *end3     = arg_end(20);
    void* argtable3[] = {cmd3,verbose3,pattern3,outfile3,end3};
    int nerrors3;

    /* SYNTAX 4: [-help] [-version] */
    struct arg_lit  *help4    = arg_lit0(NULL,"help",     "print this help and exit");
    struct arg_lit  *version4 = arg_lit0(NULL,"version",  "print version information and exit");
    struct arg_end  *end4     = arg_end(20);
    void* argtable4[] = {help4,version4,end4};
    int nerrors4;

    const char* progname = "multisyntax";
    int exitcode=0;

    /* verify all argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable1)!=0 ||
        arg_nullcheck(argtable2)!=0 ||
        arg_nullcheck(argtable3)!=0 ||
        arg_nullcheck(argtable4)!=0 )
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* set any command line default values prior to parsing */
    outfile1->filename[0]="-";
    outfile3->filename[0]="-";

    /* Above we defined a separate argtable for each possible command line syntax */
    /* and here we parse each one in turn to see if any of them are successful    */
    nerrors1 = arg_parse(argc,argv,argtable1);
    nerrors2 = arg_parse(argc,argv,argtable2);
    nerrors3 = arg_parse(argc,argv,argtable3);
    nerrors4 = arg_parse(argc,argv,argtable4);

    /* Execute the appropriate main<n> routine for the matching command line syntax */
    /* In this example program our alternate command line syntaxes are mutually     */
    /* exclusive, so we know in advance that only one of them can be successful.    */
    if (nerrors1==0)
        exitcode = mymain1(noact1->count, verbose1->count, recurse1->count,
                           outfile1->filename[0], infiles1->filename, infiles1->count);
    else if (nerrors2==0)
        exitcode = mymain2(noact2->count, verbose2->count, infiles2->filename[0]);
    else if (nerrors3==0)
        exitcode = mymain3(verbose3->count, pattern3->sval[0], outfile3->filename[0]);
    else if (nerrors4==0)
        exitcode = mymain4(help4->count, version4->count, progname,
                           argtable1, argtable2, argtable3, argtable4);
    else
        {
        /* We get here if the command line matched none of the possible syntaxes */
        if (cmd1->count > 0)
            {
            /* here the cmd1 argument was correct, so presume syntax 1 was intended target */ 
            arg_print_errors(stdout,end1,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable1,"\n");
            }
        else if (cmd2->count > 0)
            {
            /* here the cmd2 argument was correct, so presume syntax 2 was intended target */ 
            arg_print_errors(stdout,end2,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable2,"\n");
            }
        else if (cmd3->count > 0)
            {
            /* here the cmd3 argument was correct, so presume syntax 3 was intended target */ 
            arg_print_errors(stdout,end3,progname);
            printf("usage: %s ", progname);
            arg_print_syntax(stdout,argtable3,"\n");
            }
        else
            {
            /* no correct cmd literals were given, so we cant presume which syntax was intended */
            printf("%s: missing <insert|remove|search> command.\n",progname); 
            printf("usage 1: %s ", progname);  arg_print_syntax(stdout,argtable1,"\n");
            printf("usage 2: %s ", progname);  arg_print_syntax(stdout,argtable2,"\n");
            printf("usage 3: %s ", progname);  arg_print_syntax(stdout,argtable3,"\n");
            printf("usage 4: %s",  progname);  arg_print_syntax(stdout,argtable4,"\n");
            }
        }

exit:
    /* deallocate each non-null entry in each argtable */
    arg_freetable(argtable1,sizeof(argtable1)/sizeof(argtable1[0]));
    arg_freetable(argtable2,sizeof(argtable2)/sizeof(argtable2[0]));
    arg_freetable(argtable3,sizeof(argtable3)/sizeof(argtable3[0]));
    arg_freetable(argtable4,sizeof(argtable4)/sizeof(argtable4[0]));

    return exitcode;
    }
Example #10
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int 
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

int Rslt;
int iProcMode;
int iMinLength;
int iMaxLength;

int iMinMergeLength;
int iMaxMergeLength;

char szRefFile[_MAX_PATH];	// process ref hypers from this file
char szRelFile[_MAX_PATH];	// process rel hypers from this file
char szOutLociFile[_MAX_PATH];	// write loci to this file

char szRefSpecies[cMaxDatasetSpeciesChrom];	// use this species as the ref species in generated szOutLociFile
char szRelSpecies[cMaxDatasetSpeciesChrom];	// use this species/list as the rel species in generated szOutLociFile
char szElType[cMaxDatasetSpeciesChrom];		// use this as the element type in generated szOutLociFile

int iRefExtend;			// extend ref element lengths left+right by this many bases
int iRelExtend;			// extend rel element lengths left+right by this many bases
int iJoinDistance;		// if > 0 then join elements which only differ by at most this distance beween end of element i and start of element i+1


// command line args
struct arg_lit  *help    = arg_lit0("h","help",                 "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to screen and logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_file *RefFile = arg_file1("i","reffile","<file>",	"reference hyper element CSV file");
struct arg_file *RelFile = arg_file0("I","relfile","<file>",	"relative hyper element CSV file");
struct arg_file *OutLociFile = arg_file1("o",NULL,"<file>",		"output loci to file as CSV");

struct arg_str  *RefSpecies = arg_str1("r","refspecies","<string>","output loci file ref species");
struct arg_str  *RelSpecies = arg_str1("R","relspecies","<string>","output loci file rel species");
struct arg_str  *ElType = arg_str0("t","eltype","<string>","output loci file element type");

struct arg_int  *ProcMode = arg_int0("p","mode","<int>",		 "processing mode: 0:Intersect (Ref & Rel)\n\t\t1:Ref exclusive (Ref & !Rel)\n\t\t2:Rel exclusive (!Ref & Rel)\n\t\t3:Union (Ref | Rel)\n\t\t4:Neither (!(Ref | Rel))");
struct arg_int  *MinLength = arg_int0("l","minlength","<int>",   "minimum input ref/rel element length (default 4)");
struct arg_int  *MaxLength = arg_int0("L","maxlength","<int>",   "maximum input ref/rel element length (default 1000000)");

struct arg_int  *MinMergeLength = arg_int0("m","minmergelength","<int>","minimum merged output element length (default 4)");
struct arg_int  *MaxMergeLength = arg_int0("M","maxmergelength","<int>","maximum merged output element length (default 1000000)");

struct arg_int  *RefExtend = arg_int0("e","refextend","<int>",	 "extend ref element flanks left+right by this many bases (default 0)");
struct arg_int  *RelExtend = arg_int0("E","relextend","<int>",	 "extend rel element flanks left+right by this many bases (default 0)");

struct arg_int  *JoinDistance = arg_int0("j","join","<int>",     "merge output elements which are only separated by this number of bases (default 0)");

struct arg_end *end = arg_end(20);

void *argtable[] = {help,version,FileLogLevel,LogFile,
					ProcMode,
					RefFile,RelFile,OutLociFile,
					MinLength,MaxLength,RefExtend,RelExtend,JoinDistance,MinMergeLength,MaxMergeLength,
					RefSpecies,RelSpecies,ElType,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

    /* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s CSV Merge Elements, Version %s\nOptions ---\n", gszProcName,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s @myparams.txt\n",gszProcName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		exit(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s Version %s\n",gszProcName,cpszProgVer);
		exit(1);
        }
if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}
	
	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}


	iProcMode = ProcMode->count ? ProcMode->ival[0] : ePMElIntersect;
	if(iProcMode < ePMElIntersect || iProcMode > ePMElRefNotRefRel)
		{
		printf("Error: Processing mode '-p%d' is not in range 0..4",iProcMode);
		exit(1);
		}

	strncpy(szOutLociFile,OutLociFile->filename[0],_MAX_PATH);
	szOutLociFile[_MAX_PATH-1] = '\0';

	strncpy(szRefSpecies,RefSpecies->sval[0],sizeof(szRefSpecies));
	szRefSpecies[sizeof(szRefSpecies)-1] = '\0';
	strncpy(szRelSpecies,RelSpecies->sval[0],sizeof(szRelSpecies));
	szRelSpecies[sizeof(szRelSpecies)-1] = '\0';
	if(ElType->count)
		{
		strncpy(szElType,ElType->sval[0],sizeof(szElType));
		szElType[sizeof(szElType)-1] = '\0';
		}
	else
		strcpy(szElType,"merged");

	iMinLength = MinLength->count ? MinLength->ival[0] : cDfltMinLength;
	if(iMinLength < 0 || iMinLength > cMaxLengthRange)
		{
		printf("Error: Minimum element length '-l%d' is not in range 0..%d",iMinLength,cMaxLengthRange);
		exit(1);
		}

	iMaxLength = MaxLength->count ? MaxLength->ival[0] : cDfltMaxLength;
	if(iMaxLength < iMinLength || iMaxLength > cMaxLengthRange)
		{
		printf("Error: Maximum element length '-L%d' is not in range %d..%d",iMaxLength,iMinLength,cMaxLengthRange);
		exit(1);
		}

	iMinMergeLength = MinMergeLength->count ? MinMergeLength->ival[0] : cDfltMinLength;
	if(iMinMergeLength < 0 || iMinMergeLength > cMaxLengthRange)
		{
		printf("Error: Minimum output merged element length '-m%d' is not in range 0..%d",iMinMergeLength,cMaxLengthRange);
		exit(1);
		}

	iMaxMergeLength = MaxMergeLength->count ? MaxMergeLength->ival[0] : cDfltMaxLength;
	if(iMaxMergeLength < iMinMergeLength || iMaxMergeLength > cMaxLengthRange)
		{
		printf("Error: Maximum element length '-M%d' is not in range %d..%d",iMaxMergeLength,iMinMergeLength,cMaxLengthRange);
		exit(1);
		}

	iJoinDistance = JoinDistance->count ? JoinDistance->ival[0] : cDfltJoinOverlap;
	if(iJoinDistance < 0 || iJoinDistance > cMaxJoinOverlap)
		{
		printf("Error: Join separation length '-j%d' is not in range %d..%d",iJoinDistance,0,cMaxJoinOverlap);
		exit(1);
		}

	iRefExtend = RefExtend->count ? RefExtend->ival[0] : 0;
	if(iRefExtend < (-1 * cMaxExtendLength) || iRefExtend > cMaxExtendLength)
		{
		printf("Error: Ref Extension length '-e%d' is not in range %d..%d",iRefExtend,(-1 * cMaxExtendLength),cMaxExtendLength);
		exit(1);
		}

	iRelExtend = RelExtend->count ? RelExtend->ival[0] : 0;
	if(iRelExtend < (-1 * cMaxExtendLength) || iRelExtend > cMaxExtendLength)
		{
		printf("Error: Rel Extension length '-E%d' is not in range %d..%d",iRelExtend,(-1 * cMaxExtendLength),cMaxExtendLength);
		exit(1);
		}


	strncpy(szRefFile,RefFile->filename[0],_MAX_PATH);
	szRefFile[_MAX_PATH-1] = '\0';

	if(RelFile->count)
		{
		strncpy(szRelFile,RelFile->filename[0],_MAX_PATH);
		szRelFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		if(iProcMode == ePMElRefExclusive || iProcMode == ePMElRefRelUnion)
			szRelFile[0] = '\0';
		else
			{
			printf("Error: Rel loci file must be specified in processing mode '-p%d' (%s)",iProcMode,ProcMode2Txt((etProcMode)iProcMode));
			exit(1);
			}
		}

		// now that command parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem.");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile);
		exit(1);
		}
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s Processing parameters:",cpszProgVer);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing Mode: %d (%s)",iProcMode,ProcMode2Txt((etProcMode)iProcMode));
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Reference CSV file: '%s'",szRefFile);
	if(szRelFile[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Relative CSV file: '%s'",szRelFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output processed loci into CSV file: '%s'",szOutLociFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output loci file ref species: '%s'",szRefSpecies);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output loci file rel species: '%s'",szRelSpecies);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output loci file element type: '%s'",szElType);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum input element length: %d",iMinLength);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum input element length: %d",iMaxLength);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Ref element flank extension length: %d",iRefExtend);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Rel element flank extension length: %d",iRelExtend);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Merge output elements separated by at most this many bases: %d",iJoinDistance);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum output merged element length: %d",iMinMergeLength);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum output merged element length: %d",iMaxMergeLength);


	// processing here...
	gStopWatch.Start();
#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif	
	Rslt = Process((etProcMode)iProcMode,iMinLength,iMaxLength,iRefExtend,iRelExtend,iJoinDistance,iMinMergeLength,iMaxMergeLength,szRefFile,szRelFile,szOutLociFile,
		szRefSpecies,szRelSpecies,szElType);
	gStopWatch.Stop();
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	printf("\n%s CSV Merge Elements, Version %s\n",gszProcName,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
}
Example #11
0
int main(int argc, char* argv[])
{
	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_str* type_assembler = arg_str0("t", NULL, "<type>", "The type of assembler to output for.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file (or - to read from standard input).");
	struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
	struct arg_end *end = arg_end(20);
	void *argtable[] = { output_file, show_help, type_assembler, input_file, end };

	// Parse arguments.
	int nerrors = arg_parse(argc,argv,argtable);
	if (nerrors != 0 || show_help->count != 0)
	{
		if (show_help->count != 0)
			arg_print_errors(stdout, end, "compiler");
		fprintf(stderr, "syntax:\n    compiler");
		arg_print_syntax(stdout, argtable, "\n");
		fprintf(stderr, "options:\n");
		arg_print_glossary(stdout, argtable, "    %-25s %s\n");
		return 1;
	}

	// Parse C.
	pp_add_search_path(".");
	pp_add_search_path("include");
	pp_add_search_path(dirname<std::string>(input_file->filename[0]).c_str());
	yyout = stderr;
	yyin = pp_do(input_file->filename[0]);
	if (yyin == NULL)
	{
		pp_cleanup();
		return 1;
	}
	yyparse();
	if (yyin != stdin)
		fclose(yyin);
	pp_cleanup();
	if (program == NULL)
	{
		std::cerr << "An error occurred while compiling." << std::endl;
		return 1;
	}

	// Assembler type.
	const char* asmtype = "dcpu16toolchain";
	if (type_assembler->count > 0)
		asmtype = type_assembler->sval[0];

	// Spacing.
	std::cerr << std::endl;

	// Generate assembly using the AST.
	try
	{
		AsmGenerator generator(asmtype);
		AsmBlock* block = program->compile(generator);
		if (strcmp(output_file->filename[0], "-") == 0)
		{
			std::cout << generator.m_Preassembly << std::endl;
			std::cout << *block << std::endl;
			std::cout << generator.m_Postassembly << std::endl;
		}
		else
		{
			std::ofstream output(output_file->filename[0], std::ios::out | std::ios::trunc);
			output << generator.m_Preassembly << std::endl;
			output << *block << std::endl;
			output << generator.m_Postassembly << std::endl;
			output.close();
		}
		delete block;
	}
	catch (CompilerException* ex)
	{
		std::string msg = ex->getMessage();
		std::cerr << "An error occurred while compiling." << std::endl;
		std::cerr << msg << std::endl;
		return 1;
	}
	
	return 0;
}
int main(int argc, char* argv[]) {

    double discountFactor = 0.9;

    FILE* initFileFd = NULL;
    FILE** combinedFd = NULL;
    FILE* optimalFd = NULL;

    optimistic_instance* optimistic = NULL;
    random_search_instance* random_search = NULL;
    uct_instance* uct = NULL;
    uniform_instance* uniform = NULL;

    unsigned int maxDepth = 0;
    unsigned int i = 0;
    unsigned int n = 0;
    state** initialStates = NULL;
    unsigned int timestamp = time(NULL);
    double* optimalValues = NULL;
    int readFscanf = -1;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_int* d = arg_int1("d", NULL, "<n>", "Maximum depth of an uniform tree which the number of call per step");
    struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_file* optimal = arg_file1(NULL, "optimal", "<file>", "File containing the optimal values");
    struct arg_end* end = arg_end(6);

    void* argtable[6];
    int nerrors = 0;

    argtable[0] = initFile;
    argtable[1] = where;
    argtable[2] = d;
    argtable[3] = k;
    argtable[4] = optimal;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    K = k->ival[0];
    initGenerativeModel();

    optimalFd = fopen(optimal->filename[0], "r");
    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &n);
    initialStates = (state**)malloc(sizeof(state*) * n);
    
    for(i = 0; i < n; i++) {
        char str[1024];
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }

    maxDepth = d->ival[0];

    combinedFd = (FILE**)malloc(sizeof(FILE*) * maxDepth);

    for(i = 1; i <= maxDepth; i++) {
        char str[1024];
        sprintf(str, "%s/%u_combined_%u_%u.csv", where->filename[0], timestamp, K, i);
        combinedFd[i - 1] = fopen(str, "w");
        fprintf(combinedFd[i - 1], "n,optimistic,random search,uct,uniform\n");
    }

    arg_freetable(argtable, 6);

    optimalValues = (double*)malloc(sizeof(double) * K);

    optimistic = optimistic_initInstance(initialStates[0], discountFactor);
    random_search = random_search_initInstance(initialStates[0], discountFactor);
    uct = uct_initInstance(initialStates[0], discountFactor);
    uniform = uniform_initInstance(initialStates[0], discountFactor);

    for(i = 0; i < n; i++) {
        unsigned int j = 1;
        unsigned int maxNbIterations = K;
        unsigned int optimalAction = 0;
        char str[1024];

        readFscanf = fscanf(optimalFd, "%s\n", str);
        optimalValues[0] = strtod(strtok(str, ","), NULL);
        printf("%.15f,",optimalValues[0]);

        for(; j < K; j++) {
            optimalValues[j] = strtod(strtok(NULL, ","), NULL);
            printf("%.15f,",optimalValues[j]);
        }

        optimalAction = atol(strtok(NULL, ","));
        printf("%u\n",optimalAction);

        for(j = 1; j <= maxDepth; j++) {
            unsigned int crtOptimalAction = getActionId(optimistic_planning(optimistic, maxNbIterations));
            fprintf(combinedFd[j - 1], "%u,", maxNbIterations);
            fprintf(combinedFd[j - 1], "%.15f,", crtOptimalAction == optimalAction ? 0.0 : optimalValues[optimalAction] - optimalValues[crtOptimalAction]);
            maxNbIterations += pow(K, j+1);
        }
        if(i < (n - 1))
            optimistic_resetInstance(optimistic, initialStates[i+1]);

        printf("optimistic: %uth initial state processed\n", i+1);

        fflush(NULL);


        maxNbIterations = K;
        for(j = 1; j <= maxDepth; j++) {
            unsigned int crtOptimalAction = getActionId(random_search_planning(random_search, maxNbIterations));
            fprintf(combinedFd[j - 1], "%.15f,", crtOptimalAction == optimalAction ? 0.0 : optimalValues[optimalAction] - optimalValues[crtOptimalAction]);
            maxNbIterations += pow(K, j+1);
        }
        if(i < (n - 1))
            random_search_resetInstance(random_search, initialStates[i + 1]);

        printf("random_search: %uth initial state processed\n", i+1);

        fflush(NULL);


        maxNbIterations = K;
        for(j = 1; j <= maxDepth; j++) {
            unsigned int crtOptimalAction = getActionId(uct_planning(uct, maxNbIterations));
            fprintf(combinedFd[j - 1], "%.15f,", crtOptimalAction == optimalAction ? 0.0 : optimalValues[optimalAction] - optimalValues[crtOptimalAction]);
            maxNbIterations += pow(K, j+1);
        }
        if(i < (n - 1))
            uct_resetInstance(uct, initialStates[i + 1]);

        printf("uct: %uth initial state processed\n", i+1);

        fflush(NULL);


        maxNbIterations = K;
        for(j = 1; j <= maxDepth; j++) {
            unsigned int crtOptimalAction = getActionId(uniform_planning(uniform, maxNbIterations));
            fprintf(combinedFd[j - 1], "%.15f\n", crtOptimalAction == optimalAction ? 0.0 : optimalValues[optimalAction] - optimalValues[crtOptimalAction]);
            maxNbIterations += pow(K, j+1);
        }
        if(i < (n - 1))
            uniform_resetInstance(uniform, initialStates[i + 1]);

        printf("uniform: %uth initial state processed\n", i+1);

        printf("%uth initial state processed\n", i+1);

        fflush(NULL);

    }

    for(i = 0; i < maxDepth; i++) {
        fclose(combinedFd[i]);
    }

    for(i = 0; i < n; i++)
        freeState(initialStates[i]);

    free(initialStates);

    free(combinedFd);

    optimistic_uninitInstance(&optimistic);
    random_search_uninitInstance(&random_search);
    uct_uninitInstance(&uct);
    uniform_uninitInstance(&uniform);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
Example #13
0
int main(int argc, char *argv[]) {
    SDL_AudioSpec want, have;
    SDL_AudioDeviceID dev;
    Streamer streamer;
    int retcode = 0;

    // Init SDL Audio
    if(SDL_Init(SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "Error: %s\n", SDL_GetError());
        return 1;
    }

    // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "SOUNDS.DAT file");
    struct arg_file *output = arg_file0("o", "output", "<file>", "Output sounds file");
    struct arg_int *sid = arg_int0("s", "sound", "<int>", "Sound ID");
    struct arg_int *sampleprint = arg_int0(NULL, "print", "<int>", "Print first n bytes from selected sound");
    struct arg_lit *play = arg_lit0("p", "play", "Play selected sound");
    struct arg_file *export = arg_file0("e", "export", "<file>", "Export selected sound to AU file");
    struct arg_file *import = arg_file0("i", "import", "<file>", "Import selected sound from AU file");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,output,sid,sampleprint,play,export,import,end};
    const char* progname = "soundtool";

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 SOUNDS.DAT file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2013 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Open sounds.dat
    sd_sound_file sf;
    sd_sounds_create(&sf);
    retcode = sd_sounds_load(&sf, file->filename[0]);
    if(retcode) {
        printf("Error %d: %s\n", retcode, sd_get_error(retcode));
        goto exit_1;
    }

    if(sid->count > 0) {
        // Sound ID to handle
        int sound_id = sid->ival[0];
        const sd_sound *sound = sd_sounds_get(&sf, sound_id-1);
        if(sound == NULL) {
            printf("Invalid sound ID");
            goto exit_1;
        }

        if(sampleprint->count > 0) {
            int count = (sampleprint->ival[0] > sound->len) ? sound->len : sampleprint->ival[0];
            printf("Sample size = %d\n", sound->len);
            printf("Unknown = %d\n", sound->unknown);
            printf("Attempting to print %d first bytes.\n", count);
            for(int i = 0; i < count; i++) {
                unsigned int s = sound->data[i] & 0xFF;
                printf("%2x ", s);
            }
        } else if(play->count > 0) {
            printf("Attempting to play sample #%d.\n", sound_id);

            // Make sure there is data at requested ID position
            if(sound->len <= 0) {
                printf("Sample does not contain data.\n");
                goto exit_1;
            }

            // Streamer
            streamer.size = sound->len;
            streamer.pos = 0;
            streamer.data = sound->data;

            // Initialize required audio
            SDL_zero(want);
            want.freq = 8000;
            want.format = AUDIO_U8;
            want.channels = 1;
            want.samples = 4096;
            want.callback = stream;
            want.userdata = &streamer;

            // Open device, play file
            dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0);
            if(dev == 0) {
                printf("Failed to open audio dev: %s\n", SDL_GetError());
                goto exit_0;
            } else {
                if(have.format != want.format) {
                    printf("Could not get correct playback format.\n");
                } else {
                    printf("Starting playback ...\n");
                    SDL_PauseAudioDevice(dev, 0);
                    while(streamer.pos < streamer.size) {
                        SDL_Delay(100);
                    }
                    printf("All done.\n");
                }
                SDL_CloseAudioDevice(dev);
            }
        } else if(import->count > 0) {
            if(sd_sound_from_au(&sf, sound_id, import->filename[0]) != SD_SUCCESS) {
                printf("Importing sample %d from file %s failed.\n", sound_id, import->filename[0]);
            } else {
                printf("Importing sample %d from file %s succeeded.\n", sound_id, import->filename[0]);
            }
        } else if(export->count > 0) {
            if(sd_sound_to_au(&sf, sound_id, export->filename[0]) != SD_SUCCESS) {
                printf("Exporting sample %d to file %s failed.\n", sound_id, export->filename[0]);
            } else {
                printf("Exporting sample %d to file %s succeeded.\n", sound_id, export->filename[0]);
            }
        } else {
Example #14
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

int Rslt;
int Idx;
int iMode = 0;			// processing mode
int iRandSeed = 0;		// random base seed to use (if < 0 then current time used to seed generator)

int KMerLen;			// what length kmer to generate for 1..cMaxKMerLen

int NumInFileSpecs;			// number of input file specs 
char *pszInFiles[cMaxInFileSpecs];			// input control aligned reads files

char szOutputFile[_MAX_PATH];

// command line args
struct arg_lit  *help    = arg_lit0("hH","help",                "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to screen and logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_int  *Mode = arg_int0("m","mode","<int>",			"processing mode - 0 randomise genome");
struct arg_int  *kmerlen = arg_int0("k","kmerlen","<int>",		"maintain frequency composition of K-mer length (default = 1, range 1..15)");

struct arg_file *InFiles = arg_filen("i",NULL,"<file>",1,cMaxInFileSpecs, "input genome assembly multifasta files (s) to randomise");
struct arg_file *OutFile= arg_file1("o",NULL,"<file>",			"output randomised assembly to this file as multifasta");
struct arg_int *RandSeed = arg_int0("s","randseed","<int>",		"random seed to use (default is use system time)");
struct arg_end *end = arg_end(20);

void *argtable[] = {help,version,FileLogLevel,LogFile,Mode,kmerlen,InFiles,OutFile,RandSeed,end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s Kanga randomise genome K-mers, Version %s\nOptions ---\n", gszProcName,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s @myparams.txt\n",gszProcName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		exit(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s Version %s\n",gszProcName,cpszProgVer);
		exit(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>\n'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d\n",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}
	
	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	// now that log parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem\n");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created\n",szLogFile);
		exit(1);
		}

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s",cpszProgVer);

	iMode = Mode->count ? Mode->ival[0] : 0;
	if(iMode < 0 || iMode >= cMaxSupportedModes)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Unsupported Mode '-m%d' requested",iMode);
		exit(1);
		}

	KMerLen = 0;
	switch(iMode) {
		case 0:					// generate random species fasta sequence
			for(NumInFileSpecs=Idx=0;NumInFileSpecs < cMaxInFileSpecs && Idx < InFiles->count; Idx++)
				{
				pszInFiles[Idx] = NULL;
				if(pszInFiles[NumInFileSpecs] == NULL)
					pszInFiles[NumInFileSpecs] = new char [_MAX_PATH];
				strncpy(pszInFiles[NumInFileSpecs],InFiles->filename[Idx],_MAX_PATH);
				pszInFiles[NumInFileSpecs][_MAX_PATH-1] = '\0';
				CUtility::TrimQuotedWhitespcExtd(pszInFiles[NumInFileSpecs]);
				if(pszInFiles[NumInFileSpecs][0] != '\0')
					NumInFileSpecs++;
				}

			if(!NumInFileSpecs)
				{
				gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no input file(s) specified with '-i<filespec>' option)\n");
				exit(1);
				}


			KMerLen = kmerlen->count ? kmerlen->ival[0] : cDfltKMerLen;
			if(KMerLen < 1 || KMerLen > cMaxKMerLen)
				{
				gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: K-mer length specified with '-k%d' is outside of range 1..10",KMerLen);
				exit(1);
				}
			

			if(!OutFile->count || OutFile->filename[0][0] == '\0')
				{
				gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: No output fasta file specified with '-o<filename>'");
				exit(1);
				}
			strncpy(szOutputFile,OutFile->filename[0],_MAX_PATH);
			szOutputFile[_MAX_PATH] = '\0';

			if(!RandSeed->count)
				iRandSeed = -1;
			else
				{
				iRandSeed = RandSeed->ival[0];
				if(iRandSeed < 0 || iRandSeed > 32767)
					{
					gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Random seed specified as '-s%d' must be between 0 and 32767",iRandSeed);
					exit(1);
					}
				}
			break;

		}

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing parameters:");



	switch(iMode) {
		case 0:
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Mode: 0 (randomise genome K-mers)");
			for(Idx=0; Idx < NumInFileSpecs; Idx++)
				gDiagnostics.DiagOutMsgOnly(eDLInfo,"Use frequency compositions from these genome multifasta file(s) (%d): '%s'",Idx+1,pszInFiles[Idx]);
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maintain K-mer composition of length: %d",KMerLen);
			gDiagnostics.DiagOutMsgOnly(eDLInfo,"Genome output file: '%s'",szOutputFile);
			if(iRandSeed >= 0)
				gDiagnostics.DiagOutMsgOnly(eDLInfo,"Random seed: %d",iRandSeed);
			else
				gDiagnostics.DiagOutMsgOnly(eDLInfo,"Random seed: will use current time as seed");
			break;
		}
	
	gStopWatch.Start();
#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	Rslt = GenerateRandFasta(iMode,KMerLen,NumInFileSpecs,pszInFiles,szOutputFile,iRandSeed);
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	printf("\n%s Kanga randomise genome K-mers, Version %s\n",gszProcName,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
return 0;
}
Example #15
0
int main(int argc, char* argv[])
{
	// Define our variables.
	FILE* load;
	uint16_t flash[0x10000];
	char leading[0x100];
	unsigned int i;
	bool uread = true;
	vm_t* vm;
	int nerrors;
	bstring ss, st;

	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file, or - to read from standard input.");
	struct arg_file* execution_dump_file = arg_file0("e", "execution-dump", "<file>", "Produce a very large execution dump file.");
	struct arg_lit* debug_mode = arg_lit0("d", "debug", "Show each executed instruction.");
	struct arg_lit* terminate_mode = arg_lit0("t", "show-on-terminate", "Show state of machine when program is terminated.");
	struct arg_lit* legacy_mode = arg_lit0("l", "legacy", "Automatically initialize hardware to legacy values.");
	struct arg_lit* little_endian_mode = arg_lit0(NULL, "little-endian", "Use little endian serialization (for compatibility with older versions).");
	struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
	struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
	struct arg_end* end = arg_end(20);
	void* argtable[] = { input_file, debug_mode, execution_dump_file, terminate_mode, legacy_mode, little_endian_mode, verbose, quiet, end };

	// Parse arguments.
	nerrors = arg_parse(argc, argv, argtable);

	version_print(bautofree(bfromcstr("Emulator")));
	if (nerrors != 0 || show_help->count != 0)
	{
		if (show_help->count != 0)
			arg_print_errors(stdout, end, "emulator");

		printd(LEVEL_DEFAULT, "syntax:\n    dtemu");
		arg_print_syntax(stderr, argtable, "\n");
		printd(LEVEL_DEFAULT, "options:\n");
		arg_print_glossary(stderr, argtable, "	  %-25s %s\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Set verbosity level.
	debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

	// Set global path variable.
	osutil_setarg0(bautofree(bfromcstr(argv[0])));

	// Set endianness.
	isetmode(little_endian_mode->count == 0 ? IMODE_BIG : IMODE_LITTLE);

	// Zero out the flash space.
	for (i = 0; i < 0x10000; i++)
		flash[i] = 0x0;

	// Zero out the leading space.
	for (i = 0; i < 0x100; i++)
		leading[i] = 0x0;

	// Load from either file or stdin.
	if (strcmp(input_file->filename[0], "-") != 0)
	{
		// Open file.
		load = fopen(input_file->filename[0], "rb");

		if (load == NULL)
		{
			fprintf(stderr, "emulator: unable to load %s from disk.\n", argv[1]);
			arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
			return 1;
		}
	}
	else
	{
		// Windows needs stdin in binary mode.
#ifdef _WIN32
		_setmode(_fileno(stdin), _O_BINARY);
#endif

		// Set load to stdin.
		load = stdin;
	}

	// Read up to 0x10000 words.
	for (i = 0; i < 0x10000 && !feof(load); i++)
		iread(&flash[i], load);
	fclose(load);

	// Check to see if the first X bytes matches the header
	// for intermediate code and stop if it does.
	ss = bfromcstr("");
	st = bfromcstr(ldata_objfmt);
	for (i = 0; i < strlen(ldata_objfmt); i++)
		bconchar(ss, leading[i]);
	if (biseq(ss, st))
	{
		fprintf(stderr, "emulator: it appears you passed intermediate code for execution.  link\n");
		fprintf(stderr, "	   the input code with the toolchain linker to execute it.\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// And then use the VM.
	vm = vm_create();
	vm->debug = (debug_mode->count > 0);
	vm_flash(vm, flash);
	vm_hw_timer_init(vm);
	vm_hw_io_init(vm);
	vm_hw_lem1802_init(vm);
	vm_hw_lua_init(vm);
	if (legacy_mode->count > 0)
	{
		vm_hw_lem1802_mem_set_screen(vm, 0x8000);
		vm_hw_io_set_legacy(true);
	}
	vm_execute(vm, execution_dump_file->count > 0 ? execution_dump_file->filename[0] : NULL);

#ifdef __EMSCRIPTEN__
	printd(LEVEL_WARNING, "warning: not cleaning up resources in Emscripten.\n");
#else
	if (terminate_mode->count > 0)
	{
		fprintf(stderr, "\n");
		fprintf(stderr, "A:   0x%04X	 [A]:	0x%04X\n", vm->registers[REG_A], vm->ram[vm->registers[REG_A]]);
		fprintf(stderr, "B:   0x%04X	 [B]:	0x%04X\n", vm->registers[REG_B], vm->ram[vm->registers[REG_B]]);
		fprintf(stderr, "C:   0x%04X	 [C]:	0x%04X\n", vm->registers[REG_C], vm->ram[vm->registers[REG_C]]);
		fprintf(stderr, "X:   0x%04X	 [X]:	0x%04X\n", vm->registers[REG_X], vm->ram[vm->registers[REG_X]]);
		fprintf(stderr, "Y:   0x%04X	 [Y]:	0x%04X\n", vm->registers[REG_Y], vm->ram[vm->registers[REG_Y]]);
		fprintf(stderr, "Z:   0x%04X	 [Z]:	0x%04X\n", vm->registers[REG_Z], vm->ram[vm->registers[REG_Z]]);
		fprintf(stderr, "I:   0x%04X	 [I]:	0x%04X\n", vm->registers[REG_I], vm->ram[vm->registers[REG_I]]);
		fprintf(stderr, "J:   0x%04X	 [J]:	0x%04X\n", vm->registers[REG_J], vm->ram[vm->registers[REG_J]]);
		fprintf(stderr, "PC:  0x%04X	 SP:	0x%04X\n", vm->pc, vm->sp);
		fprintf(stderr, "EX:  0x%04X	 IA:	0x%04X\n", vm->ex, vm->ia);
	}

	vm_hw_lua_free(vm);
	vm_hw_timer_free(vm);
	vm_hw_io_free(vm);
	vm_hw_lem1802_free(vm);
	vm_free(vm);

	arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
	return 0;
#endif
}
Example #16
0
int main(int argc, char *argv[]) {
   // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "language file");
    struct arg_int *str = arg_int1("s", "string", "<value>", "print language string # (-1 for all).");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,str,end};
    const char* progname = "languagetool";
    
    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }
    
    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }
    
    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 Language file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2013 Tuomas Virtanen\n");
        goto exit_0;
    }
    
    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }
    
    // Get strings
    sd_language *language = sd_language_create();
    if(sd_language_load(language, file->filename[0])) {
        printf("Language file could not be loaded!\n");
        goto exit_0;
    }
    
    // Print
    int id = str->ival[0];
    if(id < 0) {
        for(int i = 0; i < language->count; i++) {
            printf("Title: %s\n", language->strings[i].description);
            printf("Data: %s\n", language->strings[i].data);
        }
    } else if(id >= 0 && id < language->count) {
        printf("Title: %s\n", language->strings[id].description);
        printf("Data: %s\n", language->strings[id].data);
    } else {
        printf("String not found!\n");
    }
    
    sd_language_delete(language);
exit_0:
    arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
    return 0;
}
Example #17
0
int main(int argc, char* argv[])
{
	// Define our variables.
	FILE* in;
	FILE* out;
	int nerrors, i;
	char* test;
	uint16_t offset, current, store, mem_index;
	struct lprov_entry* required = NULL;
	struct lprov_entry* provided = NULL;
	struct lprov_entry* adjustment = NULL;
	struct lprov_entry* temp = NULL;

	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_file* input_files = arg_filen(NULL, NULL, "<file>", 1, 100, "The input object files.");
	struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
	struct arg_end *end = arg_end(20);
	void *argtable[] = { show_help, input_files, output_file, end };
	
	// Parse arguments.
	nerrors = arg_parse(argc,argv,argtable);
	if (nerrors != 0 || show_help->count != 0)
	{
		if (show_help->count != 0)
			arg_print_errors(stdout, end, "linker");
		printf("syntax:\n    linker");
		arg_print_syntax(stdout, argtable, "\n");
		printf("options:\n");
		arg_print_glossary(stdout, argtable, "    %-25s %s\n");
		return 1;
	}

	// Open the output file for writing.
	out = fopen(output_file->filename[0], "wb");
	if (out == NULL)
	{
		// Handle the error.
		fprintf(stderr, "linker: unable to write to output file.\n");
		return 1;
	}

	// We initially need to get a list of ALL provided
	// labels before we can start replacing them.
	offset = 0;
	for (i = 0; i < input_files->count; i++)
	{
		// Open the input file.
		in = fopen(input_files->filename[i], "rb");
		if (in == NULL)
		{
			// Handle the error.
			fprintf(stderr, "linker: unable to read input file '%s'.\n", input_files->filename[i]);
			fclose(out);
			return 1;
		}
		
		// Is this the object format?
		test = malloc(strlen(ldata_objfmt) + 1);
		memset(test, 0, strlen(ldata_objfmt) + 1);
		fread(test, 1, strlen(ldata_objfmt), in);
		fseek(in, 1, SEEK_CUR);
		if (strcmp(test, ldata_objfmt) != 0)
		{
			// Handle the error.
			fprintf(stderr, "linker: input file '%s' is not in object format 1.0.\n", input_files->filename[i]);
			fclose(in);
			fclose(out);
			return 1;
		}
		free(test);

		// Load only the provided label entries into memory.
		objfile_load(input_files->filename[i], in, &offset, &provided, NULL, NULL);

		// Close the file.
		fclose(in);
	}
	
	// Now we can start replacing the labels with the provided values
	// since we have ALL of the provided labels available.
	offset = 0;
	for (i = 0; i < input_files->count; i++)
	{
		// Open the input file.
		in = fopen(input_files->filename[i], "rb");
		if (in == NULL)
		{
			// Handle the error.
			fprintf(stderr, "linker: unable to read input file '%s'.\n", input_files->filename[i]);
			fclose(out);
			return 1;
		}
		
		// Skip over the object format label; we already tested
		// for this in phase 1.
		fseek(in, strlen(ldata_objfmt) + 1, SEEK_CUR);

		// Load only the required and adjustment entries into memory.
		current = offset;
		objfile_load(input_files->filename[i], in, &offset, NULL, &required, &adjustment);

		// Copy all of the input file's data into the output
		// file, word by word.
		mem_index = 0;
		fprintf(stderr, "BEGIN %s\n", input_files->filename[i]);
		while (!feof(in))
		{
			// Read a word.
			fread(&store, sizeof(uint16_t), 1, in);

			// For some strange reason, the last two bytes get
			// written twice, as if it's only EOF after you
			// attempt to read past the end again.  I'm not sure
			// why the semantics are like this, but checking again
			// for EOF here prevents us writing double.
			if (feof(in))
				break;

			// Check to see if we need to do something with this
			// word, such as adjusting it.
			if (lprov_find_by_address(adjustment, mem_index) != NULL)
			{
				// We need to adjust this word by the offset.
				store += current;
				fprintf(stderr, "ADJUSTED 0x%04X: 0x%04X -> 0x%04X\n", mem_index, store - current, store);
			}

			// Check to see if we need to resolve this word into
			// an actual address because it was imported.
			temp = lprov_find_by_address(required, mem_index);
			if (temp != NULL)
			{
				// Find the position we should change this to.
				temp = lprov_find_by_label(provided, temp->label);

				// We need to set this word to the proper location.
				fprintf(stderr, "RESOLVED 0x%04X: 0x%04X -> 0x%04X\n", mem_index, store, temp->address);
				store = temp->address;
			}

			// Now write the (potentially modified) word to the
			// output.
			fprintf(stderr, " >> WRITE 0x%04X\n", store);
			fwrite(&store, sizeof(uint16_t), 1, out);

			// Increment memory position.
			mem_index++;
		}

		// Close the file.
		fclose(in);

		// Reset and free the required and adjustment linked list.
		// FIXME: Actually free the lists!
		required = NULL;
		adjustment = NULL;
	}

	// Close file.
	fprintf(stderr, "linker: completed successfully.\n", input_files->filename[i]);
	fclose(out);

	return 0;
}
Example #18
0
int main(int argc, char *argv[]) {
   // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "Score file");
    struct arg_int *page = arg_int0("p", "page", "<int>", "Page ID");
    struct arg_file *output = arg_file0("o", "output", "<file>", "Output file");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,page,output,end};
    const char* progname = "scoretool";

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 Score file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2014 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Get score information
    sd_score score;
    sd_score_create(&score);
    int ret = sd_score_load(&score, file->filename[0]);
    if(ret != SD_SUCCESS) {
        printf("Score file %s could not be loaded: %s\n",
            file->filename[0],
            sd_get_error(ret));
        goto exit_0;
    }

    // See if we want to print a single page or all pages
    if(page->count > 0) {
        int page_id = page->ival[0];
        if(page_id < 0 || page_id >= SD_SCORE_PAGES) {
            printf("Page must be between 0 and 3.\n");
            goto exit_1;
        }

        // Print only this page
        print_page(&score, page_id);
    } else {
        for(int i = 0; i < SD_SCORE_PAGES; i++) {
            print_page(&score, i);
            printf("\n");
        }
    }

    // Save if necessary
    if(output->count > 0) {
        ret = sd_score_save(&score, output->filename[0]);
        if(ret != SD_SUCCESS) {
            printf("Failed to save scores file to %s: %s\n",
                output->filename[0],
                sd_get_error(ret));
        }
    }

exit_1:
    sd_score_free(&score);
exit_0:
    arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
    return 0;
}
Example #19
0
int main(int argc, char* argv[])
{
    // Define our variables.
    FILE* load;
    uint16_t flash[0x10000];
    char leading[0x100];
    unsigned int i;
    bool uread = true;
    vm_t* vm;
    int nerrors;
    bstring ss, st;
    host_context_t* dtemu = malloc(sizeof(host_context_t));
    const char* warnprefix = "no-";

    // Define arguments.
    struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
    struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file, or - to read from standard input.");
    struct arg_file* execution_dump_file = arg_file0("e", "execution-dump", "<file>", "Produce a very large execution dump file.");
    struct arg_lit* debug_mode = arg_lit0("d", "debug", "Show each executed instruction.");
    struct arg_lit* terminate_mode = arg_lit0("t", "show-on-terminate", "Show state of machine when program is terminated.");
    struct arg_lit* headless_mode = arg_lit0("h", "headless", "Run machine witout displaying monitor and SPED output");
    struct arg_lit* legacy_mode = arg_lit0("l", "legacy", "Automatically initialize hardware to legacy values.");
    struct arg_str* warning_policies = arg_strn("W", NULL, "policy", 0, _WARN_COUNT * 2 + 10, "Modify warning policies.");
    struct arg_lit* little_endian_mode = arg_lit0(NULL, "little-endian", "Use little endian serialization (for compatibility with older versions).");
    struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
    struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
    struct arg_int* radiation = arg_intn("r", NULL, "<n>", 0, 1, "Radiation factor (higher is less radiation)");
    struct arg_lit* catch_fire = arg_lit0("c", "catch-fire", "The virtual machine should catch fire instead of halting.");
    struct arg_end* end = arg_end(20);
    void* argtable[] = { input_file, warning_policies, debug_mode, execution_dump_file, terminate_mode, headless_mode, legacy_mode, little_endian_mode, radiation, catch_fire, verbose, quiet, end };

    // Parse arguments.
    nerrors = arg_parse(argc, argv, argtable);

    if (nerrors != 0 || show_help->count != 0)
    {
        if (show_help->count != 0)
            arg_print_errors(stdout, end, "emulator");

        printd(LEVEL_DEFAULT, "syntax:\n    dtemu");
        arg_print_syntax(stderr, argtable, "\n");
        printd(LEVEL_DEFAULT, "options:\n");
        arg_print_glossary(stderr, argtable, "      %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Set verbosity level.
    debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);
    
    // Show version information.
    version_print(bautofree(bfromcstr("Emulator")));

    // Set global path variable.
    osutil_setarg0(bautofree(bfromcstr(argv[0])));

    // Set endianness.
    isetmode(little_endian_mode->count == 0 ? IMODE_BIG : IMODE_LITTLE);

    // Set up warning policies.
    dsetwarnpolicy(warning_policies);
    
    // Set up error handling.
    if (dsethalt())
    {
        // Handle the error.
        dautohandle();
        printd(LEVEL_ERROR, "emulator: error occurred.\n");

        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Zero out the flash space.
    for (i = 0; i < 0x10000; i++)
        flash[i] = 0x0;

    // Zero out the leading space.
    for (i = 0; i < 0x100; i++)
        leading[i] = 0x0;

    // Load from either file or stdin.
    if (strcmp(input_file->filename[0], "-") != 0)
    {
        // Open file.
        load = fopen(input_file->filename[0], "rb");

        if (load == NULL)
            dhalt(ERR_EMU_LOAD_FILE_FAILED, input_file->filename[0]);
    }
    else
    {
        // Windows needs stdin in binary mode.
#ifdef _WIN32
        _setmode(_fileno(stdin), _O_BINARY);
#endif

        // Set load to stdin.
        load = stdin;
    }
    
    // Read leading component.
    for (i = 0; i < strlen(ldata_objfmt); i++)
        leading[i] = fgetc(load);
    fseek(load, 0, SEEK_SET);

    // Read up to 0x10000 words.
    for (i = 0; i < 0x10000 && !feof(load); i++)
        iread(&flash[i], load);
    fclose(load);

    // Check to see if the first X bytes matches the header
    // for intermediate code and stop if it does.
    ss = bfromcstr("");
    st = bfromcstr(ldata_objfmt);
    for (i = 0; i < strlen(ldata_objfmt); i++)
        bconchar(ss, leading[i]);
    if (biseq(ss, st))
        dhalt(ERR_INTERMEDIATE_EXECUTION, NULL);

    // Set up the host context.
    glfwInit();
    dtemu->create_context = &dtemu_create_context;
    dtemu->activate_context = &dtemu_activate_context;
    dtemu->swap_buffers = &dtemu_swap_buffers;
    dtemu->destroy_context = &dtemu_destroy_context;
    dtemu->get_ud = &dtemu_get_ud;

    // And then use the VM.
    vm = vm_create();
    vm->debug = (debug_mode->count > 0);
    vm_flash(vm, flash);

    // Set radiation and catch fire settings.
    if (radiation->count == 1)
        vm->radiation_factor = radiation->ival[0];
    if (catch_fire->count == 1)
        vm->can_fire = true;

    // Init hardware.
    vm_hw_clock_init(vm);

    if (headless_mode->count < 1)
        vm->host = dtemu;

    vm_hw_sped3_init(vm);
    vm_hw_lem1802_init(vm);
    vm_hw_m35fd_init(vm);
    vm_hw_lua_init(vm);

    if (legacy_mode->count > 0)
    {
        for (i = 0; i < vm_hw_count(vm); i++) {

            hw_t* device = vm_hw_get_device(vm, i);
            if (device == NULL)
                continue;

            if (device->id == 0x7349F615 && device->manufacturer == 0x1C6C8B36)
            {
                vm_hw_lem1802_mem_set_screen((struct lem1802_hardware*)device->userdata, 0x8000);
                break;
            }
        }
    }

    vm_execute(vm, execution_dump_file->count > 0 ? execution_dump_file->filename[0] : NULL);

    if (terminate_mode->count > 0)
    {
        fprintf(stderr, "\n");
        fprintf(stderr, "A:   0x%04X     [A]:    0x%04X\n", vm->registers[REG_A], vm->ram[vm->registers[REG_A]]);
        fprintf(stderr, "B:   0x%04X     [B]:    0x%04X\n", vm->registers[REG_B], vm->ram[vm->registers[REG_B]]);
        fprintf(stderr, "C:   0x%04X     [C]:    0x%04X\n", vm->registers[REG_C], vm->ram[vm->registers[REG_C]]);
        fprintf(stderr, "X:   0x%04X     [X]:    0x%04X\n", vm->registers[REG_X], vm->ram[vm->registers[REG_X]]);
        fprintf(stderr, "Y:   0x%04X     [Y]:    0x%04X\n", vm->registers[REG_Y], vm->ram[vm->registers[REG_Y]]);
        fprintf(stderr, "Z:   0x%04X     [Z]:    0x%04X\n", vm->registers[REG_Z], vm->ram[vm->registers[REG_Z]]);
        fprintf(stderr, "I:   0x%04X     [I]:    0x%04X\n", vm->registers[REG_I], vm->ram[vm->registers[REG_I]]);
        fprintf(stderr, "J:   0x%04X     [J]:    0x%04X\n", vm->registers[REG_J], vm->ram[vm->registers[REG_J]]);
        fprintf(stderr, "PC:  0x%04X     SP:    0x%04X\n", vm->pc, vm->sp);
        fprintf(stderr, "EX:  0x%04X     IA:    0x%04X\n", vm->ex, vm->ia);
    }

    vm_hw_lua_free(vm);
    vm_free(vm);

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    glfwTerminate();
    return 0;
}
Example #20
0
int main(int argc, char* argv[])
{
	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_str* type_assembler = arg_str0("t", NULL, "<type>", "The type of assembler to output for.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file (or - to read from standard input).");
	struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
	// 20 is maxcount for include directories, this has to be set to some constant number.
	struct arg_file* include_dirs = arg_filen("I", NULL, "<directory>", 0, 20, "Adds the directory <dir> to the directories to be searched for header files.");
	struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
	struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
	struct arg_end* end = arg_end(20);
	void* argtable[] = { output_file, show_help, type_assembler, include_dirs, input_file, verbose, quiet, end };

	// Parse arguments.
	int nerrors = arg_parse(argc, argv, argtable);

	version_print(bautofree(bfromcstr("Compiler")));
	if (nerrors != 0 || show_help->count != 0)
	{
		if (nerrors != 0)
			arg_print_errors(stderr, end, "compiler");

		fprintf(stderr, "syntax:\n    dtcc");
		arg_print_syntax(stderr, argtable, "\n");
		fprintf(stderr, "options:\n");
		arg_print_glossary(stderr, argtable, "	  %-25s %s\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Set verbosity level.
	debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

	// Set global path variable.
	osutil_setarg0(bautofree(bfromcstr(argv[0])));

	// Run the preprocessor.
	ppfind_add_path(bautofree(bfromcstr(".")));
	ppfind_add_path(bautofree(bfromcstr("include")));
	ppfind_add_autopath(bautofree(bfromcstr(input_file->filename[0])));
	for (int i = 0; i < include_dirs->count; ++i)
		ppfind_add_path(bautofree(bfromcstr(include_dirs->filename[i])));
	bstring pp_result_name = pp_do(bautofree(bfromcstr(input_file->filename[0])));

	if (pp_result_name == NULL)
	{
		fprintf(stderr, "compiler: invalid result returned from preprocessor.\n");
		pp_cleanup(bautofree(pp_result_name));
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Parse C.
	yyout = stderr;
	yyin = fopen((const char*)(pp_result_name->data), "r");

	if (yyin == NULL)
	{
		pp_cleanup(bautofree(pp_result_name));
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	yyparse();

	if (yyin != stdin)
		fclose(yyin);

	pp_cleanup(bautofree(pp_result_name));

	if (program == NULL)
	{
		std::cerr << "An error occurred while compiling." << std::endl;
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Assembler type.
	const char* asmtype = "toolchain";

	if (type_assembler->count > 0)
		asmtype = type_assembler->sval[0];

	// Initially save to a temporary file.
	std::string temp = std::string(tempnam(".", "cc."));

	// Generate assembly using the AST.
	try
	{
		AsmGenerator generator(asmtype);
		AsmBlock* block = program->compile(generator);

		std::ofstream output(temp.c_str(), std::ios::out | std::ios::trunc);
		if (output.bad() || output.fail())
		{
			printd(LEVEL_ERROR, "compiler: temporary file not writable.\n");
			arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
			return 1;
		}
		output << *block << std::endl;
		output.close();

		delete block;
	}
	catch (CompilerException* ex)
	{
		std::string msg = ex->getMessage();
		std::cerr << "An error occurred while compiling." << std::endl;
		std::cerr << msg << std::endl;
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Re-open the temporary file for reading.
	std::ifstream input(temp.c_str(), std::ios::in);
	if (input.bad() || input.fail())
	{
		printd(LEVEL_ERROR, "compiler: temporary file not readable.\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Open the output file.
	std::ostream* output;
	if (strcmp(output_file->filename[0], "-") != 0)
	{
		// Write to file.
		output = new std::ofstream(output_file->filename[0], std::ios::out | std::ios::trunc);

		if (output->bad() || output->fail())
		{
			printd(LEVEL_ERROR, "compiler: output file not readable.\n");
			arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
			return 1;
		}
	}
	else
	{
		// Set output to cout.
		output = &std::cout;
	}

	// Copy data.
	std::copy(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(*output));

	// Close files and delete temporary.
	if (strcmp(output_file->filename[0], "-") != 0)
	{
		((std::ofstream*)output)->close();
		delete output;
	}
	input.close();
	unlink(temp.c_str());

	arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
	return 0;
}
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.99;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    unsigned int* hs = NULL;
    unsigned int nbH = 0;
    unsigned int n = 0;
    unsigned int nbSteps = 0;
    unsigned int nbIterations = 1;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    random_search_instance* random_search = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of maximum numbers of evaluations");
    struct arg_str* d = arg_str1("h", NULL, "<s>", "List of depth");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_int* it = arg_int1("i", NULL, "<n>", "Number of iteration");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(7);

    int nerrors = 0;
    void* argtable[7];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = d;
    argtable[3] = s;
    argtable[4] = it;
    argtable[5] = where;
    argtable[6] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &n);
    initialStates = (state**)malloc(sizeof(state*) * n);
    
    for(; i < n; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    nbIterations = it->ival[0];
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);
    hs = parseUnsignedIntList((char*)d->sval[0], &nbH);

    random_search = random_search_initInstance(NULL, discountFactor);
    h_max = h_max_crt_depth;

    sprintf(str, "%s/%u_results_random_search_%s.csv", where->filename[0], timestamp,(char*)r->sval[0]);
    results = fopen(str, "w");

    for(i = 0; i < nbIterations; i++) {
        unsigned int j = 0;

        for(;j < nbH; j++) {
            unsigned int k = 0;

            crtDepth = hs[j];

            for(; k < nbN; k++) {
                unsigned int l = 0;
                double sumRewards = 0.0;

                for(; l < n; l++) {
                    unsigned int m = 0;
                    state* crt = copyState(initialStates[l]);

                    for(; m < nbSteps; m++) {
                        char isTerminal = 0;
                        double reward = 0.0;
                        state* nextState = NULL;
                        double* optimalAction = NULL;

                        random_search_resetInstance(random_search, crt);
                        optimalAction = random_search_planning(random_search, ns[k]);
                        isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                        freeState(crt);
                        free(optimalAction);
                        crt = nextState;
                        sumRewards += reward;
                        if(isTerminal)
                            break;
                    }
                    random_search_resetInstance(random_search, crt);
                    freeState(crt);

                    printf(">>>>>>>>>>>>>> %uth initial state processed with h=%u and n=%u of iteration %u\n", l + 1, hs[j], ns[k], i+1);
                    fflush(NULL);
                }

                fprintf(results, "%u,%u,%.15f\n", hs[j],ns[k], sumRewards / (double)n);
                printf(">>>>>>>>>>>>>> n = %u  done\n\n", ns[k]);
                fflush(NULL);
            }
            printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> h = %u done \n\n", hs[j]);
            fflush(NULL);
        }

        fprintf(results,"\n");
        printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ITERATION %u DONE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n", i+1);
        fflush(NULL);

    }

    fclose(results);

    arg_freetable(argtable, 7);

    for(i = 0; i < n; i++)
        freeState(initialStates[i]);

    free(initialStates);

    random_search_uninitInstance(&random_search);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
int main(int argc, char* argv[]) {

    double discountFactor = 0.9;

    FILE* initFileFd = NULL;
    double* setPoints = NULL;
    unsigned int nbSetPoints = 0;
    unsigned int maxDepth = 0;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int minDepth = 1;
    unsigned int crtDepth = 0;
    unsigned int maxNbIterations = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    optimistic_instance* optimistic = NULL;
    random_search_instance* random_search = NULL;
    uct_instance* uct = NULL;
    uniform_instance* uniform = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the set points");
    struct arg_int* d2 = arg_int0(NULL, "min", "<n>", "Minimum depth to start from (min>0)");
    struct arg_int* d = arg_int1("d", NULL, "<n>", "Maximum depth of an uniform tree which the number of call per step");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(7);

    int nerrors = 0;
    void* argtable[7];

    argtable[0] = initFile;
    argtable[1] = d2;
    argtable[2] = d;
    argtable[3] = s;
    argtable[4] = k;
    argtable[5] = where;
    argtable[6] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    K = k->ival[0];
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &nbSetPoints);
    setPoints = (double*)malloc(sizeof(double) * nbSetPoints);
    
    for(; i < nbSetPoints; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        setPoints[i] = strtod(str, NULL);
    }
    fclose(initFileFd);

    if(d2->count)
        minDepth = d2->ival[0];
    maxDepth = d->ival[0];
    maxNbIterations = K;
    nbSteps = s->ival[0];

    optimistic = optimistic_initInstance(NULL, discountFactor);
    random_search = random_search_initInstance(NULL, discountFactor);
    uct = uct_initInstance(NULL, discountFactor);
    uniform = uniform_initInstance(NULL, discountFactor);

    sprintf(str, "%s/%u_results_%u_%u.csv", where->filename[0], timestamp, K, nbSteps);
    results = fopen(str, "w");

    for(crtDepth = 1; crtDepth < minDepth; crtDepth++)
        maxNbIterations += pow(K, crtDepth+1);

    for(crtDepth = minDepth; crtDepth <= maxDepth; crtDepth++) {
        double averages[4] = {0.0, 0.0, 0.0, 0.0};
        state* crt1 = initState();
        state* crt2 = copyState(crt1);
        state* crt3 = copyState(crt1);
        state* crt4 = copyState(crt1);

        optimistic_resetInstance(optimistic, crt1);
        uct_resetInstance(uct, crt3);
        uniform_resetInstance(uniform, crt4);
        for(i = 0; i < nbSetPoints; i++) {
            unsigned int j = 0;

            parameters[10] = setPoints[i];

            for(; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                optimistic_keepSubtree(optimistic);
                action* optimalAction = optimistic_planning(optimistic, maxNbIterations);
                isTerminal = nextStateReward(crt1, optimalAction, &nextState, &reward);
                freeState(crt1);
                crt1 = nextState;
                averages[0] += reward;
                if(isTerminal < 0)
                    break;
            }
            optimistic_resetInstance(optimistic, crt1);

            printf("Optimistic   : %uth set point processed\n", i + 1);

            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                random_search_resetInstance(random_search, crt2);
                action* optimalAction = random_search_planning(random_search, maxNbIterations);
                isTerminal = nextStateReward(crt2, optimalAction, &nextState, &reward);
                freeState(crt2);
                crt2 = nextState;
                averages[1] += reward;
                if(isTerminal < 0)
                    break;
            }
            random_search_resetInstance(random_search, crt1);

            printf("Random search: %uth set point processed\n", i + 1);

            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                uct_keepSubtree(uct);
                action* optimalAction = uct_planning(uct, maxNbIterations);
                isTerminal = nextStateReward(crt3, optimalAction, &nextState, &reward);
                freeState(crt3);
                crt3 = nextState;
                averages[2] += reward;
                if(isTerminal < 0)
                    break;
            }
            uct_resetInstance(uct, crt3);

            printf("Uct          : %uth set point processed\n", i + 1);

            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                uniform_keepSubtree(uniform);
                action* optimalAction = uniform_planning(uniform, maxNbIterations);
                isTerminal = nextStateReward(crt4, optimalAction, &nextState, &reward);
                freeState(crt4);
                crt4 = nextState;
                averages[3] += reward;
                if(isTerminal < 0)
                    break;
            }
            uniform_resetInstance(uniform, crt4);

            printf("Uniform      : %uth set point processed\n", i + 1);
            printf(">>>>>>>>>>>>>> %uth set point processed\n", i + 1);

        }

        fprintf(results, "%u,%.15f,%.15f,%.15f,%.15f\n", maxNbIterations, averages[0] / (double)nbSetPoints, averages[1] / (double)nbSetPoints, averages[2] / (double)nbSetPoints, averages[3] / (double)nbSetPoints);
        fflush(results);
        freeState(crt1);
        freeState(crt2);
        freeState(crt3);
        freeState(crt4);

        printf(">>>>>>>>>>>>>> %u depth done\n\n", crtDepth);

        maxNbIterations += pow(K, crtDepth+1);

    }

    fclose(results);

    arg_freetable(argtable, 7);

    free(setPoints);

    optimistic_uninitInstance(&optimistic);
    random_search_uninitInstance(&random_search);
    uct_uninitInstance(&uct);
    uniform_uninitInstance(&uniform);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
Example #23
0
int main(int argc, char* argv[]) {
    // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "Input altpals file");
    struct arg_int *pal = arg_int1("p", "palette", "<number>", "Select a palette");
    struct arg_file *export = arg_file0("e", "export", "<file>", "Export selected palette to GPL file");
    struct arg_file *import = arg_file0("i", "import", "<file>", "Import selected palette from GPL file");
    struct arg_file *output = arg_file0("o", "output", "<file>", "Output altpals file");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,pal,output,import,export,end};
    const char* progname = "altpaltool";

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 Altpals file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2014 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Need import or export ...
    if(pal->count > 0 && import->count == 0 && export->count == 0) {
        printf("Define either --import or --export with --palette!\n");
        goto exit_0;
    }

    // Make sure output is set
    if(import->count > 0 && output->count <= 0) {
        printf("Define --output with --import.\n");
        goto exit_0;
    }

    // Load file
    sd_altpal_file alt;
    sd_altpal_create(&alt);
    int ret = sd_altpals_load(&alt, file->filename[0]);
    if(ret != SD_SUCCESS) {
        printf("Unable to load altpals file %s: %s.\n",
            file->filename[0],
            sd_get_error(ret));
        goto exit_1;
    }

    // Check ID
    int pal_id = pal->ival[0];
    if(pal_id < 0 || pal_id > SD_ALTPALS_PALETTES) {
        printf("Palette index %d does not exist!\n", pal_id);
        goto exit_1;
    }

    // Check what to do
    if(export->count > 0) {
        ret = sd_palette_to_gimp_palette(&alt.palettes[pal_id], export->filename[0]);
        if(ret == SD_SUCCESS) {
            printf("Palette %d exported to file %s succesfully.\n",
                pal_id,
                export->filename[0]);
        } else {
Example #24
0
int main(int argc, char *argv[]) {
    
#ifndef _OPENMP
    fprintf(stderr, "\nERROR: Program built with compiler lacking OpenMP support.\n");
    fprintf(stderr, "See SEAStAR README file for information about suitable compilers.\n");
    exit(EXIT_FAILURE);
#endif
    
    ///////////////////////////
    // Variable declarations
    ///////////////////////////
    
    // Input filenames
    UT_string *in_read1_fq_fn, *in_read2_fq_fn, *in_single1_fq_fn, *in_single2_fq_fn;
    utstring_new(in_read1_fq_fn);
    utstring_new(in_read2_fq_fn);
    utstring_new(in_single1_fq_fn);
    utstring_new(in_single2_fq_fn);
    
    // Output filenames
    UT_string *out_read1_fn, *out_read2_fn, *out_single1_fn, *out_single2_fn, *out_mates_fn, *out_filetype;
    utstring_new(out_filetype);
    utstring_new(out_read1_fn);
    utstring_new(out_read2_fn);
    utstring_new(out_single1_fn);
    utstring_new(out_single2_fn);
    utstring_new(out_mates_fn);
    
    // Read name prefix
    UT_string *out_read_prefix;
    utstring_new(out_read_prefix);
    
    // Flags
    int singles_flag = 0;   // 1 when two output singles files being written
    int num_input_singles_files = 0;
    
    // Read counters
    unsigned long int mp_org = 0, R1_org = 0, R2_org = 0, singlet1_org = 0, singlet2_org = 0;
    unsigned long int mp_cnt = 0, R1_cnt = 0, R2_cnt = 0, singlet1_cnt = 0, singlet2_cnt = 0, s1_cnt = 0, s2_cnt = 0;
    unsigned long int comp_r1 = 0, comp_r2 = 0, comp_s1 = 0, comp_s2 = 0;
    unsigned long int read1_singlet_cnt = 0, read2_singlet_cnt = 0;

    ////////////////////////////////////////////////////////////////////////
    // All done with variable declarations!!
    
    ///////////////////////////////////
    // Command line argtable settings
    ///////////////////////////////////
    
    struct arg_lit *gzip = arg_lit0("z", "gzip", "Output converted files in gzip compressed format. [NULL]");
    struct arg_lit *inv_singles = arg_lit0("v", "invert_singles", "Causes singles output to be the inverse of the input. 2->1 or 1->2 [NULL]");
    struct arg_lit *num_singles = arg_lit0("s", "singles", "Write two singlet files, one for each mate-paired input file. [NULL]");
    struct arg_rem *sing_rem = arg_rem(NULL, "Note! -v is only valid when there are input singlet reads. -s is only valid when there are NO input singlet reads.");    
    struct arg_str *pre_read_id = arg_str0(NULL, "prefix", "<string>", "Prefix to add to read identifiers. [out_prefix]");
    struct arg_lit *no_pre = arg_lit0(NULL, "no_prefix", "Do not change the read names in any way. [NULL]");
    struct arg_lit *pre_read_len = arg_lit0(NULL, "add_len", "Add the final trimmed length value to the read id prefix. [length not added]");
    struct arg_dbl *prob = arg_dbl0("p","correct_prob","<d>","Probability that output reads are correct. 0.0 disables quality trimming. [0.5]");
    struct arg_int *fixed_len = arg_int0("f","fixed_len","<u>","Trim all reads to a fixed length, still filtering on quality [no fixed length]");
    struct arg_int *len = arg_int0("l","min_read_len","<u>","Minimum length of a singlet or longest-mate in nucleotides [24]");
    struct arg_int *mate_len = arg_int0("m","min_mate_len","<u>","Minimum length of the shortest mate in nucleotides [min_read_len]");
    struct arg_dbl *entropy = arg_dbl0("e","entropy_filter","<d>","Remove reads with per position information below given value (in bits per dinucleotide) [No filter]");
    struct arg_lit *entropy_strict = arg_lit0(NULL, "entropy_strict", "Reject reads for low entropy overall, not just the retained part after trimming [NULL]");
    struct arg_lit *mates = arg_lit0(NULL, "mates_file", "Produce a Velvet compatible interleaved paired read output file (e.g. <out_prefix>_mates.fastq). [NULL]");
    struct arg_lit *no_rev = arg_lit0(NULL, "no_rev", "By default, the second read in each pair is reversed for colorspace --mate-file output. --no_rev disables reversing. [rev]");
    struct arg_lit *only_mates = arg_lit0(NULL, "only_mates", "Supress writing .read1 and .read2 outputs. Requires --mates_file. [NULL]");
    struct arg_lit *fasta = arg_lit0(NULL, "fasta", "Write FASTA format files instead of FASTQ for all outputs (e.g. <out_prefix>.<read_type>.fasta). [FASTQ]");
    struct arg_file *input = arg_file1(NULL, NULL, "<in_prefix>", "Input file prefix: (e.g. <in_prefix>_single.fastq [<in_prefix>_read1.fastq <in_prefix>_read2.fastq]) ");
    struct arg_file *output = arg_file1(NULL, NULL, "<out_prefix>", "Output file prefix: (e.g. <out_prefix>_single.fastq [<out_prefix>_read1.fastq <out_prefix>_read2.fastq]) ");
    struct arg_lit *version = arg_lit0(NULL,"version","Print the build version and exit."); 
    struct arg_lit *h = arg_lit0("h", "help", "Request help.");
    struct arg_end *end = arg_end(20);
    
    void *argtable[] = {h,version,gzip,inv_singles,num_singles,sing_rem,prob,len,mate_len,fixed_len,pre_read_id,pre_read_len,no_pre,entropy,entropy_strict,mates,no_rev,only_mates,fasta,input,output,end};
    int arg_errors = 0;
        
    ////////////////////////////////////////////////////////////////////////
    // Handle command line processing (via argtable2 library) 
    ////////////////////////////////////////////////////////////////////////
    
    arg_errors = arg_parse(argc, argv, argtable);

	if (version->count) {
		fprintf(stderr, "%s version: %s\n", argv[0], SS_BUILD_VERSION);
		exit(EXIT_SUCCESS);
    }    
	
    if (h->count) {
        fprintf(stderr,"\ntrim_fastq is a utility for performing quality and information-based\n");
        fprintf(stderr,"trimming on paired or unpaired, nucleotide or SOLiD colorspace reads. \n\n");
        arg_print_syntaxv(stderr, argtable, "\n\n");
        arg_print_glossary(stderr, argtable, "%-25s %s\n");
        fprintf(stderr, "\nInput and output \"prefixes\" are the part of the filename before:\n");
        fprintf(stderr, "_single.fastq [_read1.fastq _read2.fastq]  A singlets (single) file\n");
        fprintf(stderr, "is required.  Mate-paired read files are automatically used if present.\n");
        fprintf(stderr, "Multiple output files only produced for mate-paired inputs.\n");
        fprintf(stderr, "\nNote! Input and output files may be gzipped, and outputs can be written\n");
        fprintf(stderr, "as either FASTQ or FASTA format files.\n");
        
        exit(EXIT_FAILURE);
    }    
    
    if (arg_errors) { 
        arg_print_errors(stderr, end, "trimfastq");
        arg_print_syntaxv(stderr, argtable, "\n");
        exit(EXIT_FAILURE);
    }
    
    // Validate entropy
    if (entropy->count) {
        entropy_cutoff = entropy->dval[0];
        if ((entropy_cutoff < 0.0) || (entropy_cutoff > 4.0)) {
            fprintf(stderr, "entropy_filter must be [0.0 - 4.0] \n");
            exit(EXIT_FAILURE);
        }
        strict_ent = entropy_strict->count;
    } else {
        if (entropy_strict->count) {
            fprintf(stderr, "Error: --entropy_strict requires --entropy_filter.\n");
            exit(EXIT_FAILURE);
        } 
        entropy_cutoff = -1.0;
    }    
    
    // Validate error_prob
    if (prob->count) {
        err_prob = prob->dval[0];
        if ((err_prob < 0.0) || (err_prob > 1.0)) {
            fprintf(stderr, "--correct_prob (-p) must be 0.0 - 1.0 inclusive\n");
            exit(EXIT_FAILURE);
        }
    } else {
        err_prob = 0.5;
    }    

    // Validate min read len
    if (len->count) {
        min_len = len->ival[0];
        if (min_len <= 0) {
            fprintf(stderr, "min_read_len must be > 0\n");
            exit(EXIT_FAILURE);
        }        
    } else {
        min_len = 24;
    }

    // Validate min mate len
    if (mate_len->count) {
        min_mate_len = mate_len->ival[0];
        if (min_mate_len <= 0) {
            fprintf(stderr, "min_mate_len must be > 0\n");
            exit(EXIT_FAILURE);
        }        
        if (min_mate_len > min_len) {
            fprintf(stderr, "min_mate_len must be <= min_len\n");
            exit(EXIT_FAILURE);
        }        
    } else {
        min_mate_len = min_len;
    }
    
    if (fixed_len->count) {
        fix_len = min_mate_len = min_len = fixed_len->ival[0];
        if ((mate_len->count) || (len->count)) {
            fprintf(stderr, "fixed_len cannot be used with min_read_len or min_mate_len\n");
            exit(EXIT_FAILURE);
        }
        if (fix_len <= 0) {
            fprintf(stderr, "fixed_len must be > 0\n");
            exit(EXIT_FAILURE);
        }
    } else {
        fix_len = 0;
    }
    
    if (pre_read_id->count) {
        
        if (no_pre->count) {
            fprintf(stderr, "Error: Both --prefix and --no_prefix were specified.\n");
            exit(EXIT_FAILURE);
        }
        
        if (! strlen(pre_read_id->sval[0])) {
            fprintf(stderr, "Read ID prefix may not be zero length.\n");
            exit(EXIT_FAILURE);
        } 
        
        if (strchr(pre_read_id->sval[0], ':') || strchr(pre_read_id->sval[0], '|') || strchr(pre_read_id->sval[0], '+') || strchr(pre_read_id->sval[0], '/')) {
            fprintf(stderr, "Read ID prefix '%s' may not contain the characters ':', '|', '+' or '/'.\n", pre_read_id->sval[0]);
            exit(EXIT_FAILURE);
        }
        
        // Build default read ID prefix
        ss_strcat_utstring(out_read_prefix, pre_read_id->sval[0]);
        
    } else {

        if (!no_pre->count) {
            
            if (strchr(output->filename[0], ':') || strchr(output->filename[0], '|') || strchr(output->filename[0], '+') || strchr(output->filename[0], '/')) {
                fprintf(stderr, "Read ID prefix '%s' (from output prefix) may not contain the characters ':', '|', '+' or '/'.\n", output->filename[0]);
                fprintf(stderr, "Hint: Use the --prefix parameter if the output file prefix contains path information.\n");
                exit(EXIT_FAILURE);
            }  
            
            // Build default read ID prefix
            ss_strcat_utstring(out_read_prefix, output->filename[0]);
        }
    }
    
    if ((only_mates->count) && (!mates->count)) {
        fprintf(stderr, "--only_mates requires --mates.\n");
        exit(EXIT_FAILURE);
    }

    if ((no_rev->count) && (!mates->count)) {
        fprintf(stderr, "--no_rev requires --mates.\n");
        exit(EXIT_FAILURE);
    }
    
    // Check for null string prefixes
    if (!(strlen(input->filename[0]) && strlen(output->filename[0]))) {
        fprintf(stderr, "Error: NULL prefix strings are not permitted.\n");
        exit(EXIT_FAILURE);
    }
    
    // Construct input filenames
    utstring_printf(in_read1_fq_fn, "%s.read1.fastq", input->filename[0]);
    utstring_printf(in_read2_fq_fn, "%s.read2.fastq", input->filename[0]);
    
    utstring_printf(in_single1_fq_fn, "%s.single.fastq", input->filename[0]);
    
    FILE *in_read_file = NULL;
    
    num_input_singles_files = 1;
    
    // Try to open a singlet fastq file
    // Check singlet output options -s and -v
    // Set input singlet names to
    //   - *.single.fastq or
    //   - *.single1.fastq and *.single2.fastq
    if (!(in_read_file = ss_get_gzFile(utstring_body(in_single1_fq_fn), "r"))) {
        utstring_clear(in_single1_fq_fn);
        utstring_printf(in_single1_fq_fn, "%s.single1.fastq", input->filename[0]);
        utstring_printf(in_single2_fq_fn, "%s.single2.fastq", input->filename[0]);
        num_input_singles_files = 2;
        
        if ((in_read_file = ss_get_gzFile(utstring_body(in_single1_fq_fn), "r")) || (in_read_file = ss_get_gzFile(utstring_body(in_single2_fq_fn), "r"))) {
            singles_flag = 1;   // Two singlet outputs
        } else {
            singles_flag = num_singles->count;  // Number of singlet outputs set by -s parm
            if (inv_singles->count) {
                fprintf(stderr, "Error: Invalid option -v, No input singlet file(s) found. Use -s to select multiple output singlet files.\n");
                exit(EXIT_FAILURE);
            }
        }
    }
    
    if (in_read_file) {
        gzclose(in_read_file);
        if (num_singles->count) {
            fprintf(stderr, "Error: Invalid option -s, Input singlet file(s) found, use -v to change the number of output singlet files.\n");
            exit(EXIT_FAILURE);
        }
    }

    // singles->count inverts the current singles file input scheme
    singles_flag = (singles_flag ^ inv_singles->count);
    
    // Check if input fastq is colorspace
    // If some files are colorspace and some are basespace, throw an error
    int fcount = 0;
    int cscount = 0;
    fcount += ss_is_fastq(utstring_body(in_read1_fq_fn));
    fcount += ss_is_fastq(utstring_body(in_read2_fq_fn));
    fcount += ss_is_fastq(utstring_body(in_single1_fq_fn));
    fcount += ss_is_fastq(utstring_body(in_single2_fq_fn));
    cscount += (ss_is_fastq(utstring_body(in_read1_fq_fn)) && ss_is_colorspace_fastq(utstring_body(in_read1_fq_fn)));
    cscount += (ss_is_fastq(utstring_body(in_read2_fq_fn)) && ss_is_colorspace_fastq(utstring_body(in_read2_fq_fn)));
    cscount += (ss_is_fastq(utstring_body(in_single1_fq_fn)) && ss_is_colorspace_fastq(utstring_body(in_single1_fq_fn)));
    cscount += (ss_is_fastq(utstring_body(in_single2_fq_fn)) && ss_is_colorspace_fastq(utstring_body(in_single2_fq_fn)));
    
    if (cscount && (cscount != fcount)) {        
        printf("Error: Mixed colorspace and basespace FASTQ files detected\n");
        exit(EXIT_FAILURE);
    }
    colorspace_flag = cscount ? 1 : 0;
    
    // Output filenames
    
    if (fasta->count) {
        ss_strcat_utstring(out_filetype, "fasta");
        read_count_divisor = 2;
    } else {
        ss_strcat_utstring(out_filetype, "fastq");
        read_count_divisor = 4;
    }
    
    if (!only_mates->count) {
        utstring_printf(out_read1_fn, "%s.read1.%s", output->filename[0], utstring_body(out_filetype));
        utstring_printf(out_read2_fn, "%s.read2.%s", output->filename[0], utstring_body(out_filetype));
    }
    
    if (singles_flag == 1) {
        utstring_printf(out_single1_fn, "%s.single1.%s", output->filename[0], utstring_body(out_filetype));
        utstring_printf(out_single2_fn, "%s.single2.%s", output->filename[0], utstring_body(out_filetype));
    } else {
        utstring_printf(out_single1_fn, "%s.single.%s", output->filename[0], utstring_body(out_filetype));
    }

    if (mates->count) {
        utstring_printf(out_mates_fn, "%s.mates.%s", output->filename[0], utstring_body(out_filetype));
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////
    // Begin processing!
    
#ifdef _OPENMP    
    omp_set_num_threads(10);
#endif    
    
    // This is the value of a non-valid pipe descriptor    
#define NO_PIPE 0
    
    int r1_pipe[2];
    int r2_pipe[2];
    int s1_pipe[2];
    int s2_pipe[2];
    pipe(r1_pipe);
    pipe(r2_pipe);
    pipe(s1_pipe);
    pipe(s2_pipe);
    
    int r1_out_pipe[2];
    int r2_out_pipe[2];
    int mates_out_pipe[2];
    int s1_out_pipe[2];
    int s2_out_pipe[2];
    pipe(r1_out_pipe);
    pipe(r2_out_pipe);
    pipe(mates_out_pipe);
    pipe(s1_out_pipe);
    pipe(s2_out_pipe);
    
    
#pragma omp parallel sections default(shared)       
    {
        
#pragma omp section 
        {   // Read1 reader
            fq_stream_trimmer(in_read1_fq_fn, r1_pipe[1], out_read_prefix, no_pre->count, pre_read_len->count, &comp_r1, &R1_org, '\0', fasta->count);
        }
        
#pragma omp section 
        {   // Read1 writer
            R1_cnt = ss_stream_writer(out_read1_fn, r1_out_pipe[0], gzip->count) / read_count_divisor;
        }
        
#pragma omp section 
        {   // Read2 reader
            fq_stream_trimmer(in_read2_fq_fn, r2_pipe[1], out_read_prefix, no_pre->count, pre_read_len->count, &comp_r2, &R2_org, '\0', fasta->count);
        }
        
#pragma omp section 
        {   // Read2 writer
            R2_cnt = ss_stream_writer(out_read2_fn, r2_out_pipe[0], gzip->count) / read_count_divisor;
        }
        
#pragma omp section 
        {   // Single1 reader
            
            // When there is only one input singles file, but two output singles files, then supply which mate to use for this stream in the split parameter
            if ((singles_flag) && (num_input_singles_files == 1)) {
                singlet1_cnt = fq_stream_trimmer(in_single1_fq_fn, s1_pipe[1], out_read_prefix, no_pre->count, pre_read_len->count, &comp_s1, &singlet1_org, '1', fasta->count);
            } else {
                singlet1_cnt = fq_stream_trimmer(in_single1_fq_fn, s1_pipe[1], out_read_prefix, no_pre->count, pre_read_len->count, &comp_s1, &singlet1_org, '\0', fasta->count);
            }
        }
        
#pragma omp section 
        {   // Single1 writer
            s1_cnt = ss_stream_writer(out_single1_fn, s1_out_pipe[0], gzip->count) / read_count_divisor;
        }
        
#pragma omp section 
        {   // Single2 reader
            
            // When there is only one input singles file, but two output singles files, then supply which mate to use for this stream in the split parameter
            if ((singles_flag) && (num_input_singles_files == 1)) {
                singlet2_cnt = fq_stream_trimmer(in_single1_fq_fn, s2_pipe[1], out_read_prefix, no_pre->count, pre_read_len->count, &comp_s2, &singlet2_org, '2', fasta->count);
            } else {
                singlet2_cnt = fq_stream_trimmer(in_single2_fq_fn, s2_pipe[1], out_read_prefix, no_pre->count, pre_read_len->count, &comp_s2, &singlet2_org, '\0', fasta->count);
            }
        }
        
#pragma omp section 
        {   // Single2 writer
            s2_cnt = ss_stream_writer(out_single2_fn, s2_out_pipe[0], gzip->count) / read_count_divisor;
        }

#pragma omp section 
        {   // Velvet mates writer
            // Divide count by 2 because both R1 and R2 reads go through this writer
            mp_cnt = ss_stream_writer(out_mates_fn, mates_out_pipe[0], gzip->count)  / 2 / read_count_divisor;
        }
        
#pragma omp section 
        {   // Dispatcher

            
            // Allocate data buffer strings
            
            UT_string *r1_data;
            utstring_new(r1_data);
            UT_string *r2_data;
            utstring_new(r2_data);
            UT_string *s1_data;
            utstring_new(s1_data);
            UT_string *s2_data;
            utstring_new(s2_data);
            
            UT_string *rev_tmp;
            utstring_new(rev_tmp);
            
            UT_string *rev_data;
            utstring_new(rev_data);
            
            // Pipes
            FILE *r1_in = fdopen(r1_pipe[0],"r"); 
            FILE *r2_in = fdopen(r2_pipe[0],"r");                 
            
            FILE *s1_in = fdopen(s1_pipe[0],"r");
            FILE *s2_in = fdopen(s2_pipe[0],"r");             

            FILE *mates_out = fdopen(mates_out_pipe[1],"w"); 
            
            FILE *r1_out = fdopen(r1_out_pipe[1],"w"); 
            FILE *r2_out = fdopen(r2_out_pipe[1],"w");                 
            
            FILE *s1_out = fdopen(s1_out_pipe[1],"w");
            FILE *s2_out = fdopen(s2_out_pipe[1],"w");             
            
            if (!singles_flag) {
                fclose(s2_out);
                s2_out = s1_out;
            }
            
            // Flags for data left in single files
            int single1_hungry = 1;
            int single2_hungry = 1;
            
            // Handle read1 and read2 files
            while (ss_get_utstring(r1_in, r1_data)) {
                if (!ss_get_utstring(r2_in, r2_data)) {
                    fprintf(stderr, "Error: Input read1 and read2 files are not synced\n");
                    exit(EXIT_FAILURE);
                }
                if (keep_read(r1_data)) {
                    if (keep_read(r2_data)) {
                        // Output both read1 and read2
                        if (mates->count) {
                            if (only_mates->count) {
                                // Interleaved velvet output only
                                output_read(r1_data, NULL, NULL, r1_in, NULL, mates_out, fasta->count);
                                if (no_rev->count || !colorspace_flag) {
                                    output_read(r2_data, NULL, NULL, r2_in, NULL, mates_out, fasta->count);
                                } else {
                                    output_read(r2_data, rev_data, rev_tmp, r2_in, NULL, mates_out, fasta->count);
                                }
                            } else {
                                // Interleaved velvet output and normal read file output
                                output_read(r1_data, NULL, NULL, r1_in, r1_out, mates_out, fasta->count);
                                if (no_rev->count || !colorspace_flag) {
                                    output_read(r2_data, NULL, NULL, r2_in, r2_out, mates_out, fasta->count);
                                } else {
                                    output_read(r2_data, rev_data, rev_tmp, r2_in, r2_out, mates_out, fasta->count);
                                }
                            }
                        } else {
                            // No interleaved velvet output
                            output_read(r1_data, NULL, NULL, r1_in, r1_out, NULL, fasta->count);
                            output_read(r2_data, NULL, NULL, r2_in, r2_out, NULL, fasta->count);
                        }
                    } else {
                        // Discard read2, output read1 as singlet
                        output_read(r1_data, NULL, NULL, r1_in, s1_out, NULL, fasta->count);
                        read1_singlet_cnt++;
                    }
                } else {
                    if (keep_read(r2_data)) {
                        // Discard read1, output read2 as singlet
                        output_read(r2_data, NULL, NULL, r2_in, s2_out, NULL, fasta->count);
                        read2_singlet_cnt++;
                    }
                }
                
                // Process reads from singles here to take advantage of
                // parallelism
                if (single1_hungry || single2_hungry) {
                    if (single1_hungry) {
                        if (ss_get_utstring(s1_in, s1_data)) {
                            if (keep_read(s1_data)) {
                                output_read(s1_data, NULL, NULL, s1_in, s1_out, NULL, fasta->count);
                            }
                        } else {
                            single1_hungry = 0;
                        }
                    }
                    if (single2_hungry) {
                        if (ss_get_utstring(s2_in, s2_data)) {
                            if (keep_read(s2_data)) {
                                output_read(s2_data, NULL, NULL, s2_in, s2_out, NULL, fasta->count);
                            }
                        } else {
                            single2_hungry = 0;
                        }
                    }
                }
            }
            
            while (single1_hungry || single2_hungry) {
                if (single1_hungry) {
                    if (ss_get_utstring(s1_in, s1_data)) {
                        if (keep_read(s1_data)) {
                            output_read(s1_data, NULL, NULL, s1_in, s1_out, NULL, fasta->count);
                        }
                    } else {
                        single1_hungry = 0;
                    }
                }
                if (single2_hungry) {
                    if (ss_get_utstring(s2_in, s2_data)) {
                        if (keep_read(s2_data)) {
                            output_read(s2_data, NULL, NULL, s2_in, s2_out, NULL, fasta->count);
                        }
                    } else {
                        single2_hungry = 0;
                    }
                }
            }
            
            fclose(r1_in);
            fclose(r2_in);
            
            fclose(s1_in);
            fclose(s2_in);
            
            fclose(mates_out);
            
            fclose(r1_out);
            fclose(r2_out);
            
            fclose(s1_out);
            
            if (singles_flag) {
                fclose(s2_out);
            }
            
            // Free buffers
            utstring_free(r1_data);
            utstring_free(r2_data);
            utstring_free(s1_data);
            utstring_free(s2_data);
            utstring_free(rev_tmp);
            utstring_free(rev_data);
        }
    }

    if (!(R1_org+singlet1_org+singlet2_org)) {
    
        fprintf(stderr, "ERROR! No reads found in input files, or input(s) not found.\n");
        exit(EXIT_FAILURE);
    
    }
    
    if (R1_org != R2_org) {
        fprintf(stderr, "\nWarning! read1 and read2 fastq files did not contain an equal number of reads. %lu %lu\n", R1_org, R2_org);
    }
    
    if ((R1_org + R2_org) && !(singlet1_cnt + singlet2_cnt)) {
        fprintf(stderr, "\nWarning! read1/read2 files were processed, but no corresponding input singlets were found.\n");
    } 
    
    if (entropy->count) {
        printf("\nLow complexity reads discarded: Read1: %lu, Read2: %lu, Singlets: %lu %lu\n", comp_r1, comp_r2, comp_s1, comp_s2);
    }

    mp_org = R1_org;
    if (!only_mates->count) {
        mp_cnt = R1_cnt;
    }
    
    printf("\nMatepairs: Before: %lu, After: %lu\n", mp_org, mp_cnt);
    printf("Singlets: Before: %lu %lu After: %lu %lu\n", singlet1_org, singlet2_org, s1_cnt, s2_cnt);
    printf("Read1 singlets: %lu, Read2 singlets: %lu, Original singlets: %lu %lu\n", read1_singlet_cnt, read2_singlet_cnt, singlet1_cnt, singlet2_cnt);
    printf("Total Reads Processed: %lu, Reads retained: %lu\n", 2*mp_org+singlet1_org+singlet2_org, 2*mp_cnt+s1_cnt+s2_cnt);
    
    utstring_free(in_read1_fq_fn);
    utstring_free(in_read2_fq_fn);
    utstring_free(in_single1_fq_fn);
    utstring_free(in_single2_fq_fn);
    utstring_free(out_read1_fn);
    utstring_free(out_read2_fn);
    utstring_free(out_single1_fn);
    utstring_free(out_single2_fn);
    utstring_free(out_mates_fn);
    utstring_free(out_filetype);
    
    utstring_free(out_read_prefix);
    
    exit(EXIT_SUCCESS);
}
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.99;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef CART_POLE_BINARY
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int h = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    unsigned int n = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    optimistic_instance* optimistic = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of maximum numbers of evaluations");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(6);

    int nerrors = 0;
    void* argtable[6];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = s;
    argtable[3] = k;
    argtable[4] = where;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    K = k->ival[0];
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &n);
    initialStates = (state**)malloc(sizeof(state*) * n);
    
    for(; i < n; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);

    optimistic = optimistic_initInstance(NULL, discountFactor);

    sprintf(str, "%s/%u_results_%u_%u.csv", where->filename[0], timestamp, K, nbSteps);
    results = fopen(str, "w");

    for(h = 0; h < nbN; h++) {
        double sumRewards = 0.0;

        for(i = 0; i < n; i++) {
            unsigned int j = 0;
            state* crt = copyState(initialStates[i]);

            optimistic_resetInstance(optimistic, crt);
            for(; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                optimistic_keepSubtree(optimistic);
                action* optimalAction = optimistic_planning(optimistic, ns[h]);
                isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                freeState(crt);
                crt = nextState;
                sumRewards += reward;
                if(isTerminal)
                    break;
            }
            optimistic_resetInstance(optimistic, crt);
            freeState(crt);

            printf(">>>>>>>>>>>>>> %uth initial state processed\n", i + 1);
            fflush(NULL);
        }

        fprintf(results, "%u,%.15f\n", ns[h], sumRewards / (double)n);
        printf(">>>>>>>>>>>>>> n = %u  done\n\n", ns[h]);
        fflush(NULL);
    }

    fclose(results);

    arg_freetable(argtable, 6);

    for(i = 0; i < n; i++)
        freeState(initialStates[i]);

    free(initialStates);

    optimistic_uninitInstance(&optimistic);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.95;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef CART_POLE_BINARY
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    unsigned int maxDepth = 0;
    FILE* combinedFd = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int minDepth = 1;
    unsigned int crtDepth = 0;
    unsigned int n = 0;
    unsigned int maxNbIterations = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    optimistic_instance* optimistic = NULL;
    random_search_instance* random_search = NULL;
    uct_instance* uct = NULL;
    uniform_instance* uniform = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_int* d = arg_int1("d", NULL, "<n>", "Maximum depth of an uniform tree which the number of call per step");
    struct arg_int* d2 = arg_int0(NULL, "min", "<n>", "Minimun depth to start from (min > 0)");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(7);

    int nerrors = 0;
    void* argtable[7];

    argtable[0] = initFile;
    argtable[1] = d2;
    argtable[2] = d;
    argtable[3] = s;
    argtable[4] = k;
    argtable[5] = where;
    argtable[6] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    K = k->ival[0];
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &n);
    initialStates = (state**)malloc(sizeof(state*) * n);
    
    for(; i < n; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    if(d2->count)
        minDepth = d2->ival[0];
    maxDepth = d->ival[0];
    maxNbIterations = K;
    nbSteps = s->ival[0];

    optimistic = optimistic_initInstance(NULL, discountFactor);
    random_search = random_search_initInstance(NULL, discountFactor);
    uct = uct_initInstance(NULL, discountFactor);
    uniform = uniform_initInstance(NULL, discountFactor);

    sprintf(str, "%s/%u_results_%u_%u.csv", where->filename[0], timestamp, K, nbSteps);
    results = fopen(str, "w");

    for(crtDepth = 1; crtDepth < minDepth; crtDepth++)
        maxNbIterations += pow(K, crtDepth+1);

    for(crtDepth = minDepth; crtDepth <= maxDepth; crtDepth++) {
        double averages[4] = {0.0, 0.0, 0.0, 0.0};
        sprintf(str, "%s/%u_combined_%u_%u(%u)_%u.csv", where->filename[0], timestamp, K, crtDepth, maxNbIterations, nbSteps);
        combinedFd = fopen(str, "w");
        fprintf(combinedFd, "nbIterations,optimistic,optimistic(discounted),optimistic depth,random search,random search(discounted),random search depth,uct,uct(discounted),uct depth,uniform,uniform(discounted),uniform depth\n");

        for(i = 0; i < n; i++) {
            unsigned int j = 0;
            double sumRewards = 0.0;
            double discountedSumRewards = 0.0;
            unsigned int sumDepths = 0;
            state* crt = copyState(initialStates[i]);

            optimistic_resetInstance(optimistic, crt);
            for(; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                optimistic_keepSubtree(optimistic);
                action* optimalAction = optimistic_planning(optimistic, maxNbIterations);
                isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward);
                freeState(crt);
                crt = nextState;
                sumRewards += reward;
                sumDepths += optimistic_getMaxDepth(optimistic);
                discountedSumRewards += optimistic->gammaPowers[j] * reward;
                if(isTerminal < 0)
                    break;
            }
            optimistic_resetInstance(optimistic, crt);
            freeState(crt);
            fprintf(combinedFd, "%u,%.15f,%.15f,%.15f,",maxNbIterations, sumRewards, discountedSumRewards, sumDepths / (double)((j == nbSteps) ? nbSteps : (j + 1)));

            averages[0] += sumRewards;

            printf("Optimistic   : %uth initial state processed\n", i + 1);

            sumRewards = 0.0;
            discountedSumRewards = 0.0;
            sumDepths = 0;
            crt = copyState(initialStates[i]);
            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                random_search_resetInstance(random_search, crt);
                action* optimalAction = random_search_planning(random_search, maxNbIterations);
                isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward);
                freeState(crt);
                crt = nextState;
                sumRewards += reward;
                sumDepths += random_search_getMaxDepth(random_search);
                discountedSumRewards += random_search->gammaPowers[j] * reward;
                if(isTerminal < 0)
                    break;
            }
            random_search_resetInstance(random_search, crt);
            freeState(crt);
            fprintf(combinedFd, "%.15f,%.15f,%.15f,", sumRewards, discountedSumRewards, sumDepths / (double)((j == nbSteps) ? nbSteps : (j + 1)));

            averages[1] += sumRewards;

            printf("Random search: %uth initial state processed\n", i + 1);

            sumRewards = 0.0;
            discountedSumRewards = 0.0;
            sumDepths = 0;
            crt = copyState(initialStates[i]);
            uct_resetInstance(uct, crt);
            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                uct_keepSubtree(uct);
                action* optimalAction = uct_planning(uct, maxNbIterations);
                isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward);
                freeState(crt);
                crt = nextState;
                sumRewards += reward;
                sumDepths += uct_getMaxDepth(uct);
                discountedSumRewards += uct->gammaPowers[j] * reward;
                if(isTerminal < 0)
                    break;
            }
            uct_resetInstance(uct, crt);
            freeState(crt);
            fprintf(combinedFd, "%.15f,%.15f,%.15f,", sumRewards, discountedSumRewards, sumDepths / (double)((j == nbSteps) ? nbSteps : (j + 1)));

            averages[2] += sumRewards;

            printf("Uct          : %uth initial state processed\n", i + 1);

            sumRewards = 0.0;
            discountedSumRewards = 0.0;
            crt = copyState(initialStates[i]);
            uniform_resetInstance(uniform, crt);
            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                uniform_keepSubtree(uniform);
                action* optimalAction = uniform_planning(uniform, maxNbIterations);
                isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward);
                freeState(crt);
                crt = nextState;
                sumRewards += reward;
                discountedSumRewards += uniform->gammaPowers[j] * reward;
                if(isTerminal < 0)
                    break;
            }
            uniform_resetInstance(uniform, crt);
            freeState(crt);
            fprintf(combinedFd, "%.15f,%.15f,%u\n", sumRewards, discountedSumRewards, crtDepth -1);

            fflush(combinedFd);

            averages[3] += sumRewards;

            printf("Uniform      : %uth initial state processed\n", i + 1);
            printf(">>>>>>>>>>>>>> %uth initial state processed\n", i + 1);

        }

        fprintf(results, "%u,%.15f,%.15f,%.15f,%.15f\n", maxNbIterations, averages[0] / (double)n, averages[1] / (double)n, averages[2] / (double)n, averages[3] / (double)n);
        fflush(results);

        printf(">>>>>>>>>>>>>> %u depth done\n\n", crtDepth);

        fclose(combinedFd);
        maxNbIterations += pow(K, crtDepth+1);

    }

    fclose(results);

    arg_freetable(argtable, 7);

    for(i = 0; i < n; i++)
        freeState(initialStates[i]);

    free(initialStates);

    optimistic_uninitInstance(&optimistic);
    random_search_uninitInstance(&random_search);
    uct_uninitInstance(&uct);
    uniform_uninitInstance(&uniform);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
Example #27
0
int main(int argc, char* argv[])
{
    // Define our variables.
    int nerrors, i;
    int32_t saved = 0; // The number of words saved during compression and optimization.
    struct errinfo* errval;
    const char* prepend = "error: ";
    const char* warnprefix = "no-";
    int msglen;
    char* msg;
    int target;

    // Define arguments.
    struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
    struct arg_str* target_arg = arg_str0("l", "link-as", "target", "Link as the specified object, can be 'image', 'static' or 'kernel'.");
    struct arg_file* symbol_file = arg_file0("s", "symbols", "<file>", "Produce a combined symbol file (~triples memory usage!).");
    struct arg_str* symbol_ext = arg_str0(NULL, "symbol-extension", "ext", "When -s is used, specifies the extension for symbol files.  Defaults to \"dsym16\".");
    struct arg_file* input_files = arg_filen(NULL, NULL, "<file>", 1, 100, "The input object files.");
    struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
    struct arg_file* kernel_file = arg_file0("k", "kernel", "<file>", "Directly link in the specified kernel.");
    struct arg_file* jumplist_file = arg_file0("j", "jumplist", "<file>", "Link against the specified jumplist.");
    struct arg_str* warning_policies = arg_strn("W", NULL, "policy", 0, _WARN_COUNT * 2 + 10, "Modify warning policies.");
    struct arg_lit* keep_output_arg = arg_lit0(NULL, "keep-outputs", "Keep the .OUTPUT entries in the final static library (used for stdlib).");
    struct arg_lit* little_endian_mode = arg_lit0(NULL, "little-endian", "Use little endian serialization (for compatibility with older versions).");
    struct arg_lit* no_short_literals_arg = arg_lit0(NULL, "no-short-literals", "Do not compress literals to short literals.");
    struct arg_int* opt_level = arg_int0("O", NULL, "<level>", "The optimization level.");
    struct arg_lit* opt_mode = arg_lit0("S", NULL, "Favour runtime speed over size when optimizing.");
    struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
    struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
    struct arg_end* end = arg_end(20);
    void* argtable[] = { show_help, target_arg, keep_output_arg, little_endian_mode, opt_level, opt_mode, no_short_literals_arg,
                         symbol_ext, symbol_file, kernel_file, jumplist_file, warning_policies, output_file, input_files, verbose, quiet, end
                       };

    // Parse arguments.
    nerrors = arg_parse(argc, argv, argtable);

    version_print(bautofree(bfromcstr("Linker")));
    if (nerrors != 0 || show_help->count != 0)
    {
        if (show_help->count != 0)
            arg_print_errors(stdout, end, "linker");

        printd(LEVEL_DEFAULT, "syntax:\n    dtld");
        arg_print_syntax(stderr, argtable, "\n");
        printd(LEVEL_DEFAULT, "options:\n");
        arg_print_glossary(stderr, argtable, "    %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Set verbosity level.
    debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

    // Set global path variable.
    osutil_setarg0(bautofree(bfromcstr(argv[0])));

    // Set endianness.
    isetmode(little_endian_mode->count == 0 ? IMODE_BIG : IMODE_LITTLE);

    // Set up warning policies.
    dsetwarnpolicy(warning_policies);

    // Set up error handling.
    if (dsethalt())
    {
        errval = derrinfo();

        // FIXME: Use bstrings here.
        msglen = strlen(derrstr[errval->errid]) + strlen(prepend) + 1;
        msg = malloc(msglen);
        memset(msg, '\0', msglen);
        strcat(msg, prepend);
        strcat(msg, derrstr[errval->errid]);
        printd(LEVEL_ERROR, msg, errval->errdata);

        // Handle the error.
        printd(LEVEL_ERROR, "linker: error occurred.\n");

        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Check to make sure target is correct.
    if (target_arg->count == 0)
        target = IMAGE_APPLICATION;
    else
    {
        if (strcmp(target_arg->sval[0], "image") == 0)
            target = IMAGE_APPLICATION;
        else if (strcmp(target_arg->sval[0], "static") == 0)
            target = IMAGE_STATIC_LIBRARY;
        else if (strcmp(target_arg->sval[0], "kernel") == 0)
            target = IMAGE_KERNEL;
        else
        {
            // Invalid option.
            dhalt(ERR_INVALID_TARGET_NAME, NULL);
        }
    }

    // Load all passed objects and use linker bin system to
    // produce result.
    bins_init();
    for (i = 0; i < input_files->count; i++)
        if (!bins_load(bautofree(bfromcstr(input_files->filename[i])), symbol_file->count > 0, (symbol_file->count > 0 && symbol_ext->count > 0) ? symbol_ext->sval[0] : "dsym16"))
            // Failed to load one of the input files.
            dhalt(ERR_BIN_LOAD_FAILED, input_files->filename[i]);
    bins_associate();
    bins_sectionize();
    bins_flatten(bautofree(bfromcstr("output")));
    if (target == IMAGE_KERNEL)
        bins_write_jump();
    saved = bins_optimize(
                opt_mode->count == 0 ? OPTIMIZE_SIZE : OPTIMIZE_SPEED,
                opt_level->count == 0 ? OPTIMIZE_NONE : opt_level->ival[0]);
    if (no_short_literals_arg->count == 0 && target != IMAGE_STATIC_LIBRARY)
        saved += bins_compress();
    else if (no_short_literals_arg->count == 0)
        dwarn(WARN_SKIPPING_SHORT_LITERALS_TYPE, NULL);
    else
        dwarn(WARN_SKIPPING_SHORT_LITERALS_REQUEST, NULL);
    bins_resolve(
        target == IMAGE_STATIC_LIBRARY,
        target == IMAGE_STATIC_LIBRARY);
    bins_save(
        bautofree(bfromcstr("output")),
        bautofree(bfromcstr(output_file->filename[0])),
        target,
        keep_output_arg->count > 0,
        symbol_file->count > 0 ? symbol_file->filename[0] : NULL,
        jumplist_file->count > 0 ? jumplist_file->filename[0] : NULL);
    bins_free();
    if (saved > 0)
        printd(LEVEL_DEFAULT, "linker: saved %i words during optimization.\n", saved);
    else if (saved < 0)
        printd(LEVEL_DEFAULT, "linker: increased by %i words during optimization.\n", -saved);

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return 0;
}
Example #28
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int 
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

int Rslt;
etFMode FMode;				// format output mode

char szOutputFileSpec[_MAX_PATH];
char szInputFileSpec[_MAX_PATH];

// command line args
struct arg_lit  *help    = arg_lit0("h","help",                 "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to screen and logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_int *format = arg_int0("M","format","<int>",		    "output format: 0 - multifasta, 1 - CSV format only, 2 - BED format, 3 - XML entries only (default: 0)");

struct arg_file *InFile = arg_file1("i","input","<file>",		"input from bioseq files");
struct arg_file *OutFile = arg_file1("o","result","<file>",		"output entry dump file");
struct arg_end *end = arg_end(20);

void *argtable[] = {help,version,FileLogLevel,LogFile,LogFile,format,InFile,OutFile,end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s Dump biosequence (generated by genbioseq) file contents, Version %s\nOptions ---\n", gszProcName,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s @myparams.txt\n",gszProcName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		exit(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s Version %s\n",gszProcName,cpszProgVer);
		exit(1);
        }


if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}
	
	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}




	FMode = (etFMode)(format->count ? format->ival[0] : eFMdefault);
	if(FMode < eFMdefault || FMode >= eFMplaceholder)
		{
		printf("\nError: Requested output format '-M%d' not supported, must be in range %d..%d",FMode,eFMdefault,eFMplaceholder-1);
		exit(1);
		}

	strcpy(szInputFileSpec,InFile->filename[0]);
	strcpy(szOutputFileSpec,OutFile->filename[0]);

			// now that command parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem.");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile);
		exit(1);
		}

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s Processing parameters:",cpszProgVer);
	const char *pszDescr;
	switch(FMode) {
		case eFMdefault:			// default is for multifasta
			pszDescr = "Multifasta";
			break;
		case eFMcsv:				// CSV entries
			pszDescr = "CSV format";
			break;
		case eFMbed:				// BED entries
			pszDescr = "BED format";
			break;
		case eFMxml:				// XML entries
			pszDescr = "XML format";
			break;
		}
	
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"dump output format: %s",pszDescr);
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"input biosequence file: '%s'",szInputFileSpec);
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"output to file: '%s'",szOutputFileSpec);	
	
	gStopWatch.Start();
	Rslt = Process(szInputFileSpec,szOutputFileSpec,FMode);
	gStopWatch.Stop();
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	printf("\n%s Dump biosequence (generated by genbioseq) file contents, Version %s\n",gszProcName,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
}
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.99;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int nbInitialStates = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    double* Ls = NULL;
    unsigned int nbL = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    lipschitzian_instance* lipschitzian = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of ressources");
    struct arg_str* z = arg_str1("L", NULL, "<s>", "List of Lipschitz coefficients to try");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(6);

    int nerrors = 0;
    void* argtable[6];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = s;
    argtable[3] = z;
    argtable[4] = where;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &nbInitialStates);
    initialStates = (state**)malloc(sizeof(state*) * nbInitialStates);
    
    for(; i < nbInitialStates; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    Ls = parseDoubleList((char*)z->sval[0], &nbL);
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);

    sprintf(str, "%s/%u_results_%s_%s.csv", where->filename[0], timestamp, z->sval[0], r->sval[0]);
    results = fopen(str, "w");

    lipschitzian = lipschitzian_initInstance(NULL, discountFactor, 0.0);
    
    for(i = 0; i < nbN; i++) {                                               /* Loop on the computational ressources */
        fprintf(results, "%u", ns[i]);
        printf("Starting with %u computational ressources\n", ns[i]);
        fflush(NULL);
        unsigned int j = 0;
        for(; j < nbL; j++) {                                           /* Loop on the Lispchitz constant */
            unsigned int k = 0;
            double average = 0.0;
            lipschitzian->L = Ls[j];
            for(; k < nbInitialStates; k++) {                           /* Loop on the initial states */
                unsigned int l = 0;
                double sumRewards = 0.0;
                state* crt = copyState(initialStates[k]);

                lipschitzian_resetInstance(lipschitzian, crt);
                for(; l < nbSteps; l++) {                               /* Loop on the step */
                    char isTerminal = 0;
                    double reward = 0.0;
                    state* nextState = NULL;

                    double* optimalAction = lipschitzian_planning(lipschitzian, ns[i]);
                    isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                    free(optimalAction);
                    freeState(crt);
                    crt = nextState;
                    sumRewards += reward;
                    lipschitzian_resetInstance(lipschitzian,crt);
                    if(isTerminal)
                        break;
                }
                average += sumRewards;
                freeState(crt);
                printf("Computation of the %u initial state done with L=%f\n", k, Ls[j]);
                fflush(NULL);
            }
            average = average /(double)nbInitialStates;
            fprintf(results, ",%.15f", average);
            printf("Computation with L=%f and n=%u done\n", Ls[j], ns[i]);
            fflush(NULL);
        }
        fprintf(results,"\n");
        printf("Computation with %u computational ressources done\n\n", ns[i]);
        fflush(NULL);
    }

    fclose(results);

    arg_freetable(argtable, 6);

    for(i = 0; i < nbInitialStates; i++)
        freeState(initialStates[i]);

    free(initialStates);

    lipschitzian_uninitInstance(&lipschitzian);

    free(ns);
    free(Ls);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
int main(int argc, char* argv[]) {

    double discountFactor = 0.9;
    unsigned int i = 0;
    unsigned int n = 0;
    FILE* initFileFd = NULL;
    FILE* outputFileFd = NULL;
    unsigned int nbIterations = 0;
    int readFscanf = -1;

    optimistic_instance* optimistic = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_int* k = arg_int1("k", NULL, "<n>", "The branching factor of the problem");
    struct arg_int* it = arg_int1("n", NULL, "<n>", "The number of iterations");
    struct arg_file* outputFile = arg_file1("o", NULL, "<file>", "The output file");
    struct arg_end* end = arg_end(5);

    void* argtable[5];

    int nerrors = 0;

    argtable[0] = initFile;
    argtable[1] = it;
    argtable[2] = outputFile;
    argtable[3] = k;
    argtable[4] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 5);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 5);
        return EXIT_FAILURE;
    }

    nbIterations = it->ival[0];

    initGenerativeModelParameters();
    K = k->ival[0];
    initGenerativeModel();

    outputFileFd = fopen(outputFile->filename[0], "w");

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &n);

    arg_freetable(argtable, 5);

    optimistic = optimistic_initInstance(NULL, discountFactor);

    for(; i < n; i++) {
        char str[1024];
        unsigned int j = 0;

        readFscanf = fscanf(initFileFd, "%s\n", str);
        state* initial = makeState(str);
        double crtOptimalValue = 0.0;
        unsigned int crtOptimalAction = 0;

        for(; j < K; j++) {
            state* nextState = NULL;
            double reward = 0.0;
            char isTerminal = 0;

            isTerminal = nextStateReward(initial, actions[j], &nextState, &reward);
            optimistic_resetInstance(optimistic, nextState);
            freeState(nextState);
            optimistic_planning(optimistic, nbIterations);

            if(optimistic->crtOptimalValue > crtOptimalValue) {
                crtOptimalValue = optimistic->crtOptimalValue;
                crtOptimalAction = j;
            }

            fprintf(outputFileFd, "%.15f,", optimistic->crtOptimalValue);
            printf("%uth action done\n", j+1);
            fflush(outputFileFd);
        }
        fprintf(outputFileFd, "%u\n", crtOptimalAction);
        freeState(initial);
        printf("%uth initial state processed\n", i+1);
        fflush(outputFileFd);
    }

    fclose(outputFileFd);
    fclose(initFileFd);

    optimistic_uninitInstance(&optimistic);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}