Example #1
0
bool file_utils::split_path(const char *p, dynamic_string *pDrive, dynamic_string *pDir, dynamic_string *pFilename, dynamic_string *pExt)
{
    VOGL_ASSERT(p);

#if defined(PLATFORM_WINDOWS)
    char drive_buf[_MAX_DRIVE];
    char dir_buf[_MAX_DIR];
    char fname_buf[_MAX_FNAME];
    char ext_buf[_MAX_EXT];

#if defined(COMPILER_MSVC)
    // Compiling with MSVC
    errno_t error = _splitpath_s(p,
                                 pDrive ? drive_buf : NULL, pDrive ? _MAX_DRIVE : 0,
                                 pDir ? dir_buf : NULL, pDir ? _MAX_DIR : 0,
                                 pFilename ? fname_buf : NULL, pFilename ? _MAX_FNAME : 0,
                                 pExt ? ext_buf : NULL, pExt ? _MAX_EXT : 0);
    if (error != 0)
        return false;
#elif defined(COMPILER_MINGW)
    // Compiling with MinGW
    _splitpath(p,
               pDrive ? drive_buf : NULL,
               pDir ? dir_buf : NULL,
               pFilename ? fname_buf : NULL,
               pExt ? ext_buf : NULL);
#else
#error "Need to provide splitpath functionality for this compiler / platform combo."
#endif

    if (pDrive)
        *pDrive = drive_buf;
    if (pDir)
        *pDir = dir_buf;
    if (pFilename)
        *pFilename = fname_buf;
    if (pExt)
        *pExt = ext_buf;
#else // !PLATFORM_WINDOWS
    char dirtmp[1024];
    char nametmp[1024];
    strcpy_safe(dirtmp, sizeof(dirtmp), p);
    strcpy_safe(nametmp, sizeof(nametmp), p);

    if (pDrive)
        pDrive->clear();

    const char *pDirName = dirname(dirtmp);
    if (!pDirName)
        return false;

    if (pDir)
    {
        pDir->set(pDirName);
        if ((!pDir->is_empty()) && (pDir->back() != '/'))
            pDir->append_char('/');
    }

    const char *pBaseName = basename(nametmp);
    if (!pBaseName)
        return false;

    if (pFilename)
    {
        pFilename->set(pBaseName);
        remove_extension(*pFilename);
    }

    if (pExt)
    {
        pExt->set(pBaseName);
        get_extension(*pExt);
        if (pExt->get_len())
            *pExt = "." + *pExt;
    }
#endif // #if defined(PLATFORM_WINDOWS)

    return true;
}
Example #2
0
/*  �����������������������������������������������������������������������ͼ */
PRIVATE void    parse_parms (int argc, char *argv[])
{
	LONG     i;
#if PC_WATCOM
	char    ci_drive[5], ci_dir[60], ci_fname[20], ci_ext[10], *pp;
	BOOL    have_name;
#endif

		/****/

#if PC_WATCOM
	wild_card = (strchr(argv[1], '*') != NULL  ||
							 strchr(argv[1], '?') != NULL);
	_fullpath(src_name, argv[1], sizeof(src_name));   strupr(src_name);
	_splitpath(src_name, ci_drive, ci_dir, ci_fname, ci_ext);
	if (ci_ext[0] == '\0')  strcpy(ci_ext, ".PIC");
	_makepath(src_name, ci_drive, ci_dir, ci_fname, ci_ext);
	_makepath(src_path, ci_drive, ci_dir, "", "");
	des_ext = ".JPG";
#else
	check(argc >= 3, "need output filename. ");
	check(argv[1][0] != '-' && argv[1][0] != '/',"need input filename");
	check(argv[2][0] != '-' && argv[2][0] != '/',"need output filename");
	src_name = argv[1];
	des_name = argv[2];
#endif

	pad = FALSE;
	keep_colors = FALSE;
	orient = 0;
	skip_copyright = FALSE;
	get_buff_size = DEFAULT_GET_BUFF_SIZE;
	put_buff_size = DEFAULT_PUT_BUFF_SIZE;
	num_loops = 1;
	lum_opt = 24;
	chrom_opt = 30;
	requant = 0;
	QTableName[0] = '\0';
#if PIC2_OUT
	pic2_out = FALSE;
#endif
#if ELS_CODER_OUT
	els_coder_out = FALSE;
#endif
	crop_x = crop_y = crop_w = crop_h = 0;
	crop_flg = FALSE;
	memset(key, 0, sizeof(key));
	apps_to_keep = 0;
	remove_comments = 0;
	src_name_join = NULL;
	join_left_right = FALSE;
	join_insert = FALSE;
	join_second_on_top_left = FALSE;
	join_subsampling_from_second = FALSE;
	join_quantization_from_second = FALSE;
	join_use_requested_quantization = FALSE;
	regions = FALSE;
	insert_transparency_lum = insert_transparency_chrom = 0;

	for (i = 2;  i < argc;  ++i)
	{
		if (argv[i][0] == '-'  ||  argv[i][0] == '/')
		{
			switch (toupper(argv[i][1]))
			{
#if PIC2_OUT
				case '2' :  pic2_out = TRUE;
							des_ext = ".PIC";
							break;
#endif
#if ELS_CODER_OUT
				case 'W' :  els_coder_out = TRUE;
							break;
#endif
				case 'K' :
						strncpy(key, argv[i]+2, 8);
						break;
								case 'X' :
						strncpy(outputkey, argv[i]+2, 8);
												break;
				case 'C' :
						keep_colors = TRUE;
						break;
				case 'P' :
						pad = TRUE;
						break;
				case 'E' :
						get_buff_size = atoi(argv[i]+2);
						check(get_buff_size >= 128, "Bad input buff size");
						break;
				case 'F' :
						put_buff_size = atoi(argv[i]+2);
						check(put_buff_size >= 128, "Bad output buff size");
						break;
				case 'T' :
						num_loops = atoi(argv[i]+2);
						check(num_loops > 0 && num_loops <= 1000, "Bad num loops");
						break;
				case 'R' :
						orient = atoi(argv[i]+2);
						check(orient >= 0 && orient <= 7, "Bad orientation");
						break;
				case 'Q' :  strcpy(QTableName, argv[i]+2);
							break;
				case 'L' :  lum_opt = atoi(argv[i]+2);
							break;
				case 'M' :  chrom_opt = atoi(argv[i]+2);
							break;
#if REQUANT
				case 'B' :
							requant = atoi(argv[i]+2);
							if(requant == 0)
								requant = 1;
							break;
#endif
				case 'A' :
							apps_to_keep = strtoul(argv[i]+2, NULL,0);
							break;
				case 'N' :
							remove_comments |= 1;
							break;
				case 'S' :
							remove_comments |= 2;
							break;
				case 'V' :
						crop_flg = TRUE;
						switch (toupper(argv[i][2]))
						{
							case 'X' :
									crop_x = atoi(argv[i]+3);
									break;
							case 'Y' :
									crop_y = atoi(argv[i]+3);
									break;
							case 'W' :
									crop_w = atoi(argv[i]+3);
									break;
							case 'H' :
									crop_h = atoi(argv[i]+3);
									break;
							default :
									check(FALSE, "Unknown crop option %s", argv[i]);
									break;
						}
						break;
				case 'J' :
						switch (toupper(argv[i][2]))
						{
							case 'I' :
									src_name_join = argv[i]+3;
									break;
							case 'L' :
									join_left_right = TRUE;
									break;
							case 'N' :
									join_insert = TRUE;
									break;
							case 'T' :
									switch (toupper(argv[i][3]))
									{
											case 'L' :
													insert_transparency_lum = atoi(argv[i]+4);
													break;
											case 'C' :
													insert_transparency_chrom = atoi(argv[i]+4);
													break;
											default :
													check(FALSE, "Unknown join option %s", argv[i]);
													break;
									}
									break;
							case 'Q' :
									join_use_requested_quantization = TRUE;
									break;
							case '2' :
									switch (toupper(argv[i][3]))
									{
											case 'T' :
													join_second_on_top_left = TRUE;
													break;
											case 'Q' :
													join_quantization_from_second = TRUE;
													break;
											case 'S' :
													join_subsampling_from_second = TRUE;
													break;
											default :
													check(FALSE, "Unknown join option %s", argv[i]);
													break;
									}
									break;
							default :
									check(FALSE, "Unknown join option %s", argv[i]);
									break;
						}
						break;
				case 'G' :
						regions = TRUE;
						break;
				case '!' :
						skip_copyright = TRUE;
						break;
				default  :
						check(FALSE, "Unknown option %s", argv[i]);
						break;
			}
		}
	}
	if(join_insert || regions)
		crop_flg = FALSE;
#if PC_WATCOM
	have_name = (argc > 2  &&  argv[2][0] != '-'  &&  argv[2][0] != '/');
	if (have_name) {
					_fullpath(des_name, argv[2], 100);   strupr(des_name);
	} else {
		strcpy(des_name, src_name);
	}
	if (wild_card) {
			if (have_name) {
					pp = des_name + strlen(des_name);
					if (pp[-1] != '\\'  &&  pp[-1] != ':')  *((WORD *) pp) = 0x005C;
			}
			_splitpath(des_name, ci_drive, ci_dir, ci_fname, ci_ext);
			_makepath(des_path, ci_drive, ci_dir, "", "");
	} else {
			pp = strchr(des_name, '.');
			if (have_name) {
					if (pp == NULL)  strcat(des_name, des_ext);
			} else {
					strcpy(pp, des_ext);
			}
	}
#endif
}
Example #3
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int 
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

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


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

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

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

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

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

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

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

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

	bSkipFirst = SkipFirst->count ? true : false;

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

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

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

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

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

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

	gStopWatch.Stop();
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	printf("\n%s csv2stats, Version %s\n",gszProcName,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
}
/*-------------------------------------------------------------------------*/
VOID ViewHeader( CHAR *file )
{
    INT          i, m;
    CHAR         buf[64];
    static CHAR  str[140], tmp[140];

    _splitpath( file, NULL, NULL, fname, ext );

    if( pktcount )
        sprintf( str, "%u - %u  (%s%s)", pktNumber + 1, pktcount, fname, ext );
    else
        sprintf( str,  "1 - 1  (%s%s)", fname, ext );

    i = strlen( str );
    WSetCurColor( wmain, C_TEXT );
    WSetXY      ( wmain,  6, 0 );
    WPuts       ( wmain, str );
    memset      ( str, ' ', 30 - i ); str[ 30 - i ] = 0;
    WSetXY      ( wmain,  6 + i, 0 );
    WPuts       ( wmain, str );
    
    if(( m = maxXmain - 32 ) > 64 )
        m = 64;

    strncpy( tmp, Current -> from, m - 7 ); WSetXY( wmain, 6, 1 );
    sprintf( str,  "%-*.*s", m - 7, m - 7, tmp ); WPutstr( wmain, str );
    
    strncpy( tmp, Current -> to, m - 7 ); WSetXY( wmain, 6, 2 );
    sprintf( str,  "%-*.*s", m - 7, m - 7, tmp ); WPutstr( wmain, str );

    strncpy( tmp, Current -> subj, maxXsubj - 6 ); WSetXY( wmain, 6, 3 );
    sprintf( str,  "%-*.*s", maxXsubj - 6, maxXsubj - 6, tmp ); WPutstr( wmain, str );

    if( Current -> area )
    {
        strcpy ( str, " " );
        strncat( str, Current -> area, 60 );
        strcat ( str, " " );
    }
    else
        strcpy( str, " Netmail " );

    i = strlen( str );
    WPutbs ( wmain, 0,  6, WGetSchColor( wmain, C_MORE ), str );
    memset ( str, 'Ä', 60 - i ); str[ 60 - i ] = 0;
    WPutbs ( wmain, 0, 6 + i, WGetSchColor( wmain, C_BORDER ), str );

    if( BadPkt )
    {
        WPutbs( wmain, 0, 2, WGetSchColor( wmain, C_BORDER ), "´ Ã" );
        WPutbs( wmain, 0, 3, WGetSchColor( wmain, C_MORE   ),  "b"  );
    }
    else
        WPutbs( wmain, 0, 2, WGetSchColor( wmain, C_BORDER ), "ÄÄÄ" );
    
    if( ReadOnly )
    {
        WPutbs( wmain, 0, maxXmain - 4, WGetSchColor( wmain, C_BORDER ),  "´  Ã" );
        WPutbs( wmain, 0, maxXmain - 3, WGetSchColor( wmain, C_MORE   ),   "ro" );
    }
    else
        WPutbs( wmain, 0, maxXmain - 4, WGetSchColor( wmain, C_BORDER ), "ÄÄÄÄ" );

    WPrints ( wmain, m + 11, 0, Current -> date );

    strncpy( str, FidoAddr2Str( &Current -> AddrFrom, buf ), maxXmain - m );
    WSetXY ( wmain, m, 1 );
    WPrintf( wmain, "%-*.*s", maxXmain - m, maxXmain - m, str );

    if( Current -> area )
        WSetCurColor( wmain, C_HIDE );

    strncpy( str, FidoAddr2Str( &Current -> AddrTo, buf ), maxXmain - m );
    WSetXY( wmain, m, 2 );
    WPrintf( wmain, "%-*.*s", maxXmain - m, maxXmain - m, str );

#ifndef _LITE_
    ViewSelected();
#endif
    ViewSize();
    ViewAttr();
}
Example #5
0
//=====================================================================
int dcl_define_logical(PARAM_T *p,PARAM_T *q)
{
    char    token[MAX_TOKEN];
    char    value[LOGICAL_MAX_VALUE];
    char    name[LOGICAL_MAX_NAME];
    char    dosfile[_MAX_PATH];
    char    drive[_MAX_DRIVE];
    char    dir[_MAX_DIR];
    char    fname[_MAX_FNAME];
    char    ext[_MAX_EXT];
    int     i       = 0;
    int     log     = 1;
    int     retcod  = DCL_OK;

    *token = 0; *value = 0; *name = 0;

    for (i = 0; q[i].tag; i++) {
        if (q[i].flag & PRESENT) 
            switch (q[i].tag) {
            case 6:                                 /* /LOG     */
                log = TRUE;
                break;
            case 7:                                 /* /NOLOG   */
                log = FALSE;
                break;
            default:
                (void)dcl_printf(dcl[D].SYS_OUTPUT,"Invalid command qualifier\n");
                _SEVERITY = 2;
                _STATUS = 19;
                retcod = DCL_ERROR;
            } /* end switch */
    }   /* end for */

    if (retcod == DCL_OK) {
        dcl_string(p[0].value,name,MAX_TOKEN);
        dcl_string(p[1].value,value,MAX_TOKEN);
        (void)logical_get(name,token);
        retcod = logical_put(name,value,LOG_USER);
        if (log && *token && retcod == 0) {
            (void)dcl_printf(dcl[D].SYS_OUTPUT,"%s superseded\n",name);
        }
        if (strcasecmp(name,"SYS$OUTPUT") == 0) {
            if (dcl[D].SYS_OUTPUT != stdout) {
                //(void)fclose(dcl[D].SYS_OUTPUT);
            }
            if (strcasecmp(value, "tt") == 0) {
                dcl[D].SYS_OUTPUT = stdout;
                strcpy(dcl[D].outname, name);
            }
            else {
            	cvfs_vms_to_dos(name,dosfile,&i);
                _splitpath(dosfile,drive,dir,fname,ext);
                if (strlen(ext) == 0) strcat(dosfile,".lis");
                dcl[D].SYS_OUTPUT = fopen(dosfile,"at");
                if (dcl[D].SYS_OUTPUT == NULL) {
                    dcl[D].SYS_OUTPUT = stdout;
                    strcpy(dcl[D].outname, "SYS$OUTPUT");
                    }
                else {
                    strncpy(dcl[D].outname,dosfile,_MAX_PATH);
                    }
                }
        	}
        }

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

int Rslt;
etFMode FMode;				// format output mode

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

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

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

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

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

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

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

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


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

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




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

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

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

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

	EventPhaseType phase = evt->get_eventPhase();
	if (phase != CAPTURING_PHASE)
	{
		if (type == OLESTR("click"))
		{
			evt->stopPropagation();
			m_query->More();
		}
		else if (type == OLESTR("Activate"))
		{
			evt->stopPropagation();

			IItemSite* itemsite = dynamic_cast<IItemSite*>(evt->get_target());

			SHA1DigestField* sha1 = dynamic_cast<SHA1DigestField*>(itemsite->GetFieldData(4));

			std::string filename = ConvertS2A(dynamic_cast<TextString*>(itemsite->GetFieldUI(0))->get_textContent());
			//LPTSTR ext = PathFindExtension(filename.c_str());
			TCHAR filepart[512];
			TCHAR extpart[512];
			_splitpath(filename.c_str(), NULL, NULL, filepart, extpart);

			ByteStreamWriter* file = NULL;
			int n = 0;
			do
			{
				try
				{
					char modifiedfilename[512];

					if (n > 0)
						strcpy(modifiedfilename, filename.c_str());
					else
						sprintf(modifiedfilename, "%s(%d)%s", filepart, n, extpart);

					file = new ByteStreamWriter(modifiedfilename);
				}
				catch(int e)
				{
					if (e == ERROR_SHARING_VIOLATION)
					{
						n++;	// Try again
					}
					else
					{
						// Any other error, we give up
						break;
					}
				}
			}
			while (file == NULL);

			if (file == NULL)
			{
				MessageBox(NULL, "Couldn't create file", "", MB_OK);
			}
			else
			{
				MessageBeep(-1);
				//m_GnutellaNetwork->pP2P->Download(dynamic_cast<LongLongField*>(itemsite->GetFieldData(1))->m_value, sha1->m_buffer, m_Downloads, file);
			}
		}
	}
}
Example #8
0
void main(int argc, char **argv)
{
	char *server_name = "mayaCommand";
	int  opt;

	char *program = new char[strlen(argv[0]) + 1];
	char *cptr;
	/*
	 * Grab a copy of the program name
	 */
#ifdef _WIN32
		_splitpath (argv[0], NULL, NULL, program, NULL);
#else
	cptr = strrchr(argv[0], '/');
	if (cptr)
	{
		strcpy(program, (cptr + 1));
	}
	else
	{
		strcpy(program, argv[0]);
	}
#endif

#ifdef DEVEL
	while ((opt = getopt(argc, argv, "Dhvi1w:n:")) != -1)
#else /* DEVEL */
	while ((opt = getopt(argc, argv, "hi1w:n:")) != -1)
#endif /* DEVEL */
	{	  
		switch (opt)
		{
		case 'h':
			show_usage++;
			break;

		case 'D':
			debug_mode++;
			break;

		case 'n':
			server_name = optarg;
			break;

		case 'v':
			verbose++;
			break;

		case '1':
			perLine++;
			numPerLine = 1;
			break;

		case 'i':
			interactive++;
			break;

		case 'w':
			perLine++;
			numPerLine = atoi(optarg);
			break;

		case GETOPTHUH:
			show_usage++;
		}
	}

	if (show_usage)
	{
		fprintf(stderr, "Usage:\n");
#ifdef DEVEL
		fprintf(stderr, "    %s [-Dvhi1] [-w num ] [-n name]\n", argv[0]);
#else /* DEVEL */
		fprintf(stderr, "    %s [-hi1] [-w num ] [-n name]\n", argv[0]);
#endif /* DEVEL */
		fprintf(stderr, "\n");
		fprintf(stderr, "        -h        Print this help message\n");
#ifdef DEVEL
		fprintf(stderr, "        -D        Set the debug flag\n");
		fprintf(stderr, "        -v        Set the vebose flag\n");
#endif /* DEVEL */
		fprintf(stderr, "        -n name   The server's UNIX socket name\n");
		fprintf(stderr, "        -1 	   Format the results one field per line\n");
		fprintf(stderr, "        -w num	   Format the results num fields per line\n");
		fprintf(stderr, "        -i 	   Interactive. Prompt each line with the server name.\n");

		fprintf(stderr, "\n");

		exit(1);
	}

	char command[5000] = {'\0' };

	int i;

    for ( i = optind ; i < argc; i++) {
		strcat(command,argv[i]);
		strcat(command," ");
	}
	if ( strlen(command) == 0 )
		readStdIn = 1;

	if ( verbose ) {
		fprintf(stderr,"// debug_mode  = %d\n", debug_mode);
		fprintf(stderr,"// readStdIn   = %d\n", readStdIn);
		fprintf(stderr,"// perLine     = %d\n", perLine);
		fprintf(stderr,"// numPerLine  = %d\n", numPerLine);
		fprintf(stderr,"// interactive = %d\n", interactive);
		fprintf(stderr,"// verbose     = %d\n", verbose);
	}

	if ( verbose ) {
		fprintf(stderr,"// %s: contacting server %s\n",program, server_name);
		fflush(stderr);
	}


	
	// Connect to the new server
	int fd = CapTcpOpen(server_name);

	if ( fd < 0 ) {
		fprintf(stderr,"// %s: couldn't connect to server %s\n"
				,program, server_name);
		exit(-1);
	} else if ( verbose ) {
		fprintf(stderr,"// %s: connected to server %s\n",program, server_name);
	}
		

	do {
		if ( readStdIn ) {
			if ( interactive ) {
				printf("%s %% ", server_name);
				fflush(stdout);
			}

			if ( NULL == fgets (command, 5000, stdin) ) 
				break;
		}

		if ( verbose )
			fprintf(stderr,"// %s: sending command %s\n",program, command);

		send(fd,command,strlen(command),0);

		if ( verbose )
			fprintf(stderr,"// %s: awaiting reply...",program);

		char reply[5000];
		int red = recv(fd,reply,4096,0);

		if ( verbose )
			fprintf(stderr,"// %s: recieved %d bytes\n",program,red);

		if ( red > 0)
		{
			if ( perLine ) {
				char *tabby = reply;
				int   count = 0;
				// replace \t with \n in reply
				while ( tabby = strchr ( tabby, '\t' ) ) {
					if ( (++count % numPerLine) == 0 )
						*tabby = '\n';
					tabby++;
				}
			}


			printf("%s",reply);
		}
		else {
			if ( verbose )
				printf("READ FAILED\n");
			break;
		}
	} while (readStdIn);

	if ( verbose )
		fprintf(stderr,"// %s: closing connection.\n",program);

	closesocket(fd);
}
Example #9
0
/*
 * AccLoadProg
 *
 * To load a app, we do the following:
 *
 *  Case 1: debugging an existing task
 *      - Find its current CS:IP.
 *      - Plant a breakpoint at the current CS:IP
 *
 *  Case 2: starting a task from scratch
 *      - Look up the start address from the .EXE
 *      - WinExec the app
 *      - Wait for the STARTASK notification for the app
 *      - Plant a breakpoint at its start address
 *
 *  - Wait for the app to hit the breakpoint
 *  - Check if the app is a 32-bit app (look for "DEADBEEF" in code seg).
 *     If it is a 32-bit app:
 *      - Flip the "DEADBEEF" to "BEEFDEAD".  If the extender see's the
 *        "BEEFDEAD", it executes a breakpoint right before it jumps to
 *        the 32-bit code
 *      - Let the app run until a breakpoint is hit
 *      - Trace one instruction. This leaves you at the first instruction
 *        of the 32-bit code
 */
unsigned ReqProg_load( void )
{
    char                exe_name[_MAX_PATH];
    char                drive[_MAX_DRIVE],directory[_MAX_DIR];
    char                buff[256];
    lm_parms            loadp;
    word_struct         cmdshow;
    char                *parm;
    char                *src;
    char                *dst;
    char                ch;
    unsigned            a,b;
    private_msg         pmsg;
    char                sig[sizeof(DWORD)];
    HTASK               tid;
    DWORD               csip;
    prog_load_req       *acc;
    prog_load_ret       *ret;
    char                *end;

    acc = GetInPtr( 0 );
    ret = GetOutPtr( 0 );
    ret->flags = LD_FLAG_IS_PROT | LD_FLAG_HAVE_RUNTIME_DLLS;
    parm = GetInPtr( sizeof( *acc ) );

    /*
     * reset flags
     */
    OutPos = 0;
    WasStarted = FALSE;
    LoadingDebugee = TRUE;
    Debugging32BitApp = FALSE;
    AddAllCurrentModules();

    /*
     * check for task id
     */
    tid = 0;
    src = parm;
    if( *src == '#' ) {
        src++;
        tid = (HTASK)strtol( src, NULL, 16 );
    } else {
        while( *src != 0 ) {
            if( !isdigit( *src ) ) {
                break;
            }
            src++;
        }
        if( *src == 0 && src != parm ) {
            tid = (HTASK)atoi( parm );
        }
    }
    if( tid != 0 ) {
        csip = GetRealCSIP( tid, &DebugeeModule );
        if( csip == 0 ) {
            tid = 0;
        } else {
            DebugeeTask = tid;
            StopNewTask.loc.segment = FP_SEG( (LPVOID) csip );
            StopNewTask.loc.offset = FP_OFF( (LPVOID) csip );
            ReadMem( StopNewTask.loc.segment, StopNewTask.loc.offset,
                    &StopNewTask.value, 1 );
            ch = 0xcc;
            WriteMem( StopNewTask.loc.segment, StopNewTask.loc.offset, &ch, 1 );
        }
    } else {
        tid = 0;
    }

    /*
     * get the file to execute
     */
    if( tid == 0 ) {
        if( TINY_ERROR( FindFilePath( parm, exe_name, ExtensionList ) ) ) {
            exe_name[0] = 0;
        } else {
            _splitpath( exe_name, drive, directory, NULL, NULL );
            a = tolower( drive[0] ) - 'a' + 1;
            _dos_setdrive( a, &b );
            directory[ strlen( directory ) - 1 ] = 0;
            chdir( directory );
        }

        /*
         * get the parm list
         */

        src = parm;
        while( *src != 0 )
            ++src;
        ++src;
        end = GetInPtr( GetTotalSize() - 1 );
        dst = &buff[1];
        for( ;; ) {
            if( src > end )
                break;
            ch = *src;
            if( ch == 0 )
                ch = ' ';
            *dst = ch;
            ++dst;
            ++src;
        }
        if( dst > &buff[1] )
            --dst;
        *dst = '\0';
        buff[0] = dst-buff-1;

        /*
         * get starting point in task
         */
        if( !GetStartAddress( exe_name, &StopNewTask.loc ) ) {
            Out((OUT_ERR,"Could not get starting address"));
            ret->err = WINERR_NOSTART;
            LoadingDebugee = FALSE;
            return( sizeof( *ret ) );
        }
        StopNewTask.segment_number = StopNewTask.loc.segment;
        Out((OUT_LOAD,"Loading %s, cs:ip = %04x:%04lx", exe_name, StopNewTask.loc.segment,
                            StopNewTask.loc.offset ));

        /*
         * load the task
         */
        loadp.cmdshow = &cmdshow;
        loadp.wEnvSeg = 0;
        loadp.lpCmdLine = (LPSTR) buff;
        loadp.cmdshow->mustbe2 = 2;
        loadp.cmdshow->cmdshow = SW_NORMAL;
        loadp.reserved = 0L;
        DebuggerState = LOADING_DEBUGEE;
        DebugeeInstance = LoadModule( exe_name, (LPVOID) &loadp );
        if( (UINT)DebugeeInstance < 32 ) {
            Out((OUT_ERR,"Debugee did not load %d", DebugeeInstance));
            ret->err = WINERR_NOLOAD;
            LoadingDebugee = FALSE;
            return( sizeof( *ret ) );
        }
        DebuggerWaitForMessage( WAITING_FOR_TASK_LOAD, NULL, RESTART_APP );
    }
    AddDebugeeModule();
    pmsg = DebuggerWaitForMessage( WAITING_FOR_BREAKPOINT, DebugeeTask, RESTART_APP );
    if( pmsg == START_BP_HIT ) {

        ret->err = 0;
        ret->task_id = (unsigned_32)DebugeeTask;

        /*
         * look for 32-bit windows application
         */
        ReadMem( IntResult.CS, SIG_OFF, sig, sizeof( DWORD ) );
        if( !StopOnExtender && (!memcmp( sig, win386sig, 4 ) ||
                !memcmp( sig, win386sig2, 4 )) ) {
            Out((OUT_LOAD,"Is Win32App" ));
            Debugging32BitApp = TRUE;
            /*
             * make sure that WDEBUG.386 is installed
             */
            if( !WDebug386 ) {
                ret->err = WINERR_NODEBUG32; /* Can't debug 32 bit app */
                LoadingDebugee = FALSE;
                return( sizeof( *ret ) );
            }
            ret->flags |= LD_FLAG_IS_32;
            if( tid == 0 ) {
                WriteMem( IntResult.CS, SIG_OFF, win386sig2, sizeof( DWORD ) );
                pmsg = DebuggerWaitForMessage( GOING_TO_32BIT_START,
                                DebugeeTask, RESTART_APP );
                if( pmsg == FAULT_HIT && IntResult.InterruptNumber == INT_3 ) {
                    IntResult.EIP++;
                    SingleStepMode();
                    pmsg = DebuggerWaitForMessage( GOING_TO_32BIT_START,
                                DebugeeTask, RESTART_APP );
                    if( pmsg != FAULT_HIT || IntResult.InterruptNumber != INT_1 ) {
                        Out((OUT_ERR,"Expected INT_1 not found"));
                        ret->err = WINERR_NOINT1;
                    }
                } else {
                    Out((OUT_ERR,"Expected INT_3 not found"));
                    ret->err = WINERR_NOINT3;
                }
            }
        }
        if( tid != 0 ) {
            ret->flags |= LD_FLAG_IS_STARTED;
            WasStarted = TRUE;
        }
    } else {
        Out((OUT_ERR,"Starting breakpoint not found, pmsg=%d", pmsg ));
        ret->err = WINERR_STARTNOTFOUND;
    }
#if 0
    if( DebugeeTask != NULL ) {
        InitASynchHook();
    }
#endif
    LoadingDebugee = FALSE;
    CurrentModule = 1;
    ret->mod_handle = 0;
    return( sizeof( *ret ) );
}
Example #10
0
/*
 * Examine a file's extension to determine what type of file it is.  If the
 * file has no extension, a warning is issued and TYPE_ASSUME_FILE is assumed.
 */
static int file_type( const char *filename )
/******************************************/
{
    char *              newfilename;
    char *              tempfilename;
    char                ext[_MAX_EXT];
    int                 type;

    /*** Strip quotes from filename ***/
    newfilename = DupStrMem( filename );
    if( *newfilename == '"' ) {
        tempfilename = newfilename + 1;                 /* skip leading " */
        tempfilename[ strlen(tempfilename)-1 ] = '\0';  /* smite trailing " */
    } else {
        tempfilename = newfilename;
    }

    _splitpath( tempfilename, NULL, NULL, NULL, ext );
    if( allowC && !stricmp( ext, ".c" ) ) {
        type = TYPE_C_FILE;
    } else if( allowCPP && !stricmp( ext, ".cc" ) ) {
        type = TYPE_CPP_FILE;
    } else if( allowCPP && !stricmp( ext, ".cpp" ) ) {
        type = TYPE_CPP_FILE;
    } else if( allowCPP && !stricmp( ext, ".cxx" ) ) {
        type = TYPE_CPP_FILE;
    } else if( allowCPP && !stricmp( ext, ".odl" ) ) {
        type = TYPE_CPP_FILE;
    } else if( allowCPP && !stricmp( ext, ".idl" ) ) {
        type = TYPE_CPP_FILE;
    } else if( allowDEF && !stricmp( ext, ".def" ) ) {
        type = TYPE_DEF_FILE;
    } else if( allowOBJ && !stricmp( ext, ".obj" ) ) {
        type = TYPE_OBJ_FILE;
    } else if( allowLIB && !stricmp( ext, ".lib" ) ) {
        type = TYPE_LIB_FILE;
    } else if( allowRC && !stricmp( ext, ".rc" ) ) {
        type = TYPE_RC_FILE;
    } else if( allowRES && !stricmp( ext, ".res" ) ) {
        type = TYPE_RES_FILE;
    } else if( allowRBJ && !stricmp( ext, ".rbj" ) ) {
        type = TYPE_RBJ_FILE;
    } else if( allowRS && !stricmp( ext, ".rs" ) ) {
        type = TYPE_RS_FILE;
    } else if( allowEXP && !stricmp( ext, ".exp" ) ) {
        type = TYPE_EXP_FILE;
    } else {
        if( defaultType == TYPE_INVALID_FILE ) {
            Zoinks();
        }
        if( languageToForce == FORCE_NONE ) {
            Warning( "Unrecognized file type '%s' -- %s file assumed",
                     filename, defaultName );
        }
        type = defaultType;
    }
    if( type == TYPE_C_FILE && languageToForce == FORCE_CPP_COMPILE ) {
        type = TYPE_CPP_FILE;
    } else if( type == TYPE_CPP_FILE && languageToForce == FORCE_C_COMPILE ) {
        type = TYPE_C_FILE;
    }
    FreeMem( newfilename );
    return( type );
}
Example #11
0
static std::string sGetProcessPath() {
#if EE_PLATFORM == EE_PLATFORM_MACOSX
	char exe_file[PATH_MAX + 1];
	CFBundleRef mainBundle = CFBundleGetMainBundle();
	if (mainBundle) {
		CFURLRef mainURL = CFBundleCopyBundleURL(mainBundle);

		if (mainURL) {
			int ok = CFURLGetFileSystemRepresentation ( mainURL, (Boolean) true, (UInt8*)exe_file, PATH_MAX );

			if (ok) {
				return std::string(exe_file) + "/";
			}
		}
	}

	return "./";
#elif EE_PLATFORM == EE_PLATFORM_LINUX
	char exe_file[PATH_MAX + 1];
	int size;
	size = readlink("/proc/self/exe", exe_file, PATH_MAX);
	if (size < 0) {
		return "./";
	} else {
		exe_file[size] = '\0';
		return std::string(dirname(exe_file)) + "/";
	}
#elif EE_PLATFORM == EE_PLATFORM_WIN
	#ifdef UNICODE
		// Get path to executable:
		char szDrive[_MAX_DRIVE];
		char szDir[_MAX_DIR];
		char szFilename[_MAX_DIR];
		char szExt[_MAX_DIR];
		std::wstring dllName( _MAX_DIR, 0 );

		GetModuleFileName(0, &dllName[0], _MAX_PATH);

		std::string dllstrName( String( dllName ).ToUtf8() );

		#ifdef EE_COMPILER_MSVC
		_splitpath_s( dllstrName.c_str(), szDrive, _MAX_DRIVE, szDir, _MAX_DIR, szFilename, _MAX_DIR, szExt, _MAX_DIR );
		#else
		_splitpath(szDllName, szDrive, szDir, szFilename, szExt);
		#endif

		return std::string( szDrive ) + std::string( szDir );
	#else
		// Get path to executable:
		TCHAR szDllName[_MAX_PATH];
		TCHAR szDrive[_MAX_DRIVE];
		TCHAR szDir[_MAX_DIR];
		TCHAR szFilename[_MAX_DIR];
		TCHAR szExt[_MAX_DIR];
		GetModuleFileName(0, szDllName, _MAX_PATH);

		#ifdef EE_COMPILER_MSVC
		_splitpath_s(szDllName, szDrive, _MAX_DRIVE, szDir, _MAX_DIR, szFilename, _MAX_DIR, szExt, _MAX_DIR );
		#else
		_splitpath(szDllName, szDrive, szDir, szFilename, szExt);
		#endif

		return std::string(szDrive) + std::string(szDir);
	#endif
#elif EE_PLATFORM == EE_PLATFORM_BSD
	int mib[4];
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PATHNAME;
	mib[3] = -1;
	char buf[1024];
	size_t cb = sizeof(buf);
	sysctl(mib, 4, buf, &cb, NULL, 0);

	return FileSystem::FileRemoveFileName( std::string( buf ) );
#elif EE_PLATFORM == EE_PLATFORM_SOLARIS
	return FileRemoveFileName( std::string( getexecname() ) );
#elif EE_PLATFORM == EE_PLATFORM_HAIKU
	image_info info;
	int32 cookie = 0;

	while ( B_OK == get_next_image_info( 0, &cookie, &info ) ) {
		if ( info.type == B_APP_IMAGE )
			break;
	}

	return FileSystem::FileRemoveFileName( std::string( info.name ) );
#elif EE_PLATFORM == EE_PLATFORM_ANDROID
	if ( NULL != Window::cEngine::instance() && NULL != Window::cEngine::instance()->GetCurrentWindow() )
		return Window::cEngine::instance()->GetCurrentWindow()->GetExternalStoragePath();

	return "/sdcard/";
#else
	#warning Sys::GetProcessPath() not implemented on this platform. ( will return "./" )
	return "./";
#endif
}
Example #12
0
int MEDimport(char * filein, char *  fileout) {

  med_idt fid, gid;
  med_err ret;
  med_int majeur, mineur, release;
  med_bool hdfok=MED_FALSE;
  med_bool medok=MED_FALSE;
  char *_fileout,*tmp=NULL;
  int   _fileoutsize;
  bool  hasfileout=false;
  char *commande;
  med_int nprofil;
  char chemin_profils[MED_TAILLE_PROFILS+1];
  char chemin_liens[MED_TAILLE_LIENS+1];
  char version[9];
  int MAJ_21_22 = 0, MAJ_231_232 = 0, MAJ_236_300 = 0, MAJ_300_310 = 0, MAJ_310_320 = 0 ;
#ifdef PPRO_NT
  char *drive, *dir, *ext;
#endif
  unsigned char reponse='o';
  med_bool      _noversion=MED_FALSE;

  EXIT_IF(filein == NULL,"Le nom du fichier d'entrée est vide : ", filein);

  hasfileout = strcmp(fileout,"");
  if ( hasfileout ) {
    _fileoutsize = strlen(fileout);
    _fileout     = fileout;
  } else {
    _fileoutsize = strlen(filein)+strlen(PACKAGE_VERSION);
    tmp          = (char *) malloc(sizeof(char)*(_fileoutsize+1));
    strcpy(tmp,filein);
    strcat(tmp,PACKAGE_VERSION);
#ifdef PPRO_NT
    _splitpath( tmp, drive, dir, _fileout, ext );
#else
    _fileout     = basename(tmp);
#endif
    _fileoutsize = strlen(_fileout);

  }

  /* Test du format du fichier */

  ret = MEDfileCompatibility(filein,&hdfok,&medok);

  if (ret < 0 ) {
    fprintf(stdout,">>> Attention le fichier %s ne contient pas de numéro de version. \n",filein);
    fprintf(stdout,">>> Le fichier  %s est supposé être en version 2.1.1. \n",filein);
    /* PAs d'interactif dans une bibliothèque !*/
/*     fprintf(stdout,">>> Voulez-vous essayer une conversion d'un fichier  < 2.2 (o/n) ? "); */
/*     scanf("%c",&reponse); */
    if ( (reponse != 'o') && (reponse != 'O') && (reponse != 'y') && (reponse != 'Y') ) {
      EXIT_IF(MEDfileCompatibility(filein,&hdfok,&medok) < 0,
	      "Erreur d'appel de  MEDfileCompatibility : ", filein);
    }
    _noversion = MED_TRUE;
  }
  EXIT_IF( !hdfok ,
	  "Le fichier d'entrée n'est pas dans un format HDF compatible : ", filein);

/*   EXIT_IF( !medok , */
/* 	  "MEDimport ne gère pas le format  MED de ce fichier : ", filein); */

  /* Creation et ouverture du fichier que l'on va convertir au format MED actuel */
  commande = (char *) malloc(sizeof(char)*(strlen("cp ")+strlen(filein)+
					   strlen(" ")+_fileoutsize + 4 +1  ) );
  EXIT_IF(commande == NULL,NULL,NULL);
  strcpy(commande,"cp \"");
  strcat(commande,filein);
  strcat(commande,"\" \"");
  strcat(commande,_fileout);
  strcat(commande,"\"");
  fprintf(stdout,">>> Creation du fichier %s : %s \n",_fileout,commande);
  system(commande);
  free(commande);
  commande = (char *) malloc(sizeof(char)*(strlen("chmod u+w \"") + _fileoutsize +1 +1  ) );
  EXIT_IF(commande == NULL,NULL,NULL);
  strcpy(commande,"chmod u+w \"");
  strcat(commande,_fileout);
  strcat(commande,"\"");
  fprintf(stdout,">>> Chmod +w du fichier %s : %s \n",_fileout,commande);
  system(commande);
  free(commande);

  fid = MEDfileOpen(_fileout,MED_ACC_RDWR);
  EXIT_IF(fid < 0,"Ouverture du fichier : ", _fileout);

  /* Verification du numero de version */
  if (! _noversion)
    ret = MEDfileNumVersionRd(fid,&majeur,&mineur,&release);
  else {
    ret=0;
    majeur=2;
    mineur=1;
    release=1;
  }
  sprintf(version, IFORMAT"_"IFORMAT"_"IFORMAT, majeur, mineur, release);
  EXIT_IF(ret < 0,"Lecture du numero de version de MED-fichier",NULL);
  if (strcmp(version, "2_2_0") < 0)
    MAJ_21_22 = 1;
  if (strcmp(version, "2_3_2") < 0)
    MAJ_231_232 = 1;
  if (strcmp(version, "3_0_0") < 0)
    MAJ_236_300 = 1;
  if (strcmp(version, "3_1_0") < 0)
    MAJ_300_310 = 1;
  if (strcmp(version, "3_2_0") < 0)
    MAJ_310_320 = 1;

  /* Ne pas oublier que la version cible du fichier à convertir est celui de la bibliothèque. */
  if (MAJ_310_320 == 0) {
    fprintf(stdout,"Le fichier %s est déjà au bon format !!! \n",_fileout);
    ret = MEDfileClose(fid);
    EXIT_IF(ret < 0,"Fermeture du fichier",filein);
    return 0;
  }

  /* On avertit qu'on commence la conversion */
  fprintf(stdout,">>> Lancement de la normalisation du fichier selon le format " PACKAGE_VERSION " ...\n");

  /* On inhibe le gestionnaire d'erreur HDF5 */
  _MEDmodeErreurVerrouiller();

  /* Mise a jour du numero de version */
  fprintf(stdout,"- Lancement de la mise à jour du numéro de version ... \n");
  /*   La mise à jour MAJ_version(fid); doit être différée pour que les majs des fichiers anciens
       fonctionnent correctement*/
  /*   MAJ_version(fid); */
  MAJ_write_version_num(fid,2,3,6);
  fprintf(stdout,"  Numéro de version : ... OK ... \n");

  if (MAJ_21_22) {

    /* Mise a jour des maillages : type = MED_NON_STRUCTURE, description, ... */
    fprintf(stdout,"- Lancement de la mise à jour des maillages (21_22)... \n");
    MAJ_21_22_maillages(fid);
    fprintf(stdout,"  Maillage(s) : ... OK ...\n");

    /* Mise a jour des champs */
    fprintf(stdout,"- Lancement de la mise à jour des champs de résultats (21_22)... \n");
    MAJ_21_22_champs(fid);
    fprintf(stdout,"  Champs(s) : ... OK ...\n");

    /* Mise a jour des profils eventuels */
    nprofil = MEDnProfil(fid);
    if (nprofil > 0) {
      fprintf(stdout,"- Lancement de la mise à jour des profils (21_22)... \n");
      MAJ_21_22_profils(fid,nprofil);
      fprintf(stdout,"  Profils(s) : ... OK ...\n");
    } else {
      strncpy(chemin_profils,MED_PROFILS,MED_TAILLE_PROFILS-1);
      chemin_profils[MED_TAILLE_PROFILS-1] = '\0';
      gid = _MEDdatagroupCreer(fid,chemin_profils);
      EXIT_IF(gid < 0,"Creation du groupe HDF sur les profils",chemin_profils);
      ret = _MEDdatagroupFermer(gid);
      EXIT_IF(ret < 0,"Fermeture du groupe HDF sur les profils",chemin_profils);
    }

    /* On cree le groupe HDF pour les liens */
    strncpy(chemin_liens,MED_LIENS,MED_TAILLE_LIENS-1);
    chemin_liens[MED_TAILLE_LIENS-1] = '\0';
    gid = _MEDdatagroupCreer(fid,chemin_liens);
    EXIT_IF(gid < 0,"Creation du groupe HDF sur les liens",chemin_liens);
    ret = _MEDdatagroupFermer(gid);
    EXIT_IF(ret < 0,"Fermeture du groupe HDF sur les liens",chemin_liens);
  }

  if (MAJ_231_232) {
    /* Mise a jour des champs */
    fprintf(stdout,"- Lancement de la mise à jour des champs de résultats (231_232)... \n");
    MAJ_231_232_champs(fid);
    fprintf(stdout,"  Champs(s) : ... OK ...\n");
    fprintf(stdout,"- Lancement de la mise à jour des noms de maillages (231_232)... \n");
    MAJ_231_232_maillages(fid);
    fprintf(stdout,"  Noms(s) de maillage(s): ... OK ...\n");
  }

  if (MAJ_236_300) {
    /* Le système de cache de version a été developpé à partir de la 3.0*/
    /* Initialise le cache sur une 2.3.6 (cas d'absence d'INFO)*/
    _MEDfileVersion(fid);

    /* Mise a jour des champs */
    fprintf(stdout,"- Lancement de la mise à jour des champs de résultats (236_300)... \n");
    MAJ_236_300_champs(fid);
    fprintf(stdout,"  Champs(s) : ... OK ...\n");

    /* MAJ_version(fid); */

    fprintf(stdout,"- Lancement de la mise à jour des maillages (236_300)... \n");
    MAJ_236_300_maillages(fid);
    fprintf(stdout,"  Maillage(s): ... OK ...\n");

    /* MAJ_version(fid);  */

  }

  if (MAJ_300_310) {
    /* Le système de cache de version a été developpé à partir de la 3.0*/
    /* Initialise le cache sur une 3.0.8 (cas d'absence d'INFO)*/
    /* s'il n'a pas déjà été instanciée ds les MAJ précédentes */
    MAJ_write_version_num(fid,3,0,8);
    _MEDfileVersion(fid);
    /* Si le cache était dèjà instancié, met à jour le cache */
    MAJ_version_num(fid,3,0,8);

    /* Mise a jour des champs */
    fprintf(stdout,"- Lancement de la mise à jour des champs de résultats (300_310) ... \n");
    MAJ_300_310_champs(fid);
    fprintf(stdout,"  Champs(s) : ... OK ...\n");


  }

  if (MAJ_310_320) {
    /* Le système de cache de version a été developpé à partir de la 3.0*/
    /* Initialise le cache sur une 3.0.8 (cas d'absence d'INFO)*/
    /* s'il n'a pas été déjà été instanciée ds les MAJ_ précédentes */
    MAJ_write_version_num(fid,3,1,0);
    _MEDfileVersion(fid);
    /* Si le cache était dèjà instancié, met à jour le cache */
    MAJ_version_num(fid,3,1,0);

    /* Mise a jour des familles/groupes */
    fprintf(stdout,"- Lancement de la mise à jour des familles/groupes (310_320) ... \n");
    MAJ_310_320_familles(fid);
    fprintf(stdout,"  Famille(s)/Groupe(s) : ... OK ...\n");
  }

  /* A l'écriture d'une nouvelle version de MAJ ex 310_320,
   il est necessaire de revisiter les appels à MAJ_version(fid) pour
   les remplacer par les appels MAJ_version(fid,3,1,Lastest31z) */

  MAJ_version(fid);  
  MAJ_write_version_num(fid,MED_NUM_MAJEUR,MED_NUM_MINEUR,MED_NUM_RELEASE);

  /* Fermeture du fichier */
  ret = MEDfileClose(fid);
  EXIT_IF(ret < 0,"Fermeture du fichier",_fileout);

  /* On avertit que c'est fini */
  fprintf(stdout,">>> Conversion du fichier %s au format MED V" PACKAGE_VERSION " terminée\n",
	  _fileout);

  /* On libere la memoire */
  if (!hasfileout) free(tmp);

  return 0;
}
Example #13
0
int main( int argc, char *argv[], char** envp )
{
    int status;
    int i;
    char host_os_arg[] = "HOST_OS=Win32";
    char make_base_path[] = ".\\tools\\common\\Win32\\make.exe";

    /************************************************************/
    /*  Construct a full, safe path to the real make executable */

    char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];

    _splitpath( argv[0], drive, dir, fname, ext );

    int make_path_len = sizeof(make_base_path) + strlen(drive) + strlen(dir);

    char * make_path  = (char*) malloc( make_path_len );
    if ( make_path == NULL )
    {
        printf( "out of memory for make path - requested %d bytes\n", make_path_len);
        return -1;
    }

    /* Start with empty string */
    strcpy( make_path, "" );

    /* Add a drive spec if present */
    if ( strlen(drive) != 0 )
    {
        strcat( make_path, drive );
    }
    /* Add a path directory if present */
    if ( strlen(dir) != 0 )
    {
        strcat( make_path, dir );
    }

    /* Add a path directory if present */
    strcat( make_path, make_base_path );



    /*****************************************************************************************************/
    /*  Construct a full, command line including the real make executable path and the HOST_OS parameter */


    /* Determine the total lenght of the command line string */
    int command_length = make_path_len + strlen(host_os_arg) + 3;  // +3 for quotes around Make path and space before host_os_arg

    for( i = 1; i < argc; i++ )
    {
        command_length +=  strlen( argv[i] ) + 3; // +3 for two quotes and a space between args
    }


    /* Allocate a buffer for the command string */
    char * command  = (char*) malloc( command_length );
    if ( command == NULL )
    {
        printf( "out of memory for command - requested %d bytes\n", command_length);
        return -1;
    }

    /* Allocate a buffer for the argument pointer list */
    char** arglist = (char**) malloc( (argc + 2) * sizeof(char*) );
    if ( arglist == NULL )
    {
        printf( "out of memory for arglist - requested %d bytes\n",  (argc+2) * sizeof(char*) );
        return -1;
    }

    char** curr_arglist_pos = arglist;

    /* Add path of real make executable */
    /* surrounded by double quotes - to allow directories containing spaces to function */
    strcpy( command, "\"" );
    strcat( command, make_path );
    strcat( command, "\"" );
    *curr_arglist_pos = command;       /* Add to argument pointer list */
    curr_arglist_pos++;
    command += strlen(command) + 1;

    /* Add the HOST_OS argument */
    strcpy( command, host_os_arg );
    *curr_arglist_pos = command;       /* Add to argument pointer list  */
    curr_arglist_pos++;
    command += strlen(command) + 1;

    /* Add the other arguments - surrounded by double quotes to enable arguments with spaces to work */
    for( i = 1; i < argc; i++ )
    {
        strcpy( command, "\"" );
        strcat( command, argv[i] );
        strcat( command, "\"" );
        *curr_arglist_pos = command;    /* Add to argument pointer list */
        curr_arglist_pos++;
        command += strlen(command) + 1;
    }

    *curr_arglist_pos = NULL;


    /* Process the environment to get an environment list with most
     * variables wiped out but some saved.
     */
    const char* prefixes[] = { "",        SAVED_PREFIX, SAVED_PREFIX, (char *)0 };
    const char* env_vars[] = { "ComSpec", "HOME",       "PATH",       (char *)0 };

    char** env = get_saved_env_vars( env_vars, prefixes );

    /* Finally Spawn the real Make executable and wait for it to finish */
    return _spawnve ( _P_WAIT, make_path, (const char * const*)arglist, (const char * const*) env);
}
Example #14
0
void xrCore::_initialize	(LPCSTR _ApplicationName, LogCallback cb, BOOL init_fs, LPCSTR fs_fname)
{
	strcpy_s					(ApplicationName,_ApplicationName);
	if (0==init_counter) {
#ifdef XRCORE_STATIC	
		_clear87	();
		_control87	( _PC_53,   MCW_PC );
		_control87	( _RC_CHOP, MCW_RC );
		_control87	( _RC_NEAR, MCW_RC );
		_control87	( _MCW_EM,  MCW_EM );
#endif
		// Init COM so we can use CoCreateInstance
//		HRESULT co_res = 
			CoInitializeEx (NULL, COINIT_MULTITHREADED);

		strcpy_s			(Params,sizeof(Params),GetCommandLine());
		_strlwr_s			(Params,sizeof(Params));

		string_path		fn,dr,di;

		// application path
        GetModuleFileName(GetModuleHandle(MODULE_NAME),fn,sizeof(fn));
        _splitpath		(fn,dr,di,0,0);
        strconcat		(sizeof(ApplicationPath),ApplicationPath,dr,di);
#ifndef _EDITOR
		strcpy_s		(g_application_path,sizeof(g_application_path),ApplicationPath);
#endif

		// working path
        if( strstr(Params,"-wf") )
        {
            string_path				c_name;
            sscanf					(strstr(Core.Params,"-wf ")+4,"%[^ ] ",c_name);
            SetCurrentDirectory     (c_name);

        }
		GetCurrentDirectory(sizeof(WorkingPath),WorkingPath);
		// User/Comp Name
		DWORD	sz_user		= sizeof(UserName);
		GetUserName			(UserName,&sz_user);

		DWORD	sz_comp		= sizeof(CompName);
		GetComputerName		(CompName,&sz_comp);

		// Mathematics & PSI detection
		CPU::Detect			();
		
		Memory._initialize	(strstr(Params,"-mem_debug") ? TRUE : FALSE);
		
		DUMP_PHASE;

		InitLog				();
		_initialize_cpu		();

#ifdef DEBUG
	#ifndef DEDICATED_SERVER
		Debug._initialize	(FALSE);
	#else
		Debug._initialize	(TRUE);
	#endif
#endif
		rtc_initialize		();

		xr_FS				= xr_new<CLocatorAPI>	();

		xr_EFS				= xr_new<EFS_Utils>		();
//.		R_ASSERT			(co_res==S_OK);
	}
	if (init_fs){
		u32 flags			= 0;
		if (0!=strstr(Params,"-build"))	 flags |= CLocatorAPI::flBuildCopy;
		if (0!=strstr(Params,"-ebuild")) flags |= CLocatorAPI::flBuildCopy|CLocatorAPI::flEBuildCopy;
#ifdef DEBUG
		if (strstr(Params,"-cache"))  flags |= CLocatorAPI::flCacheFiles;
		else flags &= ~CLocatorAPI::flCacheFiles;
#endif // DEBUG
#ifdef _EDITOR // for EDITORS - no cache
		flags 				&=~ CLocatorAPI::flCacheFiles;
#endif // _EDITOR
		flags |= CLocatorAPI::flScanAppRoot;

#ifndef	_EDITOR
	#ifndef ELocatorAPIH
		if (0!=strstr(Params,"-file_activity"))	 flags |= CLocatorAPI::flDumpFileActivity;
	#endif
#endif
		FS._initialize		(flags,0,fs_fname);
		Msg					("'%s' build %d, %s\n","xrCore",build_id, build_date);
		EFS._initialize		();
#ifdef DEBUG
    #ifndef	_EDITOR
		Msg					("CRT heap 0x%08x",_get_heap_handle());
		Msg					("Process heap 0x%08x",GetProcessHeap());
    #endif
#endif // DEBUG
	}
	
	SetLogCB				(cb);

	LPAPI_VERSION ver = ImagehlpApiVersion();
	if ( NULL == GetProcAddress ( GetModuleHandle("dbghelp.dll"), "EnumerateLoadedModulesEx") )
	{
		string256 msg;		
		DWORD dwVer[2];
		WORD *v4 = (WORD*) &dwVer;
		CSymbolEngine SE;
		SE.GetInMemoryFileVersion("dbghelp.dll", dwVer[0], dwVer[1]);

		sprintf_s(msg, 256, "”старевший файл dbghelp.dll (%d.%d.%d.%d), его рекомендуетс¤ удалить.", 
								v4[1], v4[0], v4[3], v4[2]);
		MessageBox(NULL, msg, "DebugHlp Warning", MB_OK);
	}

	init_counter++;
}
Example #15
0
int main( int argc, char **argv )
{
    char                quiet;
    FILE                *fp;
    size_t              wanted;
    unsigned            i, j, k, l;
    int                 length = 0;
    char *              record_type;
    samp_block *        data;
    auto samp_header    head;
    cgraph_sample *     sptr;
    auto struct stat    file_stat;
    time_t              stamp;
    count_info          *count;
    bool                byte_swap = false;


    puts( banner1w( "Sample File Dump Utility", _WSAMP_VERSION_ ) );
    puts( banner2 );
    puts( banner2a( 1989 ) );
    puts( banner3 );
    puts( banner3a );

    if( argc != 2 && argc != 3 ) {
        puts( "usage: smpdump <sample_file> [-q]" );
        exit( 1 );
    }
    data = malloc( 63L * 1024 + 512 );
    quiet = 0;
    if( argc == 3 && strcmp( argv[2], "-q" ) == 0 ) {
        quiet = 1;
    }
    _splitpath( argv[1], drv, dir, name, ext );
    if( ext[0] == '\0' ) {
        strcpy( ext, ".smp" );
    }
    _makepath( path, drv, dir, name, ext );
    fp = fopen( path, "rb" );
    if( fp == NULL )
        return( 1 );
    if( fseek( fp, -(long)SIZE_HEADER, SEEK_END ) ) {
        fclose( fp );
        return( 1 );
    }
    fread( &head, 1, SIZE_HEADER, fp );
    if( head.signature != SAMP_SIGNATURE ) {
        SWAP_16( head.signature );
        if( head.signature == SAMP_SIGNATURE ) {
            byte_swap = true;
            SWAP_32( head.sample_start );
        } else {
            fclose( fp );
            return( 1 );
        }
    }
    printf( "Sample file version: %u.%u\n", head.major_ver, head.minor_ver );
    fseek( fp, head.sample_start, SEEK_SET );
    for( ;; ) {
        /* read the prefix of record */
        wanted = sizeof( data->pref );
        if( fread( &data->pref, 1, wanted, fp ) != wanted )
            break;
        COND_SWAP_32( data->pref.tick );
        COND_SWAP_16( data->pref.length );
        COND_SWAP_16( data->pref.kind );

        /* read the rest of the record */
        wanted = data->pref.length - sizeof( data->pref );
        if( fread( &data->d, 1, wanted, fp ) != wanted )
            break;

        /* dump common record data */
        record_type = "** UNKNOWN **";
        if( data->pref.kind < NUM_BLOCK_KINDS ) {
            record_type = Types[data->pref.kind];
        }
        printf( "%s  tick %lu length %u\n", record_type,
                data->pref.tick, data->pref.length );

        /* dump specific record data */
        switch( data->pref.kind ) {
        case SAMP_INFO:
            COND_SWAP_32( data->d.info.timer_rate );
            printf( "  timer rate %ld ms\n", data->d.info.timer_rate / 1000 );
            l = data->pref.length;
            if( head.major_ver == 2 && head.minor_ver <= 1 ) {
                count = &data->d.old_info.count[0];
                l -= offsetof( samp_block, d.old_info.count );
            } else {
                COND_SWAP_16( data->d.info.config.mad );
                printf( "  cpu=%d, fpu=%d, os_maj=%d, os_min=%d, os=%d, mad=%d\n",
                        data->d.info.config.cpu, data->d.info.config.fpu,
                        data->d.info.config.osmajor, data->d.info.config.osminor,
                        data->d.info.config.os, data->d.info.config.mad );
                count = &data->d.info.count[0];
                l -= offsetof( samp_block, d.info.count );
            }
            l /= sizeof( count_info );
            for( i = 0; i < l; ++i ) {
                COND_SWAP_32( count[i].number );
                COND_SWAP_32( count[i].size );
                printf( "    %s number %lu size %lu\n", Types[i],
                        count[i].number, count[i].size );
            }
            break;
        case SAMP_SAMPLES:
            j = data->pref.length;
            j -= offsetof( samp_block, d.sample.sample );
            j /= sizeof( samp_address );
            COND_SWAP_16( data->d.sample.thread_id );
            printf( "  thread id %u  #samples %u\n",
                    data->d.sample.thread_id, j );
            if( quiet ) {
                printf( "    ....\n    ....\n    ....\n" );
            } else {
                for( i = 0; i < j; ++i ) {
                    COND_SWAP_16( data->d.sample.sample[i].segment );
                    COND_SWAP_32( data->d.sample.sample[i].offset );
                    printf( "  - %.4x:%.8lx\n",
                            data->d.sample.sample[i].segment,
                            data->d.sample.sample[i].offset );
                }
            }
            break;
        case SAMP_MARK:
            COND_SWAP_16( data->d.sample.thread_id );
            COND_SWAP_16( data->d.mark.addr.segment );
            COND_SWAP_32( data->d.mark.addr.offset );
            printf( "  thread %u - %.4x:%.8lx  \"%s\"\n",
                    data->d.mark.thread_id, data->d.mark.addr.segment,
                    data->d.mark.addr.offset, data->d.mark.mark_string );
            break;
        case SAMP_OVL_LOAD:
            if( data->d.ovl.req_section & OVL_RETURN ) {
                printf( "  section %u (RETURN)\n",
                        data->d.ovl.req_section & (~ OVL_RETURN) );
            } else {
                printf( "  section %u\n", data->d.ovl.req_section );
            }
            printf( "    - requesting address = %.4x:%.8lx\n",
                    data->d.ovl.addr.segment, data->d.ovl.addr.offset );
            j = data->pref.length;
            j -= offsetof( samp_block, d.ovl.ovl_map );
            j /= sizeof( uint_8 );
            printf( "    - loaded overlay sections = " );
//            printf( "%.2x", data->d.ovl.ovl_map[0] );
            for( i = 0; i < j; ++i ) {
                printf( "%.2x", data->d.ovl.ovl_map[i] );
            }
            printf( "\n" );
            break;
        case SAMP_CODE_LOAD:
        case SAMP_MAIN_LOAD:
            stamp = data->d.code.time_stamp;
            COND_SWAP_32( stamp );
            COND_SWAP_16( data->d.code.ovl_tab.segment );
            COND_SWAP_32( data->d.code.ovl_tab.offset );
            printf( "  name = \"%s\"\n", data->d.code.name );
            printf( "  overlay table = %.4x:%.8lx\n",
                    data->d.code.ovl_tab.segment, data->d.code.ovl_tab.offset );
            printf( "  time stamp %lx -> %s", stamp,
                    ctime( &stamp ) );
            if( stat( data->d.code.name, &file_stat ) == 0 ) {
                printf( "  actual time stamp %lx -> %s", file_stat.st_mtime,
                        ctime( &(file_stat.st_mtime) ) );
            }
            break;
        case SAMP_ADDR_MAP:
            j = data->pref.length;
            j -= offsetof( samp_block, d.map );
            j /= sizeof( data->d.map );
            for( i = 0; i < j; ++i ) {
                COND_SWAP_16( data->d.map.data[i].map.segment );
                COND_SWAP_32( data->d.map.data[i].map.offset );
                COND_SWAP_16( data->d.map.data[i].actual.segment );
                COND_SWAP_32( data->d.map.data[i].actual.offset );
                printf( "  - %.4x:%.8lx -> %.4x:%.8lx\n",
                        data->d.map.data[i].map.segment,
                        data->d.map.data[i].map.offset,
                        data->d.map.data[i].actual.segment,
                        data->d.map.data[i].actual.offset );
            }
            break;
        case SAMP_LAST:
            break;
        case SAMP_REMAP_SECTION:
            j = data->pref.length;
            j -= offsetof( samp_block, d.remap );
            j /= sizeof( data->d.remap );
            for( i = 0; i < j; ++i ) {
                COND_SWAP_16( data->d.remap.data[i].section );
                COND_SWAP_16( data->d.remap.data[i].segment );
                printf( "  - %.4x -> %.4x\n",
                        data->d.remap.data[i].section,
                        data->d.remap.data[i].segment );
            }
            break;
        case SAMP_CALLGRAPH:
            j = data->d.cgraph.number;
            printf( "  thread id %u  #samples %u\n",
                                 data->d.cgraph.thread_id, j );
            if( quiet ) {
                printf( "    ....\n    ....\n    ....\n" );
            } else {
                sptr = &data->d.cgraph.sample[0];
                for( i = 0; i < j; i++ ) {
                    if( sptr->push_n != (uint_16)-1 || sptr->pop_n != (uint_16)-1 ) {
                        length -= sptr->pop_n;
                        if( length < 0 ) {
                            printf( "\n** Error: stack exhausted!\n\n" );
                        } else {
                            for( k = 0; k < length; k++ ) {
                                printf( " -  " );
                            }
                        }
                        for( k = sptr->push_n; k > 0; k-- ) {
                            printf( "%.4x:%.8lx    ",
                                sptr->addr[k - 1].segment,
                                sptr->addr[k - 1].offset );
                        }
                        length += sptr->push_n;
                        printf( "\n" );
                        sptr = (cgraph_sample *)&(sptr->addr[sptr->push_n]);
                    } else {
                        printf( "** Unknown callgraph info\n" );
                        sptr = (cgraph_sample *)&(sptr->addr[0]);
                    }
                }
            }
            break;
        }
        if( data->pref.kind == SAMP_LAST ) {
            break;
        }
    }
    fclose( fp );
    return( 0 );
}
Example #16
0
void GROUP_Read (int nRound)
    {
    int  nG, nT ;
    char Tmp [255] ;

    char Drive [_MAX_DRIVE] ;
    char Dir   [_MAX_DIR] ;
    char File  [_MAX_FNAME] ;
    char Ext   [_MAX_EXT] ;
    char Grp   [_MAX_PATH] ;

    // initialize group
    GROUP_InitG (nRound) ;

    // generate a full path GROUP1/2/3.TXT
    _splitpath (InstallDir, Drive, Dir, File, Ext) ;

    if (nRound == 0)
        {
        strcpy (File, GROUP1_NAME) ;
        }
    else
    if (nRound == 1)
        {
        strcpy (File, GROUP2_NAME) ;
        }
    else
        {
        strcpy (File, GROUP3_NAME) ;
        }

    strcpy (Ext, GROUP_EXT) ;

    _makepath (Grp, Drive, Dir, File, Ext) ;

    // count
    nGroup [nRound] = GetPrivateProfileInt ("Main", "Count", nGroup [nRound], Grp) ;

    // group
    for (nG = 0 ; nG < MAX_GROUP ; nG++)
        {

        sprintf (Tmp, "Group %d", nG + 1) ;

        // Index 1
        nT = GetPrivateProfileInt (Tmp, "Index 1", 0, Grp) ;
        aGroup [nRound] [nG] [0] = nT ;

        // Index 2
        nT = GetPrivateProfileInt (Tmp, "Index 2", 0, Grp) ;
        aGroup [nRound] [nG] [1] = nT ;

        // Index 3
        nT = GetPrivateProfileInt (Tmp, "Index 3", 0, Grp) ;
        aGroup [nRound] [nG] [2] = nT ;

        // Index 4
        nT = GetPrivateProfileInt (Tmp, "Index 4", 0, Grp) ;
        aGroup [nRound] [nG] [3] = nT ;
        }
    }
Example #17
0
File: GEOM.C Project: spr04/SUM2015
/* ‘ункци¤ загрузки геометрического объекта из G3D файла.
 * ј–√”ћ≈Ќ“џ:
 *   - указатель на геометрический объект:
 *       am1GEOM *G;
 *   - им¤ файла:
 *       CHAR *FileName;
 * ¬ќ«¬–јўј≈ћќ≈ «Ќј„≈Ќ»≈:
 *   (BOOL) TRUE при успехе, иначе - FALSE.
 */
BOOL AM1_GeomLoad( am1GEOM *G, CHAR *FileName )
{
  FILE *F;
  INT i, j, n;
  CHAR Sign[4];
  MATR M;
  static CHAR MtlName[300];
  static CHAR
    path_buffer[_MAX_PATH],
    drive[_MAX_DRIVE],
    dir[_MAX_DIR],
    fname[_MAX_FNAME],
    ext[_MAX_EXT];

  _splitpath(FileName, drive, dir, fname, ext);

  memset(G, 0, sizeof(am1GEOM));
  if ((F = fopen(FileName, "rb")) == NULL)
    return FALSE;

  M = MatrTranspose(MatrInverse(AM1_RndPrimMatrConvert));

  /* читаем сигнатуру */
  fread(Sign, 1, 4, F);
  if (*(DWORD *)Sign != *(DWORD *)"G3D")
  {
    fclose(F);
    return FALSE;
  }

  /* читаем количество примитивов в объекте */
  fread(&n, 4, 1, F);
  fread(MtlName, 1, 300, F);

  /* читаем и загружаем библиотеку материалов */
  _makepath(path_buffer, drive, dir, MtlName, "");
  AM1_MtlLoad(path_buffer);

  /* читаем примитивы */
  for (i = 0; i < n; i++)
  {
    INT nv, ni, *Ind;
    am1VERTEX *Vert;
    am1PRIM P;

    /* читаем количество вершин и индексов */
    fread(&nv, 4, 1, F);
    fread(&ni, 4, 1, F);
    /* читаем им¤ материала текущего примитива */
    fread(MtlName, 1, 300, F);

    /* выдел¤ем пам¤ть под вершины и индексы */
    if ((Vert = malloc(sizeof(am1VERTEX) * nv + sizeof(INT) * ni)) == NULL)
      break;
    Ind = (INT *)(Vert + nv);

    /* читаем данные */
    fread(Vert, sizeof(am1VERTEX), nv, F);
    /* конвертируем геометрию */
    for (j = 0; j < nv; j++)
    {
      Vert[j].P = VecMulMatr(Vert[j].P, AM1_RndPrimMatrConvert);
      Vert[j].N = VecMulMatr3(Vert[j].N, M);
    }
    fread(Ind, sizeof(INT), ni, F);

    /* заносим в примитив */
    AM1_PrimCreate(&P, AM1_PRIM_TRIMESH, nv, ni, Vert, Ind);
    P.MtlNo = AM1_MtlFind(MtlName);

    free(Vert);

    /* добавл¤ем примитив к объекту */
    AM1_GeomAddPrim(G, &P);
  }
  fclose(F);
  AM1_RndPrimMatrConvert = MatrIdentity();
  return TRUE;
} /* End of 'AM1_GeomDraw' function */
Example #18
0
void GROUP_Write (int nRound)
    {
    FILE *Fv ;

    char Drive [_MAX_DRIVE] ;
    char Dir   [_MAX_DIR] ;
    char File  [_MAX_FNAME] ;
    char Ext   [_MAX_EXT] ;
    char Grp   [_MAX_PATH] ;

    char Tmp   [1024] ;
    int  nG ;

    // generate a full path GROUP1/2/3.TXT
    _splitpath (InstallDir, Drive, Dir, File, Ext) ;

    if (nRound == 0)
        {
        strcpy (File, GROUP1_NAME) ;
        }
    else
    if (nRound == 1)
        {
        strcpy (File, GROUP2_NAME) ;
        }
    else
        {
        strcpy (File, GROUP3_NAME) ;
        }

    strcpy (Ext, GROUP_EXT) ;

    _makepath (Grp, Drive, Dir, File, Ext) ;

    // open
    Fv = fopen (Grp, "w") ;
    if (Fv == NULL)
        {
        sprintf (Tmp, "\n || Writing %s failed\n\n", Grp) ;
        TELNET_Write (Tmp) ;
        return ;
        }

    fprintf (Fv, ";\n") ;
    fprintf (Fv, "; TBOT group file\n") ;
    fprintf (Fv, ";\n") ;

    // [Main]
    fprintf (Fv, "[Main]\n") ;

    // group
    fprintf (Fv, "Count=%d\n", nGroup [nRound]) ;

    for (nG = 0 ; nG < MAX_GROUP ; nG++)
        {
        fprintf (Fv, "\n[Group %d]\n", nG + 1) ;
        fprintf (Fv, "Index 1=%d\n", aGroup [nRound] [nG] [0]) ;
        fprintf (Fv, "Index 2=%d\n", aGroup [nRound] [nG] [1]) ;
        fprintf (Fv, "Index 3=%d\n", aGroup [nRound] [nG] [2]) ;
        fprintf (Fv, "Index 4=%d\n", aGroup [nRound] [nG] [3]) ;
        }

    // close
    fclose (Fv) ;
    }
Example #19
0
INT_PTR CALLBACK CFileGroups::DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
// 	OutputDebugString("%s(%08X, %s, %08X, %08X)", __FUNCTION__, hwndDlg,
// 		GetMessageName(uMsg), wParam, lParam);
	static filegroups_t *pfile_groups(0);
	static HWND hwndTVCtrl, hwndEditCtrl;
	OPENFILENAME ofn;
	TVINSERTSTRUCT tvis;
	TVITEMEX tvi;
	HTREEITEM hti, hParent, hGroup, hChild, hSel;
	char text[MAX_PATH], drive[_MAX_DRIVE], dir[_MAX_DIR], path[QMAXPATH], ext[_MAX_EXT];
	BOOL hasSelection;
	switch (uMsg) {
		case WM_INITDIALOG: {
			_ASSERTE(lParam != 0);
			if (lParam == 0) {
				EndDialog(hwndDlg, IDCANCEL);
				return FALSE;
			}
			pfile_groups = reinterpret_cast<filegroups_t *>(lParam);
			hwndTVCtrl = GetDlgItem(hwndDlg, IDC_GROUPVWR);
			_ASSERTE(hwndTVCtrl != 0);
			if (hwndTVCtrl == NULL) {
				EndDialog(hwndDlg, IDCANCEL);
				return FALSE;
			}
			hwndEditCtrl = NULL;
			for (filegroups_t::const_iterator i = pfile_groups->begin(); i != pfile_groups->end(); ++i) {
				tvis.hParent = TVI_ROOT;
				tvis.hInsertAfter = TVI_SORT;
				tvis.itemex.mask = TVIF_STATE | TVIF_TEXT;
				tvis.itemex.state = 0; //TVIS_EXPANDED;
				tvis.itemex.stateMask = 0;
				tvis.itemex.pszText = const_cast<LPTSTR>(i->first.c_str());
				hParent = TreeView_InsertItem(hwndTVCtrl, &tvis);
				_ASSERTE(hParent != NULL);
				if (hParent == NULL) continue;
				for (filegroups_t::mapped_type::const_iterator j = i->second.begin(); j != i->second.end(); ++j) {
					tvis.hParent = hParent;
					tvis.hInsertAfter = TVI_SORT;
					tvis.itemex.mask = TVIF_TEXT;
					tvis.itemex.pszText = const_cast<LPTSTR>(j->c_str());
					hti = TreeView_InsertItem(hwndTVCtrl, &tvis);
					_ASSERTE(hti != NULL);
				}
				EnableDlgItem(hwndDlg, IDADD, TreeView_GetCount(hwndTVCtrl) > 0);
				EnableDlgItem(hwndDlg, IDREMOVE, TreeView_GetSelection(hwndTVCtrl) != 0);
			}
			static const tooltip_item_t tooltips[] = {
				IDC_GROUPVWR, "You can edit group names or filenames inplace by left clicking or pressing F2 on selected item",
			};
			HWND hwndTT(CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL,
				WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP | TTS_BALLOON, CW_USEDEFAULT, CW_USEDEFAULT,
				CW_USEDEFAULT, CW_USEDEFAULT, hwndDlg, NULL, hInstance, NULL));
			SetWindowPos(hwndTT, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
			SendMessage(hwndTT, TTM_SETMAXTIPWIDTH, 0, static_cast<LPARAM>(400));
			SendMessage(hwndTT, TTM_SETDELAYTIME, static_cast<WPARAM>(TTDT_AUTOPOP), static_cast<LPARAM>(20000));
			TOOLINFO tt;
			memset(&tt, 0, sizeof tt);
			tt.cbSize = sizeof tt;
			tt.uFlags = TTF_SUBCLASS | TTF_IDISHWND | TTF_TRANSPARENT;
			tt.hwnd = hwndDlg;
			tt.hinst = hInstance;
			for (UINT j = 0; j < qnumber(tooltips); ++j) {
				tt.uId = reinterpret_cast<UINT_PTR>(GetDlgItem(hwndDlg, tooltips[j].uID));
				tt.lpszText = const_cast<LPTSTR>(tooltips[j].lpText);
				SendMessage(hwndTT, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&tt));
			}
			return TRUE;
		}
		case WM_CLOSE:
			EndDialog(hwndDlg, LOWORD(wParam));
			return TRUE;
		case WM_COMMAND:
			//if (hwndEditCtrl != NULL) return FALSE;
			switch (HIWORD(wParam)) {
				case BN_CLICKED:
					switch (LOWORD(wParam)) {
						case IDOK:
							if (hwndEditCtrl != NULL) {
								TreeView_EndEditLabelNow(hwndTVCtrl, FALSE);
								SetWindowLong(hwndDlg, DWL_MSGRESULT, TRUE);
								return TRUE;
							}
							_ASSERTE(pfile_groups != 0);
							pfile_groups->clear();
							for (hGroup = TreeView_GetRoot(hwndTVCtrl);
								hGroup != NULL; hGroup = TreeView_GetNextSibling(hwndTVCtrl, hGroup)) {
								tvi.mask = TVIF_HANDLE | TVIF_TEXT;
								tvi.hItem = hGroup;
								tvi.pszText = text;
								tvi.cchTextMax = sizeof text;
								if (TreeView_GetItem(hwndTVCtrl, &tvi)) {
									filegroups_t::iterator i(pfile_groups->insert(pfile_groups->begin(),
										filegroups_t::value_type(text, filegroups_t::mapped_type())));
									_ASSERTE(i != pfile_groups->end());
									filegroups_t::mapped_type *
										pcurrentset(i != pfile_groups->end() ? &i->second : 0);
									if (pcurrentset != 0)
										for (hChild = TreeView_GetChild(hwndTVCtrl, hGroup);
											hChild != NULL; hChild = TreeView_GetNextSibling(hwndTVCtrl, hChild)) {
											tvi.mask = TVIF_HANDLE | TVIF_TEXT;
											tvi.hItem = hChild;
											tvi.pszText = text;
											tvi.cchTextMax = sizeof text;
											if (TreeView_GetItem(hwndTVCtrl, &tvi)) {
												/*if (qfileexist(text)) */pcurrentset->insert(text);
											}
#ifdef _DEBUG
											else
												_RPTF3(_CRT_ERROR, "%s(%08X, WM_COMMAND, ...): TreeView_GetItem(%08X, ...) returned NULL\n",
													__FUNCTION__, hwndDlg, hwndTVCtrl);
#endif // _DEBUG
										}
								}
#ifdef _DEBUG
								else
									_RPTF3(_CRT_ERROR, "%s(%08X, WM_COMMAND, ...): TreeView_GetItem(%08X, ...) returned NULL\n",
										__FUNCTION__, hwndDlg, hwndTVCtrl);
#endif // _DEBUG
							}
						case IDCANCEL:
							if (hwndEditCtrl != NULL)
								TreeView_EndEditLabelNow(hwndTVCtrl, TRUE);
							else
								EndDialog(hwndDlg, LOWORD(wParam));
							SetWindowLong(hwndDlg, DWL_MSGRESULT, 0);
							return TRUE;
						case IDADD: {
							hSel = TreeView_GetSelection(hwndTVCtrl);
							if (hSel == NULL) hSel = TreeView_GetRoot(hwndTVCtrl);
							if (hSel != NULL) {
								hGroup = TreeView_GetParent(hwndTVCtrl, hSel);
								if (hGroup == NULL) hGroup = hSel;
								memset(&ofn, 0, sizeof ofn);
								ofn.lStructSize = sizeof ofn;
								ofn.hInstance = hInstance;
								ofn.hwndOwner = hwndDlg;
								ofn.lpstrTitle = CFileGroups::lpstrTitle;
								boost::scoped_array<char> FileName(new char[0x10000]);
								if (!FileName) {
									_RPTF2(_CRT_ERROR, "%s(...): failed to allocate new string of size 0x%X\n",
										__FUNCTION__, 0x10000);
									SetWindowLong(hwndDlg, DWL_MSGRESULT, 0);
									throw std::bad_alloc(); //break;
								}
								FileName[0] = 0;
								ofn.lpstrFile = FileName.get();
								ofn.nMaxFile = 0x10000;
								ofn.Flags = OFN_ENABLESIZING | OFN_EXPLORER | OFN_FORCESHOWHIDDEN |
									OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST |
									OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT;
								ofn.lpstrFilter = CFileGroups::lpstrFilter;
								ofn.nFilterIndex = CFileGroups::nFilterIndex;
								ofn.lpstrDefExt = CFileGroups::lpstrDefExt;
								get_input_file_path(CPY(path));
								_splitpath(path, drive, dir, 0, 0);
								_makepath(path, drive, dir, 0, 0);
								ofn.lpstrInitialDir = path;
								ofn.nMaxFile = 0x10000;
								if (GetOpenFileName(&ofn))
									if (ofn.nFileOffset > strlen(ofn.lpstrFile))
										while (*(ofn.lpstrFile + ofn.nFileOffset)) {
											AddFile(hwndTVCtrl, hGroup, _sprintf("%s\\%s",
												ofn.lpstrFile, ofn.lpstrFile + ofn.nFileOffset).c_str());
											ofn.nFileOffset += strlen(ofn.lpstrFile + ofn.nFileOffset) + 1;
										}
									else
										AddFile(hwndTVCtrl, hGroup, ofn.lpstrFile);
								EnableDlgItem(hwndDlg, IDADD, TRUE);
								EnableDlgItem(hwndDlg, IDREMOVE, TreeView_GetSelection(hwndTVCtrl) != 0);
							}
							SetWindowLong(hwndDlg, DWL_MSGRESULT, 0);
							return TRUE;
						}
						case IDADDGROUP: {
							char *newgroup(askstr(HIST_IDENT, NULL, "New group name"));
							if (newgroup != 0 && strlen(newgroup) > 0) {
								if (strlen(newgroup) >= MAX_PATH) newgroup[MAX_PATH - 1] = 0;
								for (hGroup = TreeView_GetRoot(hwndTVCtrl);
									hGroup != NULL; hGroup = TreeView_GetNextSibling(hwndTVCtrl, hGroup)) {
									tvi.mask = TVIF_HANDLE | TVIF_TEXT;
									tvi.hItem = hGroup;
									tvi.pszText = text;
									tvi.cchTextMax = sizeof text;
									if (TreeView_GetItem(hwndTVCtrl, &tvi)) {
										if (strcmp(newgroup, text) == 0) {
											warning("Group with this name already exists");
											SetWindowLong(hwndDlg, DWL_MSGRESULT, 0);
											return FALSE;
										}
									}
#ifdef _DEBUG
									else
										_RPTF3(_CRT_ERROR, "%s(%08X, WM_COMMAND, ...): TreeView_GetItem(%08X, ...) returned NULL\n",
											__FUNCTION__, hwndDlg, hwndTVCtrl);
#endif // _DEBUG
								}
								tvis.hParent = TVI_ROOT;
								tvis.hInsertAfter = TVI_SORT;
								tvis.itemex.mask = TVIF_STATE | TVIF_TEXT;
								tvis.itemex.state = TVIS_EXPANDED;
								tvis.itemex.stateMask = 0;
								tvis.itemex.pszText = newgroup;
								hti = TreeView_InsertItem(hwndTVCtrl, &tvis);
								_ASSERTE(hti != NULL);
								if (hti != NULL) {
									TreeView_SelectItem(hwndTVCtrl, hti);
									TreeView_Expand(hwndTVCtrl, hti, TVE_EXPAND);
									EnableDlgItem(hwndDlg, IDADD, TRUE);
									EnableDlgItem(hwndDlg, IDREMOVE, TRUE);
								}
							}
							SetWindowLong(hwndDlg, DWL_MSGRESULT, 0);
							return TRUE;
						}
						case IDREMOVE:
							if ((hSel = TreeView_GetSelection(hwndTVCtrl)) != NULL) {
								if ((hParent = TreeView_GetParent(hwndTVCtrl, hSel)) == NULL
									&& TreeView_GetChild(hwndTVCtrl, hSel) != NULL) { // is group
									std::string msg("Are you sure to delete group '");
									tvi.mask = TVIF_HANDLE | TVIF_TEXT;
									tvi.hItem = hSel;
									tvi.pszText = text;
									tvi.cchTextMax = sizeof text;
									if (TreeView_GetItem(hwndTVCtrl, &tvi)) msg.append(text);
									msg.append("' and all it's files?");
									if (MessageBox(hwndDlg, msg.c_str(), "libnames matching",
										MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON1) == IDYES)
										TreeView_DeleteItem(hwndTVCtrl, hSel);
								} else  // is file or group has no files - delete without confirmation
									TreeView_DeleteItem(hwndTVCtrl, hSel);
								if (TreeView_GetCount(hwndTVCtrl) <= 0)
									EnableDlgItem(hwndDlg, IDADD, FALSE);
								EnableDlgItem(hwndDlg, IDREMOVE, TreeView_GetSelection(hwndTVCtrl) != NULL);
							}
							SetWindowLong(hwndDlg, DWL_MSGRESULT, 0);
							return TRUE;
					}
					break;
			}
			break;
		case WM_NOTIFY:
			_ASSERTE(lParam != NULL);
			if (lParam != NULL) {
//  				OutputDebugString("%s(%08X, WM_NOTIFY, ...): hwndFrom=%08X idFrom=%u code=0x%X",
//  					__FUNCTION__, hwndDlg, reinterpret_cast<LPNMHDR>(lParam)->hwndFrom, reinterpret_cast<LPNMHDR>(lParam)->idFrom,
// 					reinterpret_cast<LPNMHDR>(lParam)->code);
				switch (reinterpret_cast<LPNMHDR>(lParam)->idFrom) {
					case IDC_GROUPVWR:
						switch (reinterpret_cast<LPNMHDR>(lParam)->code) {
							case TVN_KEYDOWN:
								switch (reinterpret_cast<LPNMTVKEYDOWN>(lParam)->wVKey) {
									case VK_F2:
										if ((hSel = TreeView_GetSelection(hwndTVCtrl)) != NULL)
											TreeView_EditLabel(hwndTVCtrl, hSel);
										SetWindowLong(hwndDlg, DWL_MSGRESULT, TRUE);
										return TRUE;
									case VK_INSERT:
										SendMessage(hwndDlg, WM_COMMAND,
											(hSel = TreeView_GetSelection(hwndTVCtrl)) != NULL
											&& TreeView_GetParent(hwndTVCtrl, hSel) != NULL ?
											MAKELONG(IDADD, BN_CLICKED) : MAKELONG(IDADDGROUP, BN_CLICKED),
											reinterpret_cast<LPARAM>(hwndTVCtrl));
										SetWindowLong(hwndDlg, DWL_MSGRESULT, TRUE);
										return TRUE;
									case VK_DELETE:
										SendMessage(hwndDlg, WM_COMMAND, MAKELONG(IDREMOVE, BN_CLICKED),
											reinterpret_cast<LPARAM>(hwndTVCtrl));
										SetWindowLong(hwndDlg, DWL_MSGRESULT, TRUE);
										return TRUE;
								}
								break;
							case TVN_BEGINLABELEDIT: {
								if ((hSel = TreeView_GetSelection(hwndTVCtrl)) != NULL
									&& TreeView_GetParent(hwndTVCtrl, hSel) != NULL) {
									tvi.mask = TVIF_HANDLE | TVIF_TEXT;
									tvi.hItem = hSel;
									tvi.pszText = text;
									tvi.cchTextMax = sizeof text;
									if (TreeView_GetItem(hwndTVCtrl, &tvi)) {
										memset(&ofn, 0, sizeof ofn);
										ofn.lStructSize = sizeof ofn;
										ofn.lpstrFile = text;
										ofn.nMaxFile = sizeof text;
										_splitpath(text, drive, dir, 0, ext);
										_makepath(path, drive, dir, 0, 0);
										ofn.lpstrInitialDir = path;
										ofn.hwndOwner = hwndDlg;
										ofn.hInstance = hInstance;
										ofn.Flags = OFN_ENABLESIZING | OFN_EXPLORER | OFN_FORCESHOWHIDDEN |
											OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST |
											OFN_HIDEREADONLY;
										ofn.lpstrTitle = "Change file's location";
										ofn.lpstrFilter = "all files\0*.*\0";
										ofn.nFilterIndex = 1;
										ofn.lpstrDefExt = ext;
										if (GetOpenFileName(&ofn)) {
											tvi.mask = TVIF_HANDLE | TVIF_TEXT;
											TreeView_SetItem(hwndTVCtrl, &tvi);
										}
										SetWindowLong(hwndDlg, DWL_MSGRESULT, TRUE);
										return TRUE;
									}
#ifdef _DEBUG
									else
										_RPTF2(_CRT_WARN, "%s(...): TreeView_GetItem(%08X, ...) returned NULL",
											__FUNCTION__, hwndTVCtrl);
#endif // _DEBUG
								}
								hwndEditCtrl = TreeView_GetEditControl(hwndTVCtrl);
								_ASSERTE(hwndEditCtrl != NULL);
								SendMessage(hwndEditCtrl, EM_LIMITTEXT, MAX_PATH - 1, 0);
								SetWindowLong(hwndDlg, DWL_MSGRESULT, FALSE);
								return TRUE;
							}
							case TVN_ENDLABELEDIT:
								hwndEditCtrl = NULL;
								SetWindowLong(hwndDlg, DWL_MSGRESULT,
									reinterpret_cast<LPNMTVDISPINFO>(lParam)->item.pszText != NULL
									&& strlen(reinterpret_cast<LPNMTVDISPINFO>(lParam)->item.pszText) > 0
									&& strlen(reinterpret_cast<LPNMTVDISPINFO>(lParam)->item.pszText) < MAX_PATH);
								return TRUE;
							case TVN_SELCHANGED:
								EnableDlgItem(hwndDlg, IDREMOVE, TreeView_GetSelection(hwndTVCtrl) != 0);
								return TRUE;
							//case WM_LBUTTONDBLCLCK:
							//	break;
						} // switch code
						break;
				} // switch idFrom
			} // lParam != NULL
			break;
	} // main switch
	return 0;
}
Example #20
0
/* Функция загрузки материала.
 * АРГУМЕНТЫ:
 *   - геометрический объект:
 *       as4GEOM *G;
 *   - имя файла материалов:
 *       CHAR *FileName;
 * ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ: Нет.
*/
static VOID LoadMaterials( as4GEOM *G, CHAR *FileName )
{
  FILE *F;
  as4MATERIAL DefMat, Mat;
  static CHAR FName[_MAX_PATH];

  _makepath(FName, ModelDrive, ModelDir, FileName, "");
  if ((F = fopen(FName, "r")) == NULL)
    return;

  DefMat.Ka = VecSet(0.1, 0.1, 0.1);
  DefMat.Kd = VecSet(0.9, 0.9, 0.9);
  DefMat.Ks = VecSet(0.0, 0.0, 0.0);
  DefMat.Phong = 30;
  DefMat.TexNo = 0;
  DefMat.Trans = 1;
  strcpy(DefMat.Name, "Default Material SPR 2014");
  DefMat.MapD[0] = 0;
  Mat = DefMat;

  /* считываем все сроки */
  while (fgets(Buf, sizeof(Buf), F) != NULL)
  {
    Split();
    if (NumOfParts > 1)
      if (strcmp(Parts[0], "Ka") == 0)
      {
        sscanf(Parts[1], "%f", &Mat.Ka.x);
        sscanf(Parts[2], "%f", &Mat.Ka.y);
        sscanf(Parts[3], "%f", &Mat.Ka.z);
      }
      else if (strcmp(Parts[0], "Kd") == 0)
      {
        sscanf(Parts[1], "%f", &Mat.Kd.x);
        sscanf(Parts[2], "%f", &Mat.Kd.y);
        sscanf(Parts[3], "%f", &Mat.Kd.z);
      }
      else if (strcmp(Parts[0], "Ks") == 0)
      {
        sscanf(Parts[1], "%f", &Mat.Ks.x);
        sscanf(Parts[2], "%f", &Mat.Ks.y);
        sscanf(Parts[3], "%f", &Mat.Ks.z);
      }
      else if (strcmp(Parts[0], "Ns") == 0)
        sscanf(Parts[1], "%f", &Mat.Phong);
      else if (strcmp(Parts[0], "D") == 0 ||
               strcmp(Parts[0], "d") == 0 ||
               strcmp(Parts[0], "Tr") == 0)
        sscanf(Parts[1], "%f", &Mat.Trans);
      else if (strcmp(Parts[0], "map_Kd") == 0)
      {
        _splitpath(Parts[NumOfParts - 1], TexDrive, TexDir, TexFileName, TexFileExt);
        _makepath(Mat.MapD, ModelDrive, ModelDir, TexFileName, ".bmp");
      }
      else if (strcmp(Parts[0], "newmtl") == 0)
      {
        AS4_GeomAddMaterial(G, &Mat);
        Mat = DefMat;
        strncpy(Mat.Name, Parts[1], sizeof(Mat.Name) - 1);
      }
  }
  AS4_GeomAddMaterial(G, &Mat);
  fclose(F);
} /* End of 'LoadMaterials' function */
Example #21
0
void CPatternFunction::vfLoadEF(LPCSTR caFileName)
{
	string_path		caPath;
	if (!FS.exist(caPath,"$game_ai$",caFileName)) {
		Msg			("! Evaluation function : File not found \"%s\"",caPath);
		R_ASSERT	(false);
		return;
	}
	
	IReader			*F = FS.r_open(caPath);
	F->r			(&m_tEFHeader,sizeof(SEFHeader));

	if (EFC_VERSION != m_tEFHeader.dwBuilderVersion) {
		FS.r_close	(F);
		Msg			("! Evaluation function (%s) : Not supported version of the Evaluation Function Contructor",caPath);
		R_ASSERT	(false);
		return;
	}

	F->r			(&m_dwVariableCount,sizeof(m_dwVariableCount));
	m_dwaAtomicFeatureRange = xr_alloc<u32>(m_dwVariableCount);
	ZeroMemory		(m_dwaAtomicFeatureRange,m_dwVariableCount*sizeof(u32));
	u32				*m_dwaAtomicIndexes = xr_alloc<u32>(m_dwVariableCount);
	ZeroMemory		(m_dwaAtomicIndexes,m_dwVariableCount*sizeof(u32));

	for (u32 i=0; i<m_dwVariableCount; ++i) {
		F->r(m_dwaAtomicFeatureRange + i,sizeof(u32));
		if (i)
			m_dwaAtomicIndexes[i] = m_dwaAtomicIndexes[i-1] + m_dwaAtomicFeatureRange[i-1];
	}

	m_dwaVariableTypes = xr_alloc<u32>(m_dwVariableCount);
	F->r			(m_dwaVariableTypes,m_dwVariableCount*sizeof(u32));

	F->r			(&m_dwFunctionType,sizeof(u32));

	F->r			(&m_fMinResultValue,sizeof(float));
	F->r			(&m_fMaxResultValue,sizeof(float));

	F->r			(&m_dwPatternCount,sizeof(m_dwPatternCount));
	m_tpPatterns	= xr_alloc<SPattern>(m_dwPatternCount);
	m_dwaPatternIndexes = xr_alloc<u32>(m_dwPatternCount);
	ZeroMemory		(m_dwaPatternIndexes,m_dwPatternCount*sizeof(u32));
	m_dwParameterCount = 0;
	for (u32 i=0; i<m_dwPatternCount; ++i) {
		if (i)
			m_dwaPatternIndexes[i] = m_dwParameterCount;
		F->r		(&(m_tpPatterns[i].dwCardinality),sizeof(m_tpPatterns[i].dwCardinality));
		m_tpPatterns[i].dwaVariableIndexes = xr_alloc<u32>(m_tpPatterns[i].dwCardinality);
		F->r		(m_tpPatterns[i].dwaVariableIndexes,m_tpPatterns[i].dwCardinality*sizeof(u32));
		u32			m_dwComplexity = 1;
		for (int j=0; j<(int)m_tpPatterns[i].dwCardinality; ++j)
			m_dwComplexity *= m_dwaAtomicFeatureRange[m_tpPatterns[i].dwaVariableIndexes[j]];
		m_dwParameterCount += m_dwComplexity;
	}
	
	m_faParameters	= xr_alloc<float>(m_dwParameterCount);
	F->r			(m_faParameters,m_dwParameterCount*sizeof(float));
	FS.r_close		(F);

	m_dwaVariableValues = xr_alloc<u32>(m_dwVariableCount);
	
	xr_free			(m_dwaAtomicIndexes);
    
	ef_storage().m_fpaBaseFunctions[m_dwFunctionType] = this;
	
	_splitpath		(caPath,0,0,m_caName,0);

	// Msg			("* Evaluation function \"%s\" is successfully loaded",m_caName);
}
Example #22
0
/* Функция загрузки геометрического объекта.
 * АРГУМЕНТЫ:
 *   - геометрический объект:
 *       as4GEOM *G;
 *   - имя файла материалов:
 *       CHAR *FileName;
 * ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ:
 *   (BOOL) TRUE при успехе.
 */
BOOL AS4_GeomLoad( as4GEOM *G, CHAR *FileName )
{
  INT vn = 0, vtn = 0, vnn = 0, fn = 0, pn = 0, size, i, p;
  FILE *F;
  /* читаемые данные */
  VEC *ReadV, *ReadN;
  as4UV *ReadUV;
  INT (*ReadF)[3];
  /* хранение примитивов */
  struct
  {
    INT
      First, Last, /* первый и последний номера вершин примитива */
      Mtl;         /* материал примитива */
  } *PrimInfo;

  memset(G, 0, sizeof(as4GEOM));
  /* разбиваем имя на части и открываем файл */
  _splitpath(FileName, ModelDrive, ModelDir, ModelFileName, ModelFileExt);
  if ((F = fopen(FileName, "rt")) == NULL)
    return FALSE;

  /* считаем количества */
  while (fgets(Buf, sizeof(Buf), F) != NULL)
    if (Buf[0] == 'v' && Buf[1] == ' ')
      vn++;
    else if (Buf[0] == 'v' && Buf[1] == 't')
      vtn++;
    else if (Buf[0] == 'v' && Buf[1] == 'n')
      vnn++;
    else if (Buf[0] == 'f' && Buf[1] == ' ')
      fn += Split() - 3;
    else if (strncmp(Buf, "usemtl", 6) == 0)
      pn++;

  if (pn == 0)
    pn = 1; /* материалы не использовались */

  /* загружаем:
   *   вершины                        vn
   *   нормали                        vvn
   *   текстурные координаты          vtn
   *   треугольники                   fn
   *   примитивы                      pn
   * дополнительно:
   *   индексы (Vv, Vn, Vt) <- новые номера вершин  ? (vn + vt + vnn) * ???
   *   начальные индексы              vn
   */

  /* выделяем память под вспомогательные данные */
  size = 
    sizeof(VEC) * vn +                        /*   вершины               vn */
    sizeof(VEC) * vnn +                       /*   нормали               vnn */
    sizeof(as4UV) * vtn +                     /*   текстурные координаты vtn */
    sizeof(INT [3]) * fn +                    /*   треугольники          fn */
    sizeof(PrimInfo[0]) * pn +                /*   примитивы             pn */
    sizeof(VertexRefs[0]) * (vn + vtn + vnn) + /*   индексы (Vv, Vn, Vt)  (vn + vt + vnn) */
    sizeof(INT) * vn;                         /*   начальные индексы     vn */
  if ((ReadV = malloc(size)) == NULL)
  {
    fclose(F);
    return FALSE;
  }
  memset(ReadV, 0, size);

  /* расставляем указатели */
  ReadN = ReadV + vn;
  ReadUV = (as4UV *)(ReadN + vnn);
  ReadF = (INT (*)[3])(ReadUV + vtn);
  VertexRefsStart = (INT *)(ReadF + fn);
  PrimInfo = (VOID *)(VertexRefsStart + vn);
  VertexRefs = (VOID *)(PrimInfo + pn);
  NumOfAllocedVertexRefs = vn + vtn + vnn;
  NumOfVertexRefs = 0;
  /* начала списка индексов вершин ==> -1 */
  memset(VertexRefsStart, 0xFF, sizeof(INT) * vn);
  memset(VertexRefs, 0xFF, sizeof(VertexRefs[0]) * NumOfAllocedVertexRefs);

  /* второй проход - читаем геометрию */
  rewind(F);
  vn = 0;
  vtn = 0;
  vnn = 0;
  fn = 0;
  pn = 0;
  PrimInfo[0].First = 0;

  /* считаем количества */
  while (fgets(Buf, sizeof(Buf), F) != NULL)
    if (Buf[0] == 'v' && Buf[1] == ' ')
    {
      FLT x = 0, y = 0, z = 0;

      sscanf(Buf + 2, "%f%f%f", &x, &y, &z);
      ReadV[vn++] = VecSet(x, y, z);
    }
    else if (Buf[0] == 'v' && Buf[1] == 't')
    {
      FLT u = 0, v = 0;

      sscanf(Buf + 3, "%f%f", &u, &v);
      ReadUV[vtn++] = AS4_UVSet(u, v);
    }
    else if (Buf[0] == 'v' && Buf[1] == 'n')
    {
      FLT nx = 0, ny = 0, nz = 0;

      sscanf(Buf + 3, "%f%f%f", &nx, &ny, &nz);
      ReadN[vnn++] = VecNormalize(VecSet(nx, ny, nz));
    }
    else if (Buf[0] == 'f' && Buf[1] == ' ')
    {
      INT n0[3], n1[3], n[3], r0, r1, r;

      Split();
      SCANF3(Parts[1], n0);
      r0 = GetVertexNo(n0[0], n0[1], n0[2]);

      SCANF3(Parts[2], n1);
      r1 = GetVertexNo(n1[0], n1[1], n1[2]);

      for (i = 3; i < NumOfParts; i++)
      {
        SCANF3(Parts[i], n);
        r = GetVertexNo(n[0], n[1], n[2]);

        ReadF[fn][0] = r0;
        ReadF[fn][1] = r1;
        ReadF[fn][2] = r;
        r1 = r;
        fn++;
      }
    }
    else if (strncmp(Buf, "usemtl", 6) == 0)
    {
      Split();

      /* запоминаем номер последней грани */
      if (pn != 0)
        PrimInfo[pn - 1].Last = fn - 1;

      /* ищем материал */
      for (i = 0; i < G->NumOfMtls; i++)
        if (strcmp(Parts[1], G->Mtls[i].Name) == 0)
          break;
      if (i == G->NumOfMtls)
        PrimInfo[pn].Mtl = -1;
      else
        PrimInfo[pn].Mtl = i;
      PrimInfo[pn].First = fn;
      pn++;
    }
    else if (strncmp(Buf, "mtllib ", 7) == 0)
    {
      Split();
      LoadMaterials(G, Parts[1]);
    }

  /* у последнего примитива запоминаем номер последней грани */
  if (pn == 0)
  {
    PrimInfo[0].Last = fn - 1;
    PrimInfo[0].Mtl = -1;
  }
  else
    PrimInfo[pn - 1].Last = fn - 1;
  fclose(F);

  /* Формируем примитивы из прочитанных данных */
  AS4_DefaultColor = ColorSet(1, 1, 1);
  for (p = 0; p < pn; p++)
  {
    INT minv, maxv, j;
    as4PRIM prim;
    BOOL is_need_normal = FALSE;

    minv = maxv = ReadF[PrimInfo[p].First][0];
    for (i = PrimInfo[p].First; i <= PrimInfo[p].Last; i++)
      for (j = 0; j < 3; j++)
      {
        if (minv > ReadF[i][j])
          minv = ReadF[i][j];
        if (maxv < ReadF[i][j])
          maxv = ReadF[i][j];
      }
    vn = maxv - minv + 1;
    fn = PrimInfo[p].Last - PrimInfo[p].First + 1;
    AS4_PrimCreate(&prim, AS4_PRIM_TRIMESH, vn, fn * 3);

    /* копируем вершины */
    for (i = 0; i < vn; i++)
    {
      INT n;

      prim.V[i].P = ReadV[VertexRefs[minv + i].Nv];
      if ((n = VertexRefs[minv + i].Nn) != -1)
        prim.V[i].N = ReadN[n];
      else
        is_need_normal = TRUE;
      if ((n = VertexRefs[minv + i].Nt) != -1)
        prim.V[i].T = ReadUV[n];
    }
    /* копируем грани */
    for (i = 0; i < fn; i++)
      for (j = 0; j < 3; j++)
        prim.I[i * 3 + j] = ReadF[PrimInfo[p].First + i][j] - minv;
    if (is_need_normal)
        AS4_PrimAutoNormals(&prim);
    prim.Mtl = PrimInfo[p].Mtl;
    AS4_GeomAddPrim(G, &prim);
  }
  /* освобождаем память из-под прочитанных данных */
  free(ReadV);
  return TRUE;
} /* End of 'AS4_GeomLoad' function */
Example #23
0
void parse_args(int argc,char **argv,void (*handler_func)(char *arg),int flags)
{

	for (;argc--;argv++) {
		if (**argv=='@') {			/* read args from file */
			char *arg_ptrs[MAX_ARGS];
			int arg_count;
			FILE *argfile;
			int len;
			char *p=ab_ptr,c;

			if ((argfile=fopen(*argv+1,"rt"))==0) perror_exit(10,*argv+1);
			if ((len=fread(ab_ptr,1,ARGBUF_SIZE-((int) (ab_ptr-arg_buf)),argfile))==ARGBUF_SIZE-(ab_ptr-arg_buf)) error_exit(20,"Argument buffer not big enough\n");
			fclose(argfile);
			ab_ptr[len++]=0;		/* write terminating null */

			/* remove comments */

			while ((p=strchr(ab_ptr,';'))!=NULL) {
				char *p2=strchr(p,'\n');

				if (p2) { 	/* found cr */
					strcpy(p,p2);	/* copy over comment */
					len = strlen(ab_ptr);
				}
				else {		/* no cr, end of string */
					*p=0;
					len = (int) (p-ab_ptr);
				}
			}
			ab_ptr[len]=0;		/* write terminating null */

			while (!ab_ptr[len-1]) len--;	/* back up over terminating nulls */
			p=ab_ptr;


			for (arg_count=0;p<ab_ptr+len;) {
				while (p<ab_ptr+len && ((c=*p)==' ' || c=='\t' || c=='\n')) p++;
				if (p<ab_ptr+len) {	/* found parm? */
					arg_ptrs[arg_count++]=p;
					if (arg_count>=MAX_ARGS) error_exit(10,"Too many args");
					while (p<ab_ptr+len && !((c=*p)==' ' || c=='\t' || c=='\n')) p++;
					*p++=0;
				}
			}
			ab_ptr+=len;
			parse_args(arg_count,arg_ptrs,handler_func,flags);
		}
		else
			if (flags&PA_EXPAND && (**argv != '-')) {
				struct find_t ffblk;
				char drive[_MAX_DRIVE],dir[_MAX_DIR];
				char filename[_MAX_DRIVE+_MAX_DIR+13],*nptr;
				int done;

				_splitpath(*argv,drive,dir,NULL,NULL);		//get path
				strcpy(filename,drive);
				strcat(filename,dir);
				nptr = filename + strlen(filename);			//point at name part

				done = _dos_findfirst(*argv,0,&ffblk);

				if (done) handler_func(*argv);
			
				else while (!done) {

					strcpy(nptr,ffblk.name);	//copy name after path

					handler_func(filename);
			
					done = _dos_findnext(&ffblk);
			
				}
	
			}
			else
				handler_func(*argv);

	}

}
Example #24
0
int main( int argc, char *[] )
{
    if( argc < 2 || argc > 3 ) {
        HCWarning( USAGE );
        return( -1 );
    }

    // Parse the command line.
    char    cmdline[80];
    char    *pfilename, *temp;
    int     quiet = 0;

    getcmd( cmdline );
    temp = cmdline;
    pfilename = NULL;
    while( *temp != '\0' && isspace( *temp ) ) {
        temp++;
    }
    if( *temp == '-' || *temp == '/' ) {
        temp++;
        if( (*temp != 'q' && *temp != 'Q') || !isspace( *(temp+1) ) ) {
            HCWarning( USAGE );
            return( -1 );
        } else {
            quiet = 1;
            temp++;
            while( *temp != '\0' && isspace( *temp ) ) {
                temp++;
            }
            if( *temp == '\0' ) {
                HCWarning( USAGE );
                return( -1 );
            } else {
                pfilename = temp;
            }
        }
    } else if( *temp != '\0' ) {
        pfilename = temp++;
        while( *temp != '\0' && *temp != '/' && *temp != '-' ) {
            temp++;
        }
        if( *temp != '\0' ) {
            *temp = '\0';
            temp++;
            if( *temp != 'q' && *temp != 'Q' ) {
                HCWarning( USAGE );
                return( -1 );
            } else {
                temp++;
                while( *temp != '\0' && isspace( *temp ) ) {
                    temp++;
                }
                if( *temp != '\0' ){
                    HCWarning( USAGE );
                    return( -1 );
                } else {
                    quiet = 1;
                }
            }
        }
    }

    SetQuiet( quiet );


    //  Parse the given filename.

    char    path[_MAX_PATH];
    char    drive[_MAX_DRIVE];
    char    dir[_MAX_DIR];
    char    fname[_MAX_FNAME];
    char    ext[_MAX_EXT];

    _fullpath( path, pfilename, _MAX_PATH );
    _splitpath( path, drive, dir, fname, ext );

    if( stricmp( ext, PhExt ) == 0 || stricmp( ext, HlpExt ) == 0 ) {
        HCWarning( BAD_EXT );
        return( -1 );
    }
    if( ext[0] == '\0' ){
        _makepath( path, drive, dir, fname, HpjExt );
    }

    char    destpath[_MAX_PATH];
    _makepath( destpath, drive, dir, fname, HlpExt );

    InFile  input( path );
    if( input.bad() ) {
        HCWarning( FILE_ERR, pfilename );
        return( -1 );
    }


    //  Set up and start the help compiler.

    try {
        HFSDirectory    helpfile( destpath );
        HFFont          fontfile( &helpfile );
        HFContext       contfile( &helpfile );
        HFSystem        sysfile( &helpfile, &contfile );
        HFCtxomap       ctxfile( &helpfile, &contfile );
        HFTtlbtree      ttlfile( &helpfile );
        HFKwbtree       keyfile( &helpfile );
        HFBitmaps       bitfiles( &helpfile );

        Pointers        my_files = {
                            NULL,
                            NULL,
                            &sysfile,
                            &fontfile,
                            &contfile,
                            &ctxfile,
                            &keyfile,
                            &ttlfile,
                            &bitfiles,
        };

        if( stricmp( ext, RtfExt ) == 0 ) {
            my_files._topFile = new HFTopic( &helpfile );
            RTFparser   rtfhandler( &my_files, &input );
            rtfhandler.Go();
        } else {
            HPJReader   projfile( &helpfile, &my_files, &input );
            projfile.parseFile();
        }

        helpfile.dump();
        if( my_files._topFile != NULL ) {
            delete my_files._topFile;
        }
        if( my_files._phrFile != NULL ) {
            delete my_files._phrFile;
        }
    }
    catch( HCException ) {
        HCWarning( PROGRAM_STOPPED );
        return( -1 );
    }
    return( 0 );
}
Example #25
0
int genkmarkers(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
genkmarkers(int argc, char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file
int Rslt = 0;   			// function result code >= 0 represents success, < 0 on failure

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	if(gExperimentID > 0)
		{
		int ParamID;

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

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

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

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

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

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

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

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


#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	gStopWatch.Start();
	Rslt = LocMarkers((etPMode)PMode,KMerLen,PrefixLen,SuffixLen,MinWithPrefix,MinHamming,szCultivarName,NumPartialCultivars,pszPartialCultivars,szSfxPseudoGenome,szMarkerFile,szMarkerReadsFile,NumThreads);
	Rslt = Rslt >=0 ? 0 : 1;
	if(gExperimentID > 0)
		{
		if(gProcessingID)
			gSQLiteSummaries.EndProcessing(gProcessingID,Rslt);
		gSQLiteSummaries.EndExperiment(gExperimentID);
		}
	gStopWatch.Stop();
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	return(Rslt);
	}
else
	{
    printf("\n%s %s %s, Version %s\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	return(1);
	}
return 0;
}
Example #26
0
/*
 * AddDataToEXE - tack data to end of an EXE
 */
void AddDataToEXE( char *exe, char *buffer, unsigned len, unsigned long tocopy )
{
    int                 h, i, newh;
    char                buff[sizeof( MAGIC_COOKIE ) + sizeof( bind_size )];
    long                shift;
    unsigned            taillen;
    char                *copy;
    char                foo[128];
    char                drive[_MAX_DRIVE], dir[_MAX_DIR];

    /*
     * get files
     */
    copy = malloc( COPY_SIZE );
    if( copy == NULL ) {
        Abort( "Out of Memory" );
    }
    h = open( exe, O_RDWR | O_BINARY );
    if( h == -1 ) {
        Abort( "Fatal error opening \"%s\"", exe );
    }
    _splitpath( exe, drive, dir, NULL, NULL );
    _makepath( foo, drive, dir, "__cge__", ".exe" );
    newh = open( foo, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, PMODE_RWX );
    if( newh == -1 ) {
        Abort( "Fatal error opening \"%s\"", foo );
    }

    /*
     * get trailer
     */
    i = lseek( h, -((long)sizeof( buff )), SEEK_END );
    if( i == -1 ) {
        Abort( "Initial seek error on \"%s\"", exe );
    }
    i = read( h, buff, sizeof( buff ) );
    if( i == -1 ) {
        Abort( "Read error on \"%s\"", exe );
    }

    /*
     * if trailer is one of ours, then set back to overwrite data;
     * else just set to write at end of file
     */
    if( strcmp( buff, MAGIC_COOKIE ) ) {
        if( sflag ) {
            Abort( "\"%s\" does not contain configuration data!", exe );
        }
    } else {
        taillen = *((bind_size *)&(buff[sizeof( MAGIC_COOKIE )]));
        shift = (long)-((long)taillen + (long)sizeof( buff ));
        tocopy += shift;
    }
    i = lseek( h, 0, SEEK_SET );
    if( i ) {
        Abort( "Seek error on \"%s\"", exe );
    }

    /*
     * copy crap
     */
    while( tocopy > 0 ) {
        if( tocopy > (unsigned long)COPY_SIZE ) {
            i = read( h, copy, COPY_SIZE );
            if( i != COPY_SIZE ) {
                Abort( "Read error on \"%s\"", exe );
            }
            i = write( newh, copy, COPY_SIZE );
            if( i != COPY_SIZE ) {
                Abort( "Write error on \"%s\"", foo );
            }
            tocopy -= (unsigned long)COPY_SIZE;
        } else {
            i = read( h, copy, (unsigned int)tocopy );
            if( i != (int)tocopy ) {
                Abort( "Read error on \"%s\"", exe );
            }
            i = write( newh, copy, (unsigned int)tocopy );
            if( i != (int)tocopy ) {
                Abort( "Write error on \"%s\"", foo );
            }
            tocopy = 0;
        }
    }
    close( h );

    /*
     * write out data and new trailer
     */
    if( !sflag ) {
        i = write( newh, buffer, len );
        if( i != (int)len ) {
            Abort( "write 1 error on \"%s\"", exe );
        }
        strcpy( buff, MAGIC_COOKIE );
        *((bind_size *)&(buff[sizeof( MAGIC_COOKIE )])) = len;
        i = write( newh, buff, sizeof( buff ) );
        if( i != sizeof( buff ) ) {
            Abort( "write 2 error on \"%s\"", exe );
        }
    }
    close( newh );
    remove( exe );
    rename( foo, exe );

} /* AddDataToEXE */
Example #27
0
LPCSTR PlugSetPath(LPSTR pBuff, LPCSTR prefix, LPCSTR FileName, LPCSTR defpath)
  {
  char newname[_MAX_PATH];
  char direc[_MAX_DIR], defdir[_MAX_DIR], tmpdir[_MAX_DIR];
  char fname[_MAX_FNAME];
  char ftype[_MAX_EXT];
#if !defined(UNIX) && !defined(UNIV_LINUX)
  char drive[_MAX_DRIVE], defdrv[_MAX_DRIVE];
#else
  char *drive = NULL, *defdrv = NULL;
#endif

  if (!strncmp(FileName, "//", 2) || !strncmp(FileName, "\\\\", 2)) {
    strcpy(pBuff, FileName);       // Remote file
    return pBuff;
    } // endif

  if (PlugIsAbsolutePath(FileName))
  {
    strcpy(pBuff, FileName); // FileName includes absolute path
    return pBuff;
  } // endif
  
#if !defined(WIN32)
  if (*FileName == '~') {
    if (_fullpath(pBuff, FileName, _MAX_PATH)) {
      if (trace > 1)
        htrc("pbuff='%s'\n", pBuff);

     return pBuff;
    } else
      return FileName;     // Error, return unchanged name
      
    } // endif FileName  
#endif   // !WIN32
  
  if (prefix && strcmp(prefix, ".") && !PlugIsAbsolutePath(defpath))
  {
    char tmp[_MAX_PATH];
    int len= snprintf(tmp, sizeof(tmp) - 1, "%s%s%s",
                      prefix, defpath, FileName);
    memcpy(pBuff, tmp, (size_t) len);
    pBuff[len]= '\0';
    return pBuff;
  }

  _splitpath(FileName, drive, direc, fname, ftype);

  if (defpath) {
    char c = defpath[strlen(defpath) - 1];

    strcpy(tmpdir, defpath);

    if (c != '/' && c != '\\')
      strcat(tmpdir, "/");

  } else
    strcpy(tmpdir, "./");

  _splitpath(tmpdir, defdrv, defdir, NULL, NULL);

  if (trace > 1) {
    htrc("after _splitpath: FileName=%s\n", FileName);
#if defined(UNIX) || defined(UNIV_LINUX)
    htrc("dir=%s fname=%s ext=%s\n", direc, fname, ftype);
#else
    htrc("drive=%s dir=%s fname=%s ext=%s\n", drive, direc, fname, ftype);
    htrc("defdrv=%s defdir=%s\n", defdrv, defdir);
#endif
    } // endif trace

  if (drive && !*drive)
    strcpy(drive, defdrv);

  switch (*direc) {
    case '\0':
      strcpy(direc, defdir);
      break;
    case '\\':
    case '/':
      break;
    default:
      // This supposes that defdir ends with a SLASH
      strcpy(direc, strcat(defdir, direc));
    } // endswitch

  _makepath(newname, drive, direc, fname, ftype);

  if (trace > 1)
    htrc("newname='%s'\n", newname);

  if (_fullpath(pBuff, newname, _MAX_PATH)) {
    if (trace > 1)
      htrc("pbuff='%s'\n", pBuff);

    return pBuff;
  } else
    return FileName;     // Error, return unchanged name

  } // end of PlugSetPath
Example #28
0
int main( int argc, char *argv[] )
{
    char                *buff = NULL;
    char                *buff2, *buff3;
    char                *buffn, *buffs;
    int                 i, bytes, j, k, sl;
    FILE                *f;
    struct stat         fs;
    char                drive[_MAX_DRIVE], dir[_MAX_DIR];
    char                fname[_MAX_FNAME], ext[_MAX_EXT];
    char                path[_MAX_PATH];
    char                tmppath[_MAX_PATH];
    char                tmpfname[_MAX_FNAME], tmpext[_MAX_EXT];
    unsigned            cnt;
    unsigned            lines;
    bind_size           *index;
    bind_size           *entries;

    j = argc - 1;
    while( j > 0 ) {
        if( argv[j][0] == '/' || argv[j][0] == '-' ) {
            sl = strlen( argv[j] );
            for( i = 1; i < sl; i++ ) {
                switch( argv[j][i] ) {
                case 's': sflag = TRUE; break;
                case 'q': qflag = TRUE; break;
                case 'd':
                    bindfile = &argv[j][i + 1];
                    i = sl;
                    break;
                case '?':
                    Banner();
                    Usage( NULL );
                default:
                    Banner();
                    Usage( "Invalid option" );
                }
            }
            for( i = j; i < argc; i++ ) {
                argv[i]= argv[i + 1];
            }
            argc--;
        }
        j--;
    }
    Banner();

    /*
     * now, check for null file name
     */
    if( argc < 2 ) {
        Usage( "No executable to bind" );
    }
    _splitpath( argv[1], drive, dir, fname, ext );
    if( ext[0] == 0 ) {
        _makepath( path, drive, dir, fname, ".exe" );
    } else {
        strcpy( path, argv[1] );
    }
    if( stat( path, &fs ) == -1 ) {
        Abort( "Could not find executable \"%s\"", path );
    }

    cnt = 0;
    if( !sflag ) {

        buff = MyAlloc( 65000 );
        buff2 = MyAlloc( 32000 );
        buff3 = MyAlloc( MAX_LINE_LEN );

        /*
         * read in all data files
         */
        MyPrintf( "Getting data files from" );
        f = GetFromEnvAndOpen( bindfile );
        MyPrintf( "\n" );
        if( f == NULL ) {
            Abort( "Could not open %s", bindfile );
        }
        while( fgets( buff3, MAX_LINE_LEN, f ) != NULL ) {
            for( i = strlen( buff3 ); i && isWSorCtrlZ( buff3[i - 1] ); --i ) {
                buff3[i - 1] = '\0';
            }
            if( buff3[0] == '\0' ) {
                continue;
            }
            RemoveLeadingSpaces( buff3 );
            if( buff3[0] == '#' ) {
                continue;
            }
            dats[FileCount] = MyAlloc( strlen( buff3 ) + 1 );
            strcpy( dats[FileCount], buff3 );
            FileCount++;
            if( FileCount >= MAX_DATA_FILES ) {
                Abort( "Too many files to bind!" );
            }
        }
        fclose( f );
        index = MyAlloc( FileCount * sizeof( bind_size ) );
        entries = MyAlloc( FileCount * sizeof( bind_size ) );

        buffn = buff;

        *(bind_size *)buffn = FileCount;
        buffn += sizeof( bind_size );
        cnt += sizeof( bind_size );
        buffs = buffn;
        buffn += sizeof( bind_size );
        cnt += sizeof( bind_size );
        k = 0;
        for( i = 0; i < FileCount; i++ ) {
//          j = strlen( dats[i] ) + 1;
//          memcpy( buffn, dats[i], j );
            _splitpath( dats[i], NULL, NULL, tmpfname, tmpext );
            _makepath( tmppath, NULL, NULL, tmpfname, tmpext );
            j = strlen( tmppath ) + 1;
            memcpy( buffn, tmppath, j );
            buffn += j;
            cnt += j;
            k += j;
        }
        *(bind_size *)buffs = k + 1;  /* size of token list */
        *buffn = 0;                             /* trailing zero */
        buffn++;
        cnt++;
        buffs = buffn;
        buffn += FileCount * ( sizeof( bind_size ) + sizeof( bind_size ) );
        cnt += FileCount * ( sizeof( bind_size ) + sizeof( bind_size ) );

        for( j = 0; j < FileCount; j++ ) {
            MyPrintf( "Loading" );
            f = GetFromEnvAndOpen( dats[j] );
            if( f == NULL ) {
                Abort( "\nLoad of %s failed!", dats[j] );
            }
            setvbuf( f, buff2, _IOFBF, 32000 );
            bytes = lines = 0;
            index[j] = cnt;
            while( fgets( buff3, MAX_LINE_LEN, f ) != NULL ) {
                unsigned    len;

                for( len = strlen( buff3 ); len && isWSorCtrlZ( buff3[len - 1] ); --len )
                    buff3[len - 1] = '\0';
                if( buff3[0] == '\0' ) {
                    continue;
                }
                RemoveLeadingSpaces( buff3 );
                if( buff3[0] == '#' ) {
                    continue;
                }
                len = strlen( buff3 );
                *buffn = (char)len;
                buffn++;
                memcpy( buffn, buff3, len );
                buffn += len;
                cnt += len + 1;
                lines++;
                bytes += len;
            }
            fclose( f );
            entries[j] = lines;
            MyPrintf( "Added %d lines (%d bytes)\n", lines, bytes );
        }
        memcpy( buffs, index, FileCount * sizeof( bind_size ) );
        buffs += FileCount * sizeof( bind_size );
        memcpy( buffs, entries, FileCount * sizeof( bind_size ) );
    }

    AddDataToEXE( path, buff, cnt, fs.st_size );
    if( !sflag ) {
        MyPrintf( "Added %d bytes to \"%s\"\n", cnt, path );
    } else {
        MyPrintf( "\"%s\" has been stripped of configuration information\n", path );
    }
    return( 0 );

} /* main */
Example #29
0
static int loadPlugin(void* libraryFile, const char* fileName, const char* pluginPath, void* param)
{
    Library* plugin;
    PluginHandle* handle;
    void (*initializer)(void);
    filename_t name;
    pluginid_t plugId;

    DENG_UNUSED(libraryFile); // this is not C++...
    DENG_UNUSED(param);

    DENG_ASSERT(fileName && fileName[0]);
    DENG_ASSERT(pluginPath && pluginPath[0]);

    if(strcasestr("/bin/audio_", pluginPath))
    {
        // Do not touch audio plugins at this point.
        return true;
    }

    plugin = Library_New(pluginPath);
    if(!plugin)
    {
        Con_Message("  loadPlugin: Did not load \"%s\" (%s).", pluginPath, Library_LastError());
        return 0; // Continue iteration.
    }

    if(!strcmp(Library_Type(plugin), "deng-plugin/audio"))
    {
        // Audio plugins will be loaded later, on demand.
        Library_Delete(plugin);
        return 0;
    }

    initializer = de::function_cast<void (*)()>(Library_Symbol(plugin, "DP_Initialize"));
    if(!initializer)
    {
        DEBUG_Message(("  loadPlugin: \"%s\" does not export entrypoint DP_Initialize, ignoring.\n", pluginPath));

        // Clearly not a Doomsday plugin.
        Library_Delete(plugin);
        return 0; // Continue iteration.
    }

    // Assign a handle and ID to the plugin.
    handle = findFirstUnusedPluginHandle();
    plugId = handle - hInstPlug + 1;
    if(!handle)
    {
        DEBUG_Message(("  loadPlugin: Failed acquiring new handle for \"%s\", ignoring.\n", pluginPath));

        Library_Delete(plugin);
        return 0; // Continue iteration.
    }

    // This seems to be a Doomsday plugin.
    _splitpath(pluginPath, NULL, NULL, name, NULL);
    Con_Message("  (id:%i) %s", plugId, name);

    *handle = plugin;

    DD_SetActivePluginId(plugId);
    initializer();
    DD_SetActivePluginId(0);

    return 0; // Continue iteration.
}
Example #30
0
xi_file_re xi_pathname_split(xi_pathname_t *pathinfo, const xchar *path) {
	_splitpath(path, pathinfo->drive, pathinfo->dirname, pathinfo->filename,
			pathinfo->suffix);
	return XI_FILE_RV_OK;
}