int main(int argc, char * argv[]) { void* argtable[] = { input = arg_filen( "i", "input", "<string>", 0, 100, "input file") , o_validate = arg_strn( "v", "validate", "<string>", 0, 10, "validate operations") , o_h = arg_file0( NULL, "output-h", "<string>", "output h file dir") , o_lib_c = arg_file0( NULL, "output-lib-c", "<string>", "output c lib file") , o_lib_c_arg = arg_str0( NULL, "output-lib-c-arg", "<string>", "output c lib file") , o_lib_bin = arg_file0( NULL, "output-lib-bin", "<string>", "output c lib file") , help = arg_lit0( NULL, "help", "print this help and exit") , end = arg_end(20) }; struct error_monitor em_buf; error_monitor_t em; int rv; int nerrors; cpe_error_monitor_init(&em_buf, cpe_error_log_to_consol, 0); em = &em_buf; rv = -1; if (arg_nullcheck(argtable) != 0) { CPE_ERROR(em, "init arg table fail!"); goto exit; } nerrors = arg_parse(argc,argv,argtable); if (help->count > 0) { printf("Usage: %s", argv[0]); arg_print_syntax(stdout,argtable,"\n"); rv = 0; goto exit; } if (nerrors > 0) { arg_print_errors(stdout, end, argv[0]); printf("Try '%s --help' for more information.\n", argv[0]); goto exit; } rv = tools_main(em); exit: arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return rv; }
void parse_command_line(int argc, char* argv[]) { // if the parsing of the arguments was unsuccessful int nerrors; // Define argument table structs python_folder = arg_file0 ( NULL, "py-folder", "<path to file>", "Path to folder (relative or absolute) that contains python script (default: lpfw-pygui)" ); log_debug = arg_int0 ( NULL, "log-debug", "<1/0 for yes/no>", "Enable debug messages logging" ); struct arg_lit *help = arg_lit0 ( NULL, "help", "Display this help screen" ); struct arg_lit *version = arg_lit0 ( NULL, "version", "Display the current version" ); struct arg_end *end = arg_end ( 10 ); void *argtable[] = {python_folder, log_debug, help, version, end}; // Set default values char *python_folder_pointer = malloc(strlen("lpfw-pygui")+1); strcpy (python_folder_pointer, "lpfw-pygui"); python_folder->filename[0] = python_folder_pointer; * ( log_debug->ival ) = 0; if ( arg_nullcheck ( argtable ) != 0 ) { printf ( "Error: insufficient memory\n" ); exit(0); } nerrors = arg_parse ( argc, argv, argtable ); if ( nerrors == 0 ) { if ( help->count == 1 ) { printf ( "Leopard Flower frontend :\n Syntax and help:\n" ); arg_print_glossary ( stdout, argtable, "%-43s %s\n" ); exit (0); } else if ( version->count == 1 ) { printf ( "%s\n", VERSION ); exit (0); } } else if ( nerrors > 0 ) { arg_print_errors ( stdout, end, "Leopard Flower frontend" ); printf ( "Leopard Flower frontend:\n Syntax and help:\n" ); arg_print_glossary ( stdout, argtable, "%-43s %s\n" ); exit (1); } // Free memory - don't do this cause args needed later on // arg_freetable(argtable, sizeof (argtable) / sizeof (argtable[0])); }
int main(int argc, char *argv[]) { /* the global arg_xxx structs are initialised within the argtable */ void *argtable[] = { help = arg_lit0(NULL, "help", "display this help and exit"), version = arg_lit0(NULL, "version", "display version info and exit"), a = arg_lit0("a", NULL,"the -a option"), b = arg_lit0("b", NULL, "the -b option"), c = arg_lit0("c", NULL, "the -c option"), scal = arg_int0(NULL, "scalar", "<n>", "foo value"), verb = arg_lit0("v", "verbose", "verbose output"), o = arg_file0("o", NULL, "myfile", "output file"), file = arg_filen(NULL, NULL, "<file>", 0, 100, "input files"), end = arg_end(20), }; int exitcode = 0; char progname[] = "testargtable3.exe"; int nerrors; nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout, argtable, "\n"); printf("List information about the FILE(s) " "(the current directory by default).\n\n"); arg_print_glossary(stdout, argtable, " %-25s %s\n"); exitcode = 0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout, end, progname); printf("Try '%s --help' for more information.\n", progname); exitcode = 1; goto exit; } exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; }
/* * 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; }
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 }
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; }
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; etPMode PMode; // processing mode int Idx; int NumInputFiles; // number of input sequence files char *pszInFastaFile[cMaxInFileSpecs]; // names of input sequence files (wildcards allowed) char szRsltsFile[_MAX_PATH]; // output stats to this file // 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 - BED output, single exon"); struct arg_file *pinputfiles = arg_filen("i","infasta","<file>",1,cMaxInFileSpecs,"input fasta file(s)"); struct arg_file *RsltsFile = arg_file0("o","output","<file>", "output BED file"); struct arg_end *end = arg_end(20); void *argtable[] = {help,version,FileLogLevel,LogFile, pmode,pinputfiles,RsltsFile, 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 Generate BED file from multifasta file, 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); PMode = (etPMode)(pmode->count ? pmode->ival[0] : ePMdefault); if(PMode < ePMdefault || PMode >= ePMplaceholder) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Processing mode '-m%d' specified outside of range %d..%d\n",PMode,ePMdefault,(int)ePMplaceholder-1); exit(1); } NumInputFiles = 0; for(NumInputFiles=Idx=0;NumInputFiles < cMaxInFileSpecs && Idx < pinputfiles->count; Idx++) { pszInFastaFile[Idx] = NULL; if(pszInFastaFile[NumInputFiles] == NULL) pszInFastaFile[NumInputFiles] = new char [_MAX_PATH]; strncpy(pszInFastaFile[NumInputFiles],pinputfiles->filename[Idx],_MAX_PATH); pszInFastaFile[NumInputFiles][_MAX_PATH-1] = '\0'; CUtility::TrimQuotedWhitespcExtd(pszInFastaFile[NumInputFiles]); if(pszInFastaFile[NumInputFiles][0] != '\0') NumInputFiles++; } if(!NumInputFiles) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no input file(s) specified with '-i<filespec>' option)\n"); exit(1); } if(!RsltsFile->count) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: No output BED file specified"); exit(1); } strncpy(szRsltsFile,RsltsFile->filename[0],_MAX_PATH); szRsltsFile[_MAX_PATH-1] = '\0'; gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing parameters:"); for(Idx=0; Idx < NumInputFiles; Idx++) gDiagnostics.DiagOutMsgOnly(eDLInfo,"input fasta sequence files (%d): '%s'",Idx+1,pszInFastaFile[Idx]); if(szRsltsFile[0] != '\0') gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output to BED file: '%s'",szRsltsFile); #ifdef _WIN32 SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); #endif // processing here... gStopWatch.Start(); Rslt = Process(PMode,NumInputFiles,pszInFastaFile,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 Generate BED file from multifasta file, 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; }
int main(int argc, char **argv) { struct arg_lit *list = arg_lit0("lL",NULL, "list files"); struct arg_lit *recurse = arg_lit0("R",NULL, "recurse through subdirectories"); struct arg_int *repeat = arg_int0("k","scalar",NULL, "define scalar value k (default is 3)"); struct arg_str *defines = arg_strn("D","define","MACRO",0,argc+2, "macro definitions"); struct arg_file *outfile = arg_file0("o",NULL,"<output>", "output file (default is \"-\")"); struct arg_lit *verbose = arg_lit0("v","verbose,debug", "verbose messages"); struct arg_lit *help = arg_lit0(NULL,"help", "print this help and exit"); struct arg_lit *version = arg_lit0(NULL,"version", "print version information and exit"); struct arg_file *infiles = arg_filen(NULL,NULL,NULL,1,argc+2, "input file(s)"); struct arg_end *end = arg_end(20); void* argtable[] = {list,recurse,repeat,defines,outfile,verbose,help,version,infiles,end}; const char* progname = "myprog"; int nerrors; int exitcode=0; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 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 */ repeat->ival[0]=3; outfile->filename[0]="-"; /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout,argtable,"\n"); printf("This program demonstrates the use of the argtable2 library\n"); printf("for parsing command line arguments.\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); exitcode=0; goto exit; } /* special case: '--version' takes precedence error reporting */ if (version->count > 0) { printf("'%s' example program for the \"argtable\" command line argument parser.\n",progname); printf("September 2003, Stewart Heitmann\n"); exitcode=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,progname); printf("Try '%s --help' for more information.\n",progname); exitcode=1; goto exit; } /* special case: uname with no command line options induces brief help */ if (argc==1) { printf("Try '%s --help' for more information.\n",progname); exitcode=0; goto exit; } /* normal case: take the command line options at face value */ exitcode = mymain(list->count, recurse->count, repeat->ival[0], defines->sval, defines->count, outfile->filename[0], verbose->count, infiles->filename, infiles->count); exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return exitcode; }
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 {
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); } }
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; }
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 iProcMode; char Strand; // process features on this strand int MinLen; int JoinLen; int LenFileList; int NumIncludeChroms; char *pszIncludeChroms[cMaxIncludeChroms]; int NumExcludeChroms; char *pszExcludeChroms[cMaxExcludeChroms]; etBEDRegion Region; // process for this functional region only int NumInFiles; // number of control input files char *pszInFileSpecs[cMaxNumBedFiles]; // input (wildcards allowed) BED files char szOutFile[_MAX_PATH]; // write merged to this file // 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 *ProcMode = arg_int0("m","mode","<int>", "merge processing mode: 0 - Strand independent union, 1 - Strand dependent union"); struct arg_int *strand = arg_int0("s","strand","<int>", "filter for this strand: 0 - any, 1 - Watson '+', 2 - Crick '-' (default is any)"); struct arg_int *region = arg_int0("r","genomicregion","<int>", "Retain annotated regions 0:ALL,1:Intergenic,2:Exons,3:Introns,4:CDS,5:UTRs,6:5'UTR,7:3'UTR (default = ALL)"); struct arg_int *minlen = arg_int0("l","minlen","<int>", "generated merged features must be of at least this length (default is 20)"); struct arg_int *joinlen = arg_int0("j","joinlen","<int>", "merge features which are separated by at most this length, 0 if no merging (default is 1)"); struct arg_str *excludechroms = arg_strn("Z","chromexclude","<string>",0,cMaxExcludeChroms,"regular expressions defining chromosomes to always exclude"); struct arg_str *includechroms = arg_strn("z","chromeinclude","<string>",0,cMaxIncludeChroms,"regular expressions defining chromosomes to explicitly include if not already excluded"); struct arg_file *infiles = arg_filen("i","srcfiles","<file>",0, cMaxNumBedFiles,"merge features contained in these BED files (wildcards alllowed)"); struct arg_file *OutFile = arg_file1("o",NULL,"<file>", "output merged features to this BED file"); struct arg_end *end = arg_end(20); void *argtable[] = {help,version,FileLogLevel,LogFile, ProcMode,strand,minlen,joinlen,region,excludechroms,includechroms,infiles,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 BED Merge Blocks, 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] : ePMDefault; if(iProcMode < ePMDefault || iProcMode >= ePMplaceholder) { printf("Error: Processing mode '-p%d' is not in range 0..%d",iProcMode,ePMplaceholder-1); exit(1); } MinLen = minlen->count ? minlen->ival[0] : cDfltMergeLen; if(MinLen < cMinMergeLen || MinLen > cMaxMergeLen) { printf("Error: minimum length '-l%d' is not in range %d..%d",MinLen,cMinMergeLen,cMaxMergeLen); exit(1); } JoinLen = joinlen->count ? joinlen->ival[0] : 1; if(JoinLen < 0 || JoinLen > cMaxMergeLen) { printf("Error: Join length '-j%d' is not in range 0..%d",JoinLen,cMaxMergeLen); exit(1); } Strand = strand->count ? strand->ival[0] : 0; if(Strand < 0 || Strand > 2) { printf("\nError: Strand '-s%d' specified outside of range 0..2",Strand); exit(1); } switch(Strand) { case 1: Strand = (int)'+'; break; case 2: Strand = (int)'-'; break; case 0: Strand = (int)'*'; break; } Region = (etBEDRegion)(region->count ? region->ival[0] : eMEGRAny); // default as being any region if(Region < eMEGRAny || Region > eMEG3UTR) { printf("\nSpecified region '-g%d' outside of range 0..%d",Region,eMEG3UTR); exit(1); } NumIncludeChroms = includechroms->count; for(Idx=0;Idx < includechroms->count; Idx++) { LenFileList = (int)strlen(includechroms->sval[Idx]); pszIncludeChroms[Idx] = new char [LenFileList+1]; strcpy(pszIncludeChroms[Idx],includechroms->sval[Idx]); TrimQuotes(pszIncludeChroms[Idx]); } NumExcludeChroms = excludechroms->count; for(Idx=0;Idx < excludechroms->count; Idx++) { LenFileList = (int)strlen(excludechroms->sval[Idx]); pszExcludeChroms[Idx] = new char [LenFileList+1]; strcpy(pszExcludeChroms[Idx],excludechroms->sval[Idx]); TrimQuotes(pszExcludeChroms[Idx]); } if(!infiles->count) { printf("\nError: No input file(s) specified with with '-i<filespec>' option)"); exit(1); } for(NumInFiles=Idx=0;NumInFiles < cMaxNumBedFiles && Idx < infiles->count; Idx++) { pszInFileSpecs[Idx] = NULL; if(pszInFileSpecs[NumInFiles] == NULL) pszInFileSpecs[NumInFiles] = new char [_MAX_PATH]; strncpy(pszInFileSpecs[NumInFiles],infiles->filename[Idx],_MAX_PATH); pszInFileSpecs[NumInFiles][_MAX_PATH-1] = '\0'; CUtility::TrimQuotedWhitespcExtd(pszInFileSpecs[NumInFiles]); if(pszInFileSpecs[NumInFiles][0] != '\0') NumInFiles++; } if(!NumInFiles) { printf("\nError: After removal of whitespace, no input file(s) specified with '-i<filespec>' option)"); exit(1); } strncpy(szOutFile,OutFile->filename[0],_MAX_PATH); szOutFile[_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,"Processing Mode: %d (%s)",iProcMode,ProcMode2Txt((etProcMode)iProcMode)); gDiagnostics.DiagOutMsgOnly(eDLInfo,"process for this strand only: '%c'",(char)Strand); gDiagnostics.DiagOutMsgOnly(eDLInfo,"generated merged features will be at least this length: %d",MinLen); if(JoinLen == 0) gDiagnostics.DiagOutMsgOnly(eDLInfo,"keep separate features, no merging"); else gDiagnostics.DiagOutMsgOnly(eDLInfo,"merge features separated by upto: %d",JoinLen); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Retain Region: %s",Region2Txt((etBEDRegion)Region)); for(Idx = 0; Idx < NumIncludeChroms; Idx++) gDiagnostics.DiagOutMsgOnly(eDLInfo,"reg expressions defining chroms to include: '%s'",pszIncludeChroms[Idx]); for(Idx = 0; Idx < NumExcludeChroms; Idx++) gDiagnostics.DiagOutMsgOnly(eDLInfo,"reg expressions defining chroms to exclude: '%s'",pszExcludeChroms[Idx]); for(Idx=0;Idx < NumInFiles; Idx++) gDiagnostics.DiagOutMsgOnly(eDLInfo,"merge features from this input BED file (%d): '%s'",Idx+1,pszInFileSpecs[Idx]); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output merged features into BED file: '%s'",szOutFile); gStopWatch.Start(); #ifdef _WIN32 SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); #endif Rslt = Process((etProcMode)iProcMode,Strand,MinLen,JoinLen,Region, NumIncludeChroms, // number of chromosome regular expressions to include pszIncludeChroms, // array of include chromosome regular expressions NumExcludeChroms, // number of chromosome expressions to exclude pszExcludeChroms, // array of exclude chromosome regular expressions NumInFiles,pszInFileSpecs,szOutFile); 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 BED Merge Blocks, 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); } }
void processArgs(int argc, char **argv) { int nerrors, i; char *savptr, str[1024], *str1, machName[1024], sessIDstr[1024]; struct arg_str *arg_sessionID = arg_str1( "S", "sessionID", "<mach.sessionID>", "session ID of run to be processed\n"); struct arg_str *arg_propIDs = arg_str0( "P", "proposals", "<int [,int [,int]]>", "quoted string of proposal numbers to use\n"); struct arg_str *arg_skipDays = arg_str0( "D", "days", "<skip [,length]>", "skip days at start, do length days after\n"); struct arg_lit *arg_Check = arg_lit0( NULL, "checkobs", "check observations for basic errors\n"); struct arg_lit *arg_TimeSummary = arg_lit0( NULL, "timesummary", "time summary"); struct arg_lit *arg_PeriodSearch = arg_lit0( NULL, "periodsearch", "make periodogram plots\n"); struct arg_lit *arg_Hourglass = arg_lit0( "H", "hourglass", "make hourglass plot\n"); struct arg_lit *arg_Opposition = arg_lit0( NULL, "opposition", "make solar angle (opposition) plot\n"); struct arg_str *arg_Airmass = arg_str0( NULL, "airmass", "<int>", "make per-field airmass plot (0 is max, 1 is median)\n"); struct arg_lit *arg_SixVisits = arg_lit0( "V", "sixvisitnum", "make all-filter visit numbers plot\n"); struct arg_lit *arg_5sigma = arg_lit0( "V", "5sigma", "make aitoff plot for median 5sigma also per proposal\n"); struct arg_lit *arg_skyb = arg_lit0( "V", "skyb", "make aitoff plot for median skyb also per proposal\n"); struct arg_lit *arg_seeing = arg_lit0( "V", "seeing", "make aitoff plot for median seeing also per proposal\n"); struct arg_lit *arg_Visits = arg_lit0( "v", "visitnum", "make visit numbers plot for specified filters\n \ (requires -f|--filters)\n"); struct arg_str *arg_reqFilters = arg_str0( "f", "filters", "<f [,f [,f]]>", "which filters to use; f in {ugrizy}\n"); struct arg_lit *arg_NEOrevisits = arg_lit0( "R", "revisits", "make NEO revisit numbers plot\n"); struct arg_lit *arg_Slew = arg_lit0( NULL, "slew", "make slew time histogram\n"); struct arg_lit *arg_SNtiming = arg_lit0( NULL, "sntiming", "make SN Ia cadence plots\n"); struct arg_file *arg_plotfileRoot = arg_file0(NULL, "plotfile", "harcopy file", "root name of plotfile for hardcopy\n"); struct arg_file *arg_plotTitle = arg_file0(NULL, "plottitle", "<string>", "title for plots\n"); struct arg_lit *arg_help = arg_lit0( "h", "help", "show usage\n"); struct arg_lit *arg_debug = arg_lit0( "d", "debug", "debugging output\n"); struct arg_str *arg_hostname = arg_str1( "N", "hostname", "<string>", "if you know hostname \n"); struct arg_str *arg_databasename = arg_str1( "DB", "database", "<string>", "if you know the db name \n"); struct arg_str *arg_designstretch = arg_str1( NULL, "designstretch", "<int>", "design or stretch value\n"); struct arg_end *arg_endp = arg_end(20); void *argtable[] = {arg_sessionID, arg_propIDs, arg_skipDays, arg_TimeSummary, arg_Check, arg_PeriodSearch, arg_Hourglass, arg_Opposition, arg_Airmass, arg_SixVisits, arg_5sigma, arg_skyb, arg_seeing, arg_Slew, arg_Visits, arg_reqFilters, arg_NEOrevisits, arg_SNtiming, arg_plotfileRoot, arg_plotTitle, arg_debug, arg_help, arg_hostname, arg_designstretch, arg_databasename, arg_endp}; if (arg_nullcheck(argtable) != 0) fprintf(stderr, "error: insufficient memory\n"); nerrors = arg_parse(argc,argv,argtable); // process arguments // render assistance when asked if(arg_help->count>0) { fprintf(stderr,"Usage: %s [options]\n where [options] are:\n\n",argv[0]); arg_print_glossary(stderr, argtable, "%-45s %s"); // arg_print_syntaxv(stderr, argtable, "\n"); exit(1); } // list errors if (nerrors > 0) { arg_print_errors(stdout,arg_endp,argv[0]); fprintf(stderr,"\nUsage: %s [options]\n where [options] are:\n\n",argv[0]); arg_print_glossary(stderr, argtable, "%-45s %s"); // arg_print_syntaxv(stderr, argtable, "\n"); exit(1); } // set database tableName and sessionID from sessionID argument //strcpy(str, *arg_sessionID->sval); //strcpy(machName, strtok_r(str,".",&savptr)); //strcpy(sessIDstr, strtok_r(NULL,".",&savptr)); strcpy(sessIDstr, *arg_sessionID->sval); sessionID = atoi(sessIDstr); if ( *arg_databasename->sval == NULL ) { sprintf(database, "%s", "OpsimDB"); } else { sprintf(database, "%s", *arg_databasename->sval); } if ( *arg_hostname->sval == NULL ) { if ( gethostname(identifier, identifier_length) == 0 ) { sprintf(hostname, "%s", identifier); } else { printf( "Hostname : %s\n", strerror(errno)); exit(1); } } else { sprintf (hostname, "%s", *arg_hostname->sval); } sprintf(tableName, "output_%s_%d", hostname, sessionID); // set action flags if(arg_5sigma->count>0) do5sigma=1; if(arg_skyb->count>0) doskyb=1; if(arg_seeing->count>0) doSeeing=1; if(arg_TimeSummary->count>0) doTimeSummary=1; if(arg_Check->count>0) doCheck=1; if(arg_PeriodSearch->count>0) doPeriodSearch=1; if(arg_Hourglass->count>0) doHourglass=1; if(arg_Opposition->count>0) doOpposition=1; if(arg_designstretch->count>0) { if ( strcmp(*arg_designstretch->sval, "0") == 0) { useDesignStretch = 0; } else { useDesignStretch = 1; } } if(arg_Airmass->count>0) { doAirmass=1; if(strcmp(*arg_Airmass->sval, "0") != 0) { useMaxAirmass=0; } else { useMaxAirmass=1; } } if(arg_SixVisits->count>0) doSixVisits=1; if(arg_Visits->count>0) { doVisits=1; if(arg_reqFilters->count==0) { fprintf(stderr,"Error: with -v|--visitsnum must give -f|--filters\n"); exit(1); } strcpy(str, *arg_reqFilters->sval); i = 0; strcpy(desiredFilters[i],strtok_r(str," ,",&savptr)); i++; while((str1=strtok_r(NULL," ,",&savptr))!= NULL) { strcpy(desiredFilters[i],str1); i++; } ndesiredFilters = i; } if(arg_NEOrevisits->count>0) doNEOrevisits=1; if(arg_SNtiming->count>0) doSNtiming=1; if(arg_Slew->count>0) doSlew=1; if(arg_propIDs->count>0) { strcpy(str, *arg_propIDs->sval); i = 0; propIDs[i] = atoi(strtok_r(str," ,",&savptr)); i++; while((str1=strtok_r(NULL," ,",&savptr))!= NULL) { propIDs[i] = atoi(str1); i++; } nIDs = i; } if(arg_plotfileRoot->count>0) { strcpy(plotfileRoot,arg_plotfileRoot->filename[0]); doHardcopy = 1; } if(arg_plotTitle->count>0) { strcpy(plotTitle,arg_plotTitle->filename[0]); } if(arg_skipDays->count>0) { strcpy(str, *arg_skipDays->sval); skipDays = atoi(strtok_r(str," ,",&savptr)); str1 = strtok_r(NULL," ,",&savptr); if(str1 != (char *) NULL) lengthDays = atoi(str1); } if(arg_debug->count>0) { debug = 1; } #if 0 printf(" sessionID: %d\n", sessionID); printf(" skipDays: %d\n", skipDays); printf(" lengthDays: %d\n", lengthDays); printf(" nIDs: %d\n", nIDs); if(nIDs>0) { printf(" using IDs: "); for(i=0; i<nIDs; i++) printf(" %d",propIDs[i]); printf("\n"); } printf(" doCheck: %d\n", doCheck); printf("doPeriodSearch: %d\n", doPeriodSearch); printf(" doHourglass: %d\n", doHourglass); printf(" doOpposition: %d\n", doOpposition); printf(" doSixVisits: %d\n", doSixVisits); printf(" doVisits: %d\n", doVisits); if(doVisits) { printf(" using filters: "); for(i=0; i<ndesiredFilters; i++) printf(" %s",desiredFilters[i]); printf("\n"); } printf(" doNEOrevisits: %d\n", doNEOrevisits); printf(" doSNtiming: %d\n", doSNtiming); if(strlen(plotfileRoot)>0) printf(" hardcopy file: \"%s\"\n", plotfileRoot); if(strlen(plotTitle)>0) printf(" plot title: \"%s\"\n", plotTitle); printf(" debug: %d\n", debug); #endif arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[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 .BK file"); struct arg_file *output = arg_file0("o", "output", "<file>", "Output .BK file"); struct arg_int *anim = arg_int0("a", "anim", "<animation_id>", "Select animation"); struct arg_lit *all_anims = arg_lit0("A", "all_anims", "All animations"); struct arg_int *sprite = arg_int0("s", "sprite", "<sprite_id>", "Select sprite (requires --anim)"); struct arg_lit *keylist = arg_lit0(NULL, "keylist", "Prints a list of valid fields for --key."); struct arg_str *key = arg_strn("k", "key", "<key>", 0, 2, "Select key"); struct arg_str *value = arg_str0(NULL, "value", "<value>", "Set value (requires --key)"); struct arg_lit *play = arg_lit0(NULL, "play", "Play animation or sprite (requires --anim)"); struct arg_int *scale = arg_int0(NULL, "scale", "<factor>", "Scales sprites (requires --play)"); struct arg_lit *parse = arg_lit0(NULL, "parse", "Parse value (requires --key)"); struct arg_end *end = arg_end(20); void* argtable[] = {help,vers,file,output,anim,all_anims,sprite,keylist,key,value,play,scale,parse,end}; const char* progname = "bktool"; // 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, "%-30s %s\n"); goto exit_0; } // Handle version if(vers->count > 0) { printf("%s v0.1\n", progname); printf("Command line One Must Fall 2097 .BK 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; } // Argument dependencies if(anim->count == 0) { if(sprite->count > 0) { printf("--sprite requires --anim\n"); printf("Try '%s --help' for more information.\n", progname); goto exit_0; } if(play->count > 0) { printf("--play requires --anim\n"); printf("Try '%s --help' for more information.\n", progname); goto exit_0; } } if(key->count == 0) { if(value->count > 0) { printf("--value requires --key\n"); printf("Try '%s --help' for more information.\n", progname); goto exit_0; } } if(output->count == 0) { if(value->count > 0) { printf("--value requires --output\n"); printf("Try '%s --help' for more information.\n", progname); goto exit_0; } } if(play->count == 0) { if(scale->count > 0) { printf("--scale requires --play\n"); printf("Try '%s --help' for more information.\n", progname); 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; } // Init SDL SDL_Init(SDL_INIT_VIDEO); // Load file sd_bk_file *bk = sd_bk_create(); int ret = sd_bk_load(bk, file->filename[0]); if(ret) { printf("Unable to load BK file! Make sure the file exists and is a valid BK file.\n"); goto exit_1; } // Scaling variable int _sc = 1; if(scale->count > 0) { _sc = scale->ival[0]; if(_sc > 4) _sc = 4; if(_sc < 1) _sc = 1; } // Handle args if(sprite->count > 0) { // Make sure sprite exists. if(!check_anim_sprite(bk, anim->ival[0], sprite->ival[0])) { goto exit_1; } sd_sprite *sp = bk->anims[anim->ival[0]]->animation->sprites[sprite->ival[0]]; // Handle arguments if(key->count > 0) { if(value->count > 0) { sprite_set_key(sp, key->sval, key->count, value->sval[0]); } else { sprite_get_key(sp, key->sval, key->count); } } else if(keylist->count > 0) { sprite_keylist(); } else if(play->count > 0) { sprite_play(bk, _sc, anim->ival[0], sprite->ival[0]); } else { sprite_info(sp, anim->ival[0], sprite->ival[0]); } } else if(anim->count > 0) { // Make sure the bkanim exists if(!check_anim(bk, anim->ival[0])) { goto exit_1; } sd_bk_anim *bka = bk->anims[anim->ival[0]]; sd_animation *ani = bka->animation; if(key->count > 0) { if(value->count > 0) { bkanim_set_key(bka, ani, key->sval, key->count, value->sval[0]); } else { bkanim_get_key(bka, ani, key->sval, key->count, parse->count); } } else if(keylist->count > 0) { bkanim_keylist(); } else if(play->count > 0) { anim_play(bk, _sc, anim->ival[0]); } else { bkanim_info(bka, ani, anim->ival[0]); } } else if(all_anims->count > 0) { sd_bk_anim *bka; sd_animation *ani; for(int i = 0; i < 50; i++) { if (bk->anims[i]) { bka = bk->anims[i]; ani = bka->animation; if(key->count > 0) { if(value->count > 0) { bkanim_set_key(bka, ani, key->sval, key->count, value->sval[0]); } else { printf("Animation %2u: ", i); bkanim_get_key(bka, ani, key->sval, key->count, parse->count); } } else { printf("\n"); bkanim_info(bka, ani, i); } } } } else { if(key->count > 0) { if(value->count > 0) { bk_set_key(bk, key->sval, key->count, value->sval[0]); } else { bk_get_key(bk, key->sval, key->count); } } else if(keylist->count > 0) { bk_keylist(); } else { bk_info(bk); } } // Write output file if(output->count > 0) { sd_bk_save(bk, output->filename[0]); } // Quit exit_1: sd_bk_delete(bk); SDL_Quit(); exit_0: arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0])); return 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_file0(NULL,NULL,"address","zmq address"), end = arg_end(20), }; int32_t nerrors = arg_parse(argc,argv,argtable); if (help->count) { fprintf(stdout,"tmpcache %s - version 0\n",__FUNCTION__); /*FIXME*/ 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); tc_snapshotconfig_t config; /* check if there is an address or not */ if (netaddress0->count == 0) { config.cachepath = bfromcstr (cachepath->filename[0]); config.signalf = checksignal; config.errorf = (fsyslog->count) ? logerror : printerror; if (fsyslog->count) { openlog (NULL,LOG_PID|LOG_NDELAY,LOG_USER); syslog (LOG_INFO,"writing cache %s to stdout",btocstr(config.cachepath)); } tc_snapshotcachetostdout (&config); if (fsyslog->count) { syslog (LOG_INFO,"done writing cache %s to stdout",btocstr(config.cachepath)); closelog(); } bdestroy (config.cachepath); } else { config.cachepath = bfromcstr (cachepath->filename[0]); /*TODO: check for .cdb*/ config.address = bfromcstr (netaddress0->filename[0]); /*TODO: check for correct address*/ config.signalf = checksignal; config.errorf = (fsyslog->count) ? logerror : printerror; if (fsyslog->count) { openlog (NULL,LOG_PID|LOG_NDELAY,LOG_USER); syslog (LOG_INFO,"writing cache from %s @ %s",btocstr(config.cachepath),btocstr(config.address)); } tc_snapshotcachetoaddress (&config); if (fsyslog->count) { syslog (LOG_INFO,"closing cache %s @ %s for reading",btocstr(config.cachepath),btocstr(config.address)); closelog(); } bdestroy (config.address); bdestroy (config.cachepath); } finish: arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); exit(0); }
int main(int argc, char **argv) { const char* progname = "z-connector"; struct arg_file *device = arg_file1("dD", "device", NULL, "path to the serial port of Z-Wave dongle"); struct arg_str *server = arg_str1("sS", "server", NULL, "IP address or host name to connect to"); struct arg_int *port = arg_int0("pP", "port", NULL, "port number (defaults to 9087)"); struct arg_file *cert = arg_file0(NULL, "cert", NULL, "personal certificate"); struct arg_file *key = arg_file0(NULL, "key", NULL, "personal certificate key"); struct arg_file *cacert = arg_file0(NULL, "cacert", NULL, "CA certificate"); struct arg_file *log = arg_file0("lL", "log", NULL, "file to write log to (defaults to stdout)"); struct arg_lit *debug = arg_lit0(NULL, "debug", "log debugging information"); struct arg_lit *help = arg_lit0("h", "help", "print this help and exit"); struct arg_end *end = arg_end(20); void* argTable[] = {device, server, port, cert, key, cacert, log, debug, help, end}; #ifdef WIN32 WSADATA wsa; WORD wsaVersion = MAKEWORD(2, 2); int wsaError; DWORD win32err; #endif int retCode, nErrors; if (arg_nullcheck(argTable) != 0) { printf("%s: insufficient memory\n", progname); CLEAN_RETURN(1); } nErrors = arg_parse(argc, argv, argTable); if (IS_ARG_SET(help)) { printf("Usage: %s", progname); arg_print_syntax(stdout, argTable, "\n"); //printf("Print certain system information. With no options, same as -s.\n\n"); arg_print_glossary(stdout, argTable," %-25s %s\n"); printf("\nReport bugs to <*****@*****.**>.\n"); CLEAN_RETURN(0); } LogLevel = (IS_ARG_SET(debug)) ? 3 : 2; if (nErrors > 0) { arg_print_errors(stdout, end, progname); printf("Try '%s --help' for more information.\n", progname); CLEAN_RETURN(2); } #ifdef WIN32 hStoppingEvent = CreateEvent(NULL, TRUE, FALSE, "Local\\Z-Agent-Stop"); if (hStoppingEvent == NULL) { win32err = GetLastError(); if (win32err == ERROR_INVALID_HANDLE) { printf("Another instance is already running\n"); CLEAN_RETURN(0); } else { printf("Failed to create synchronization event: %d\n", win32err); CLEAN_RETURN(3); } } wsaError = WSAStartup(wsaVersion, &wsa); if (wsaError != 0) { printf("WSA Startup failed with code %d\n", wsaError); CloseHandle(hStoppingEvent); CLEAN_RETURN(3); } if (wsa.wVersion != wsaVersion) { printf("Required WSA version not found\n"); CloseHandle(hStoppingEvent); CLEAN_RETURN(3); } #endif retCode = main_impl(device->filename[0], server->sval[0], SAFE_INT(port, 9087), SAFE_FILE(cert, ""), SAFE_FILE(key, ""), SAFE_FILE(cacert, ""), SAFE_FILE(log, "-")); #ifdef WIN32 WSACleanup(); CloseHandle(hStoppingEvent); #endif CLEAN_RETURN(retCode); }
int main(int argc, char *argv[]) { struct arg_str *cblOpt = arg_str1("c", "cable", "nero:<VID>:<PID> | xil3 | dusb", "cable driver to use"); struct arg_lit *scanOpt = arg_lit0("s", "scan", " scan the JTAG chain"); struct arg_file *bitOpt = arg_file0("b", "bitfile", "<fileName>", " bit file to load"); struct arg_uint *devOpt = arg_uint0("d", "device", "<device>", " target device (default \"1\")"); struct arg_lit *helpOpt = arg_lit0("h", "help", " print this help and exit\n"); struct arg_end *endOpt = arg_end(20); void* argTable[] = {cblOpt, scanOpt, bitOpt, devOpt, helpOpt, endOpt}; const char *progName = "xilprg"; uint32 exitCode = 0; int numErrors; const char *cable, *bitFile; uint32 devNum; char line[1024]; char configFileName[4097]; // TODO: Fix, somehow. if ( arg_nullcheck(argTable) != 0 ) { fprintf(stderr, "%s: insufficient memory\n", progName); fail(1); } numErrors = arg_parse(argc, argv, argTable); if ( helpOpt->count > 0 ) { printf("Xilinx Programmer 0.6 Copyright (C) 2006-2011 Zoltan Csizmadia & Chris McClelland\n\nUsage: %s", progName); arg_print_syntax(stdout, argTable, "\n"); printf("\nProgram a Xilinx FPGA.\n\n"); arg_print_glossary(stdout, argTable," %-10s %s\n"); fail(0); } if ( numErrors > 0 ) { arg_print_errors(stdout, endOpt, progName); fprintf(stderr, "Try '%s --help' for more information.\n", progName); fail(2); } if ( (scanOpt->count == 0 && bitOpt->count == 0) || (scanOpt->count != 0 && bitOpt->count != 0) ) { fprintf(stderr, "%s: you must specify either -s|--scan or -b|--bitfile, but not both\n", progName); fprintf(stderr, "Try '%s --help' for more information.\n", progName); fail(3); } cable = cblOpt->sval[0]; bitFile = bitOpt->count ? bitOpt->filename[0] : NULL; devNum = devOpt->count ? devOpt->ival[0] : 1; if ( initialize() ) { fprintf(stderr, "%s failed to initialize!\n", progName); fail(4); } if ( getConfigFullPath("xilprg.conf", configFileName, sizeof(configFileName)) ) { fprintf(stderr, "%s failed to determine the location of its config file!\n", progName); fail(5); } if ( load_config_file(configFileName) ) { fprintf(stderr, "%s failed to load its config file from %s!\n", progName, configFileName); fail(6); } try { sprintf(line, "cable %s", cable); process_command_line(line); if ( scanOpt->count ) { process_command_line("detect"); } else { sprintf(line, "program %lu \"%s\"", devNum, bitFile); process_command_line(line); } } catch ( const std::exception &ex ) { fprintf(stderr, "%s failed: %s!\n", progName, ex.what()); fail(7); } cleanup: uninitialize(); arg_freetable(argTable, sizeof(argTable)/sizeof(argTable[0])); return exitCode; }
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 {
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[]) { 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; }
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; }
int GRTCLCrackCommandLineData::ParseCommandLine(int argc, char *argv[]) { int deviceCount, i; std::vector<std::string> webTableFilenames; // Command line argument parsing with argtable struct arg_lit *verbose = arg_lit0("v", "verbose", "verbose output"); struct arg_lit *silent = arg_lit0(NULL, "silent", "silence all output"); // Table related options struct arg_file *table_file = arg_filen(NULL,NULL,"<file>", 0, 10000, "GRT Tables to use"); struct arg_file *hash_file = arg_file0("f","hashfile","<file>", "Hashfile to use"); struct arg_str *hash_value = arg_str0("s", "hashstring", "hashstring", "The hash string"); struct arg_str *hash_type = arg_str1("h", "hashtype", "{NTLM, MD4, MD5, SHA1}", "hash type to crack"); // CUDA related params struct arg_int *device = arg_int0("d", "device", "<n>", "OpenCL device to use"); struct arg_int *platform = arg_int0("p", "platform", "<n>", "OpenCL platform to use"); struct arg_int *m = arg_int0("m", "ms", "<n>", "target step time in ms"); struct arg_int *blocks = arg_int0("b", "blocks", "<n>", "number of thread blocks to run"); struct arg_int *threads = arg_int0("t", "threads", "<n>", "number of threads per block"); struct arg_lit *zerocopy = arg_lit0("z", "zerocopy", "use zerocopy memory"); struct arg_file *o = arg_file0("o", "outputfile", "outputfile", "output file for results"); // hexoutput: Adds hex output to all password outputs. struct arg_lit *hex_output = arg_lit0(NULL, "hexoutput", "Adds hex output to all hash outputs"); struct arg_lit *amd_kernels = arg_lit0(NULL, "amd", "use AMD vector kernels"); struct arg_int *vector_width = arg_int0(NULL, "vectorwidth", "<n>", "vector width"); struct arg_lit *debug = arg_lit0(NULL, "debug", "Use debug display class"); struct arg_lit *devdebug = arg_lit0(NULL, "devdebug", "Developer debugging output"); struct arg_str *debugfiles = arg_str0(NULL, "debugdumpfiles", "<filename>", "Filename base to dump candidates and chains to"); struct arg_int *prefetch_count = arg_int0(NULL, "prefetch", "<n>", "number of prefetch threads"); struct arg_int *candidates_to_skip = arg_int0(NULL, "skip", "<n>", "number of candidate hashes to skip"); struct arg_str *table_url = arg_str0(NULL, "tableurl", "<URL>", "URL of the web table script"); struct arg_str *table_username = arg_str0(NULL, "tableusername", "<username>", "Username, if required, for the web table script"); struct arg_str *table_password = arg_str0(NULL, "tablepassword", "<password>", "Password, if required, for the web table script"); struct arg_end *end = arg_end(20); void *argtable[] = {verbose,silent,table_file,hash_value,hash_file,hash_type, device,platform,m,blocks,threads,zerocopy,o,amd_kernels,vector_width, debug, devdebug, prefetch_count,table_url,table_username,table_password, candidates_to_skip,debugfiles,hex_output,end}; // Get arguments, collect data, check for basic errors. if (arg_nullcheck(argtable) != 0) { printf("error: insufficient memory\n"); } // Look for errors int nerrors = arg_parse(argc,argv,argtable); if (nerrors > 0) { // Print errors, exit. arg_print_errors(stdout,end,argv[0]); //arg_print_syntax(stdout,argtable,"\n\n"); printf("\n\nOptions: \n"); arg_print_glossary(stdout,argtable," %-20s %s\n"); exit(1); } // Verbose & silent if (verbose->count) { this->Verbose = 1; } if (silent->count) { this->Silent = 1; } if (zerocopy->count) { this->CUDAUseZeroCopy = 1; } if (debug->count) { this->Debug = 1; } if (devdebug->count) { this->Debug = 1; this->DeveloperDebug = 1; } if (debugfiles->count) { this->DebugDump = 1; this->DebugDumpFilenameBase = *debugfiles->sval; } if (prefetch_count->count) { this->NumberPrefetchThreads = *prefetch_count->ival; } if (candidates_to_skip->count) { this->CandidateHashesToSkip = *candidates_to_skip->ival; } // Web table stuff if (table_url->count) { this->useWebTable = 1; this->tableURL = *table_url->sval; // If someone has NOT specified the candidates to skip, set to default. if (!candidates_to_skip->count) { this->CandidateHashesToSkip = DEFAULT_CANDIDATES_TO_SKIP; } } if (table_username->count) { this->tableUsername = *table_username->sval; } if (table_password->count) { this->tablePassword = *table_password->sval; } this->HashType = this->GRTHashTypes->GetHashIdFromString(*hash_type->sval); if (this->HashType == -1) { printf("Unknown hash type %s: Exiting.\n\n", *hash_type->sval); exit(1); } int correct_length = this->GRTHashTypes->GetHashLengthFromId(this->HashType); // if we know the correct length, we make sure the hash is the correct length if (correct_length != 0) { if ((hash_value->count) && (strlen(*hash_value->sval) != correct_length)) { printf("Hash string is not %d hex characters. Exiting.\n\n", correct_length); exit(1); } } if (hash_value->count) { convertAsciiToBinary(*hash_value->sval, this->Hash, 16); } else if (hash_file->count) { this->hashFileName = hash_file->filename[0]; this->useHashFile = 1; } else { printf("Must provide a hash value or a hash file!\n"); exit(1); } if (o->count) { this->outputHashFileName = o->filename[0]; this->useOutputHashFile = 1; } // Desired kernel time if (m->count) { this->KernelTimeMs = *m->ival; } // Do this to emulate CUDA behavior for now... // Threads - if not set, leave at default 0 if (threads->count) { this->OpenCLWorkitems = *threads->ival; } // Blocks - if not set, leave at default 0 if (blocks->count) { this->OpenCLWorkgroups = *blocks->ival * this->OpenCLWorkitems; } if (hex_output->count) { this->AddHexOutput = 1; } // Allocate space for the list of pointers // Create the table header type if (this->useWebTable) { this->TableHeader = new GRTTableHeaderVWeb(); this->TableHeader->setWebURL(this->tableURL); this->TableHeader->setWebUsername(this->tableUsername); this->TableHeader->setWebPassword(this->tablePassword); GRTTableHeaderVWeb *WebTableHeader = (GRTTableHeaderVWeb *)this->TableHeader; webTableFilenames = WebTableHeader->getHashesFromServerByType(this->HashType); } else { // V1 will work for both V1 & V2 types this->TableHeader = new GRTTableHeaderV1(); } // If we don't have any table filenames, get the ones from the web. // Note: The script ONLY reutrns valid tables. if ((table_file->count == 0) && this->useWebTable) { this->Table_File_Count = webTableFilenames.size(); this->Table_Filenames = (char **)malloc(this->Table_File_Count * sizeof(char *)); for (i = 0; i < this->Table_File_Count; i++) { // Increment size by 1 for null termination this->Table_Filenames[i] = (char *)malloc((webTableFilenames.at(i).size() + 1) * sizeof(char)); strcpy(this->Table_Filenames[i], webTableFilenames.at(i).c_str()); } } else { this->Table_File_Count = table_file->count; this->Table_Filenames = (char **)malloc(this->Table_File_Count * sizeof(char *)); // Handle the file list sanely for (i = 0; i < table_file->count; i++) { // Check to ensure the file is valid if (!this->TableHeader->isValidTable(table_file->filename[i], -1)) { printf("%s is not a valid GRT table! Exiting.\n", table_file->filename[i]); exit(1); } // Check to ensure the file is of the right type if (!this->TableHeader->isValidTable(table_file->filename[i], this->HashType)) { printf("%s is not a valid %s GRT table!\n", table_file->filename[i], this->GRTHashTypes->GetHashStringFromId(this->HashType)); exit(1); } // Increment size by 1 for null termination this->Table_Filenames[i] = (char *)malloc((strlen(table_file->filename[i]) + 1) * sizeof(char)); strcpy(this->Table_Filenames[i], table_file->filename[i]); } } // Finally, set the CUDA device and look for errors. if (device->count) { this->OpenCLDevice = *device->ival; } if (platform->count) { this->OpenCLPlatform = *platform->ival; } if (amd_kernels->count) { this->useAmdKernels = 1; this->vectorWidth = 4; } if (vector_width->count) { this->vectorWidth = *vector_width->ival; } }
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; }
int main(int argc, char* argv[]) { struct arg_lit *help; struct arg_file *input, *output; struct arg_str *rotation; struct arg_end *end; /* command line parsing through argtable package */ void* argtable[] = { help = arg_lit0("h", "help", "display this help and exit"), input = arg_file0("i", "input", "input", "name of the input file (default stdin"), output = arg_file0("o", "output", "file", "name of the output file (default stdout)"), rotation = arg_str1(NULL, NULL, "\"x y z w\"", "rotate w degrees around axis x y z"), end = arg_end(20) }; const char* progname = "xyztk-rotate"; int rc = 0; int nerrors; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n", progname); rc=1; goto exit; } /* set default values */ /* parse the command line flags, overriding default values */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout,argtable,"\n"); printf("\n"); arg_print_glossary(stdout,argtable," %-40s %s\n"); printf("\n"); rc=0; goto exit; } /* special case: no command line options induces brief help */ if (argc==1) { printf("Try '%s --help' for more information.\n",progname); rc=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,progname); printf("Try '%s --help' for more information.\n",progname); rc=1; goto exit; } /* set global structures */ /* initialize I/O pointers */ FILE* in; if (input->count) { in = fopen(input->filename[0], "r"); } else { in = stdin; } FILE* out; if (output->count) { out = fopen(output->filename[0], "w"); } else { out = stdout; } /* initialize molecule structure */ xyztk_molecule_t molecule; xyztk_molecule_load (&molecule, in); /* read rotation from string */ xyztk_quat_t r; sscanf (rotation->sval[0], "%lf%lf%lf%lf", &r.x, &r.y, &r.z, &r.w); xyztk_molecule_rotate (&molecule, &r); /* print output */ int i; fprintf(out, "%d\n", molecule.n_atoms); fprintf(out, "%s", molecule.name); for (i = 0; i < molecule.n_atoms; ++i) { fprintf(out, "%-8s %20.14lf %20.14lf %20.14lf \n", molecule.label[i].s, molecule.coord[i].x, molecule.coord[i].y, molecule.coord[i].z); } exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return rc; }
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 {
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; // processing mode char szRefFile[_MAX_PATH]; // nput from reference csv file char szFilterRefIDFile[_MAX_PATH]; // exclude any RefIDs in this filter file char szRelFile[_MAX_PATH]; // input from relative csv file(s) char szRsltfile[_MAX_PATH]; // output to results CSV file int iMinLen; // minimum accepted length int iMaxLen; // maximum accepted length // 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_int *ProcMode = arg_int0("m", "mode","<int>", "processing mode (default 0) 0: Identities (Match/Match+Mismatches), 1: Identities (Match/CoreLength), 2: Aligned Length 3: Score"); struct arg_file *RefFile = arg_file1("i","in","<file>", "input from reference csv file"); struct arg_file *FilterRefIDFile = arg_file0("X",NULL,"<file>", "filter out any ref or rel loci with RefIDs in this filter file"); struct arg_file *RelFile = arg_file1("I","in","<file>", "input from relative csv file(s) - can use wildcards"); struct arg_file *Rsltfile= arg_file1("o","out","<file>", "output to results CSV file"); struct arg_int *MinLen=arg_int0("l", "MinLen", "<int>","minimum accepted length"); struct arg_int *MaxLen=arg_int0("L", "MaxLen", "<int>","maximum accepted length"); struct arg_end *end = arg_end(20); void *argtable[] = {help,version,FileLogLevel,ScreenLogLevel,LogFile, ProcMode,RefFile,FilterRefIDFile,RelFile,Rsltfile, MinLen,MaxLen, 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 ", gszProcName); 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 %d.%2.2d",gszProcName,cProgVer/100,cProgVer%100); exit(1); } if (!argerrors) { iScreenLogLevel = ScreenLogLevel->count ? ScreenLogLevel->ival[0] : eDLInfo; if(iScreenLogLevel < eDLNone || iScreenLogLevel > eDLDebug) { printf("\nError: ScreenLogLevel '-S%d' specified outside of range %d..%d",iScreenLogLevel,eDLNone,eDLDebug); exit(1); } if(FileLogLevel->count && !LogFile->count) { printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]); exit(1); } 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] : eProcModeStandard; if(iProcMode < eProcModeStandard || iProcMode > eProcModeScore) { printf("\nError: Requested processing mode '-x%d' not supported",iProcMode); exit(1); } iMinLen = MinLen->count ? MinLen->ival[0] : 0; if(iMinLen < 0) { printf("\nError: Requested minimum length '-l%d' is negative",iMinLen); exit(1); } iMaxLen = MaxLen->count ? MaxLen->ival[0] : 1000000000; if(iMaxLen < iMinLen) { printf("\nError: Requested maximum ength '-l%d' must be >= minimum %d",iMaxLen,iMinLen); exit(1); } strcpy(szRefFile,RefFile->filename[0]); strcpy(szRelFile,RelFile->filename[0]); strcpy(szRsltfile,Rsltfile->filename[0]); if(FilterRefIDFile->count) { strncpy(szFilterRefIDFile,FilterRefIDFile->filename[0],sizeof(szFilterRefIDFile)); szFilterRefIDFile[sizeof(szFilterRefIDFile)-1] = '\0'; } else szFilterRefIDFile[0] = '\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: %d.%2.2d Processing parameters:",cProgVer/100,cProgVer%100); switch(iProcMode) { case eProcModeStandard: gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode: Identity = Match/(Match+Mismatch)"); break; case eProcModeIdentity: gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode: Identity = Match/(CoreLength)"); break; case eProcModeAligned: gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode: Aligned = (Match+Mismatch)/CoreLength"); break; case eProcModeScore: gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode: score"); break; } gDiagnostics.DiagOutMsgOnly(eDLInfo,"reference csv file to process: '%s'",szRefFile); gDiagnostics.DiagOutMsgOnly(eDLInfo,"relative csv file(s) to processs: '%s'",szRelFile); gDiagnostics.DiagOutMsgOnly(eDLInfo,"results file to generate: '%s'",szRsltfile); if(szFilterRefIDFile[0]) gDiagnostics.DiagOutMsgOnly(eDLInfo,"Exclude any RefIDs in this filter file: '%s'",szFilterRefIDFile); gDiagnostics.DiagOutMsgOnly(eDLInfo,"minimum length: %d",iMinLen); gDiagnostics.DiagOutMsgOnly(eDLInfo,"maximum length: %d",iMaxLen); gStopWatch.Start(); #ifdef _WIN32 SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); #endif Rslt = Process((etProcMode)iProcMode, // processing mode 0: default szRefFile, // reference csv file to process szFilterRefIDFile, // exclude any RefIDs in this filter file szRelFile, // relative csv file(s) to processs szRsltfile, // results file to generate iMinLen, // minimum accepted ref length iMaxLen); // maximum accepted ref length gStopWatch.Stop(); Rslt = Rslt < 0 ? 1 : 0; gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit Code: %d Total processing time: %s",Rslt,gStopWatch.Read()); exit(Rslt); } else { arg_print_errors(stdout,end,gszProcName); arg_print_syntax(stdout,argtable,"\nend of help\n"); exit(1); } return 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); } }
/** * @brief Parse command line parameters. Will exit if help/usage etc * are called or or call Log(&rLog, LOG_FATAL, ) if an error was detected. * * @param[out] user_opts * User parameter struct, with defaults already set. * @param[in] argc * mains argc * @param[in] argv * mains argv * */ void ParseCommandLine(cmdline_opts_t *user_opts, int argc, char **argv) { /* argtable command line parsing: * see * http://argtable.sourceforge.net/doc/argtable2-intro.html * * basic structure is: arg_xxxN: * xxx can be int, lit, db1, str, rex, file or date * If N = 0, arguments may appear zero-or-once; N = 1 means * exactly once, N = n means up to maxcount times * * * @note: changes here, might also affect main.cpp:ConvertOldCmdLine() * */ struct arg_rem *rem_seq_input = arg_rem(NULL, "\nSequence Input:"); struct arg_file *opt_seqin = arg_file0("i", "in,infile", "{<file>,-}", "Multiple sequence input file (- for stdin)"); struct arg_file *opt_hmm_in = arg_filen(NULL, "hmm-in", "<file>", /*min*/ 0, /*max*/ 128, "HMM input files"); struct arg_lit *opt_dealign = arg_lit0(NULL, "dealign", "Dealign input sequences"); struct arg_file *opt_profile1 = arg_file0(NULL, "profile1,p1", "<file>", "Pre-aligned multiple sequence file (aligned columns will be kept fix)"); struct arg_file *opt_profile2 = arg_file0(NULL, "profile2,p2", "<file>", "Pre-aligned multiple sequence file (aligned columns will be kept fix)"); struct arg_str *opt_seqtype = arg_str0("t", "seqtype", "{Protein, RNA, DNA}", "Force a sequence type (default: auto)"); /* struct arg_lit *opt_force_protein = arg_lit0(NULL, "protein", "Set sequence type to protein even if Clustal guessed nucleic acid"); */ struct arg_str *opt_infmt = arg_str0(NULL, "infmt", "{a2m=fa[sta],clu[stal],msf,phy[lip],selex,st[ockholm],vie[nna]}", "Forced sequence input file format (default: auto)"); struct arg_rem *rem_guidetree = arg_rem(NULL, "\nClustering:"); struct arg_str *opt_pairdist = arg_str0("p", "pairdist", "{ktuple}", "Pairwise alignment distance measure"); struct arg_file *opt_distmat_in = arg_file0(NULL, "distmat-in", "<file>", "Pairwise distance matrix input file (skips distance computation)"); struct arg_file *opt_distmat_out = arg_file0(NULL, "distmat-out", "<file>", "Pairwise distance matrix output file"); struct arg_file *opt_guidetree_in = arg_file0(NULL, "guidetree-in", "<file>", "Guide tree input file (skips distance computation and guide-tree clustering step)"); struct arg_file *opt_guidetree_out = arg_file0(NULL, "guidetree-out", "<file>", "Guide tree output file"); /* AW: mbed is default since at least R253 struct arg_lit *opt_mbed = arg_lit0(NULL, "mbed", "Fast, Mbed-like clustering for guide-tree calculation"); struct arg_lit *opt_mbed_iter = arg_lit0(NULL, "mbed-iter", "Use Mbed-like clustering also during iteration"); */ /* Note: might be better to use arg_str (mbed=YES/NO) but I don't want to introduce an '=' into pipeline, FS, r250 -> */ struct arg_lit *opt_full = arg_lit0(NULL, "full", "Use full distance matrix for guide-tree calculation (might be slow; mBed is default)"); struct arg_lit *opt_full_iter = arg_lit0(NULL, "full-iter", "Use full distance matrix for guide-tree calculation during iteration (might be slowish; mBed is default)"); struct arg_str *opt_clustering = arg_str0("c", "clustering", "{UPGMA}", "Clustering method for guide tree"); struct arg_rem *rem_aln_output = arg_rem(NULL, "\nAlignment Output:"); struct arg_file *opt_outfile = arg_file0("o", "out,outfile", "{file,-}", "Multiple sequence alignment output file (default: stdout)"); struct arg_str *opt_outfmt = arg_str0(NULL, "outfmt", "{a2m=fa[sta],clu[stal],msf,phy[lip],selex,st[ockholm],vie[nna]}", "MSA output file format (default: fasta)"); struct arg_rem *rem_iteration = arg_rem(NULL, "\nIteration:"); struct arg_str *opt_num_iterations = arg_str0(NULL, "iterations,iter", /* FIXME "{<n>,auto}", "Number of combined guide-tree/HMM iterations"); */ "<n>", "Number of (combined guide-tree/HMM) iterations"); struct arg_int *opt_max_guidetree_iterations = arg_int0(NULL, "max-guidetree-iterations", "<n>", "Maximum number guidetree iterations"); struct arg_int *opt_max_hmm_iterations = arg_int0(NULL, "max-hmm-iterations", "<n>", "Maximum number of HMM iterations"); struct arg_rem *rem_limits = arg_rem(NULL, "\nLimits (will exit early, if exceeded):"); struct arg_int *opt_max_seq = arg_int0(NULL, "maxnumseq", "<n>", "Maximum allowed number of sequences"); struct arg_int *opt_max_seqlen = arg_int0(NULL, "maxseqlen", "<l>", "Maximum allowed sequence length"); struct arg_rem *rem_misc = arg_rem(NULL, "\nMiscellaneous:"); struct arg_lit *opt_autooptions = arg_lit0(NULL, "auto", "Set options automatically (might overwrite some of your options)"); struct arg_int *opt_threads = arg_int0(NULL, "threads", "<n>", "Number of processors to use"); struct arg_file *opt_logfile = arg_file0("l", "log", "<file>", "Log all non-essential output to this file"); struct arg_lit *opt_help = arg_lit0("h", "help", "Print this help and exit"); struct arg_lit *opt_version = arg_lit0(NULL, "version", "Print version information and exit"); struct arg_lit *opt_long_version = arg_lit0(NULL, "long-version", "Print long version information and exit"); struct arg_lit *opt_verbose = arg_litn("v", "verbose", 0, 3, "Verbose output (increases if given multiple times)"); struct arg_lit *opt_force = arg_lit0(NULL, "force", "Force file overwriting"); struct arg_int *opt_macram = arg_int0(NULL, "MAC-RAM", "<n>", /* keep this quiet for the moment, FS r240 -> */ NULL/*"maximum amount of RAM to use for MAC algorithm (in MB)"*/); struct arg_end *opt_end = arg_end(10); /* maximum number of errors * to store */ void *argtable[] = {rem_seq_input, opt_seqin, opt_hmm_in, opt_dealign, opt_profile1, opt_profile2, opt_seqtype, /* opt_force_protein, */ opt_infmt, rem_guidetree, #if 0 /* no other options then default available or not implemented */ opt_pairdist, #endif opt_distmat_in, opt_distmat_out, opt_guidetree_in, opt_guidetree_out, opt_full, /* FS, r250 -> */ opt_full_iter, /* FS, r250 -> */ #if 0 /* no other options then default available */ opt_clustering, #endif rem_aln_output, opt_outfile, opt_outfmt, rem_iteration, opt_num_iterations, opt_max_guidetree_iterations, opt_max_hmm_iterations, rem_limits, opt_max_seq, opt_max_seqlen, rem_misc, opt_autooptions, opt_threads, opt_logfile, opt_help, opt_verbose, opt_version, opt_long_version, opt_force, opt_macram, /* FS, r240 -> r241 */ opt_end}; int nerrors; /* Verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable)) { Log(&rLog, LOG_FATAL, "insufficient memory (for argtable allocation)"); } /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc, argv, argtable); /* Special case: '--help' takes precedence over error reporting */ if (opt_help->count > 0) { printf("%s - %s (%s)\n", PACKAGE_NAME, PACKAGE_VERSION, PACKAGE_CODENAME); printf("\n"); printf("If you like Clustal-Omega please cite:\n%s\n", CITATION); printf("If you don't like Clustal-Omega, please let us know why (and cite us anyway).\n"); /* printf("You can contact reach us under %s\n", PACKAGE_BUGREPORT); */ printf("\n"); printf("Check http://www.clustal.org for more information and updates.\n"); printf("\n"); printf("Usage: %s", basename(argv[0])); arg_print_syntax(stdout,argtable, "\n"); printf("\n"); printf("A typical invocation would be: %s -i my-in-seqs.fa -o my-out-seqs.fa -v\n", basename(argv[0])); printf("See below for a list of all options.\n"); arg_print_glossary(stdout, argtable, " %-25s %s\n"); arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0])); exit(EXIT_SUCCESS); } /* Special case: '--version' takes precedence over error reporting */ if (opt_version->count > 0) { printf("%s\n", PACKAGE_VERSION); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); exit(EXIT_SUCCESS); } /* Special case: '--long-version' takes precedence over error reporting */ if (opt_long_version->count > 0) { char zcLongVersion[1024]; PrintLongVersion(zcLongVersion, sizeof(zcLongVersion)); printf("%s\n", zcLongVersion); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); exit(EXIT_SUCCESS); } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout, opt_end, PACKAGE); fprintf(stderr, "For more information try: %s --help\n", argv[0]); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); exit(EXIT_FAILURE); } /* ------------------------------------------------------------ * * Command line successfully parsed. Now transfer values to * user_opts. While doing so, make sure that given input files * exist and given output files are writable do not exist, or if * they do, should be overwritten. * * No logic checks here! They are done in a different function * * ------------------------------------------------------------*/ /* not part of user_opts because it declared in src/util.h */ if (0 == opt_verbose->count) { rLog.iLogLevelEnabled = LOG_WARN; } else if (1 == opt_verbose->count) { rLog.iLogLevelEnabled = LOG_INFO; } else if (2 == opt_verbose->count) { rLog.iLogLevelEnabled = LOG_VERBOSE; } else if (3 == opt_verbose->count) { rLog.iLogLevelEnabled = LOG_DEBUG; } user_opts->aln_opts.bAutoOptions = opt_autooptions->count; user_opts->bDealignInputSeqs = opt_dealign->count; /* NOTE: full distance matrix used to be default - there was --mbed flag but no --full flag after r250 decided that mBed should be default - now need --full flag to turn off mBed. wanted to retain mBed Boolean, so simply added --full flag. if both flags set (erroneously) want --mbed to overwrite --full, therefore do --full 1st, the --mbed, FS, r250 */ if (opt_full->count){ user_opts->aln_opts.bUseMbed = FALSE; } if (opt_full_iter->count){ user_opts->aln_opts.bUseMbedForIteration = FALSE; } user_opts->bForceFileOverwrite = opt_force->count; /* log-file */ if (opt_logfile->count > 0) { user_opts->pcLogFile = CkStrdup(opt_logfile->filename[0]); /* warn if already exists or not writable */ if (FileExists(user_opts->pcLogFile) && ! user_opts->bForceFileOverwrite) { Log(&rLog, LOG_FATAL, "%s '%s'. %s", "Cowardly refusing to overwrite already existing file", user_opts->pcLogFile, "Use --force to force overwriting."); } if (! FileIsWritable(user_opts->pcLogFile)) { Log(&rLog, LOG_FATAL, "Sorry, I do not have permission to write to file '%s'.", user_opts->pcLogFile); } } /* normal sequence input (no profile) */ if (opt_seqin->count > 0) { user_opts->pcSeqInfile = CkStrdup(opt_seqin->filename[0]); } /* Input limitations */ /* maximum number of sequences */ if (opt_max_seq->count > 0) { user_opts->iMaxNumSeq = opt_max_seq->ival[0]; } /* maximum sequence length */ if (opt_max_seqlen->count > 0) { user_opts->iMaxSeqLen = opt_max_seqlen->ival[0]; } /* Output format */ if (opt_infmt->count > 0) { /* avoid gcc warning about discarded qualifier */ char *tmp = (char *)opt_infmt->sval[0]; user_opts->iSeqInFormat = String2SeqfileFormat(tmp); } else { user_opts->iSeqInFormat = SQFILE_UNKNOWN; } /* Sequence type */ if (opt_seqtype->count > 0) { if (STR_NC_EQ(opt_seqtype->sval[0], "protein")) { user_opts->iSeqType = SEQTYPE_PROTEIN; } else if (STR_NC_EQ(opt_seqtype->sval[0], "rna")) { user_opts->iSeqType = SEQTYPE_RNA; } else if (STR_NC_EQ(opt_seqtype->sval[0], "dna")) { user_opts->iSeqType = SEQTYPE_DNA; } else { Log(&rLog, LOG_FATAL, "Unknown sequence type '%s'", opt_seqtype->sval[0]); } } /* if (opt_force_protein->count > 0) { user_opts->iSeqType = SEQTYPE_PROTEIN; } */ /* Profile input */ if (opt_profile1->count > 0) { user_opts->pcProfile1Infile = CkStrdup(opt_profile1->filename[0]); if (! FileExists(user_opts->pcProfile1Infile)) { Log(&rLog, LOG_FATAL, "File '%s' does not exist.", user_opts->pcProfile1Infile); } } if (opt_profile2->count > 0) { user_opts->pcProfile2Infile = CkStrdup(opt_profile2->filename[0]); if (! FileExists(user_opts->pcProfile2Infile)) { Log(&rLog, LOG_FATAL, "File '%s' does not exist.", user_opts->pcProfile2Infile); } } /* HMM input */ user_opts->aln_opts.iHMMInputFiles = 0; user_opts->aln_opts.ppcHMMInput = NULL; if (opt_hmm_in->count>0) { int iAux; user_opts->aln_opts.iHMMInputFiles = opt_hmm_in->count; user_opts->aln_opts.ppcHMMInput = (char **) CKMALLOC( user_opts->aln_opts.iHMMInputFiles * sizeof(char*)); for (iAux=0; iAux<opt_hmm_in->count; iAux++) { user_opts->aln_opts.ppcHMMInput[iAux] = CkStrdup(opt_hmm_in->filename[iAux]); if (! FileExists(user_opts->aln_opts.ppcHMMInput[iAux])) { Log(&rLog, LOG_FATAL, "File '%s' does not exist.", user_opts->aln_opts.ppcHMMInput[iAux]); } } } /* Pair distance method */ if (opt_pairdist->count > 0) { if (STR_NC_EQ(opt_pairdist->sval[0], "ktuple")) { user_opts->aln_opts.iPairDistType = PAIRDIST_KTUPLE; } else { Log(&rLog, LOG_FATAL, "Unknown pairdist method '%s'", opt_pairdist->sval[0]); } } /* Distance matrix input */ if (opt_distmat_in->count > 0) { user_opts->aln_opts.pcDistmatInfile = CkStrdup(opt_distmat_in->filename[0]); if (! FileExists(user_opts->aln_opts.pcDistmatInfile)) { Log(&rLog, LOG_FATAL, "File '%s' does not exist.", user_opts->aln_opts.pcDistmatInfile); } } /* Distance matrix output */ if (opt_distmat_out->count > 0) { user_opts->aln_opts.pcDistmatOutfile = CkStrdup(opt_distmat_out->filename[0]); /* warn if already exists or not writable */ if (FileExists(user_opts->aln_opts.pcDistmatOutfile) && ! user_opts->bForceFileOverwrite) { Log(&rLog, LOG_FATAL, "%s '%s'. %s", "Cowardly refusing to overwrite already existing file", user_opts->aln_opts.pcDistmatOutfile, "Use --force to force overwriting."); } if (! FileIsWritable(user_opts->aln_opts.pcDistmatOutfile)) { Log(&rLog, LOG_FATAL, "Sorry, I do not have permission to write to file '%s'.", user_opts->aln_opts.pcDistmatOutfile); } } /* Clustering * */ if (opt_clustering->count > 0) { if (STR_NC_EQ(opt_clustering->sval[0], "upgma")) { user_opts->aln_opts.iClusteringType = CLUSTERING_UPGMA; } else { Log(&rLog, LOG_FATAL, "Unknown guide-tree clustering method '%s'", opt_clustering->sval[0]); } } /* Guidetree input */ if (opt_guidetree_in->count > 0) { user_opts->aln_opts.pcGuidetreeInfile = CkStrdup(opt_guidetree_in->filename[0]); if (! FileExists(user_opts->aln_opts.pcGuidetreeInfile)) { Log(&rLog, LOG_FATAL, "File '%s' does not exist.", user_opts->aln_opts.pcGuidetreeInfile); } } /* Guidetree output */ if (opt_guidetree_out->count > 0) { user_opts->aln_opts.pcGuidetreeOutfile = CkStrdup(opt_guidetree_out->filename[0]); /* warn if already exists or not writable */ if (FileExists(user_opts->aln_opts.pcGuidetreeOutfile) && ! user_opts->bForceFileOverwrite) { Log(&rLog, LOG_FATAL, "%s '%s'. %s", "Cowardly refusing to overwrite already existing file", user_opts->aln_opts.pcGuidetreeOutfile, "Use --force to force overwriting."); } if (! FileIsWritable(user_opts->aln_opts.pcGuidetreeOutfile)) { Log(&rLog, LOG_FATAL, "Sorry, I do not have permission to write to file '%s'.", user_opts->aln_opts.pcGuidetreeOutfile); } } /* max guidetree iterations */ if (opt_max_guidetree_iterations->count > 0) { user_opts->aln_opts.iMaxGuidetreeIterations = opt_max_guidetree_iterations->ival[0]; } /* max guidetree iterations */ if (opt_max_hmm_iterations->count > 0) { user_opts->aln_opts.iMaxHMMIterations = opt_max_hmm_iterations->ival[0]; } /* number of iterations */ if (opt_num_iterations->count > 0) { if (STR_NC_EQ(opt_num_iterations->sval[0], "auto")) { Log(&rLog, LOG_FATAL, "Automatic iteration not supported at the moment."); user_opts->aln_opts.bIterationsAuto = TRUE; } else { int iAux; user_opts->aln_opts.bIterationsAuto = FALSE; for (iAux=0; iAux<(int)strlen(opt_num_iterations->sval[0]); iAux++) { if (! isdigit(opt_num_iterations->sval[0][iAux])) { Log(&rLog, LOG_FATAL, "Couldn't iteration parameter: %s", opt_num_iterations->sval[0]); } } user_opts->aln_opts.iNumIterations = atoi(opt_num_iterations->sval[0]); } } /* Alignment output */ if (opt_outfile->count > 0) { user_opts->pcAlnOutfile = CkStrdup(opt_outfile->filename[0]); /* warn if already exists or not writable */ if (FileExists(user_opts->pcAlnOutfile) && ! user_opts->bForceFileOverwrite) { Log(&rLog, LOG_FATAL, "%s '%s'. %s", "Cowardly refusing to overwrite already existing file", user_opts->pcAlnOutfile, "Use --force to force overwriting."); } if (! FileIsWritable(user_opts->pcAlnOutfile)) { Log(&rLog, LOG_FATAL, "Sorry, I do not have permission to write to file '%s'.", user_opts->pcAlnOutfile); } } /* Output format */ if (opt_outfmt->count > 0) { /* avoid gcc warning about discarded qualifier */ char *tmp = (char *)opt_outfmt->sval[0]; user_opts->iAlnOutFormat = String2SeqfileFormat(tmp); if (SQFILE_UNKNOWN == user_opts->iAlnOutFormat) { Log(&rLog, LOG_FATAL, "Unknown output format '%s'", opt_outfmt->sval[0]); } } /* Number of threads */ #ifdef HAVE_OPENMP if (opt_threads->count > 0) { if (opt_threads->ival[0] <= 0) { Log(&rLog, LOG_FATAL, "Changing number of threads to %d doesn't make sense.", opt_threads->ival[0]); } user_opts->iThreads = opt_threads->ival[0]; } #else if (opt_threads->count > 0) { if (opt_threads->ival[0] > 1) { Log(&rLog, LOG_FATAL, "Cannot change number of threads to %d. %s was build without OpenMP support.", opt_threads->ival[0], PACKAGE_NAME); } } #endif /* max MAC RAM (maximum amount of RAM set aside for MAC algorithm) */ if (opt_macram->count > 0) { /* FS, r240 -> r241 */ user_opts->aln_opts.rHhalignPara.iMacRamMB = opt_macram->ival[0]; } arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); UserOptsLogicCheck(user_opts); return; }
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; }
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; }