Exemple #1
0
int
getdtablesize (void)
{
  if (dtablesize == 0)
    {
      /* We are looking for the number N such that the valid file descriptors
         are 0..N-1.  It can be obtained through a loop as follows:
           {
             int fd;
             for (fd = 3; fd < 65536; fd++)
               if (dup2 (0, fd) == -1)
                 break;
             return fd;
           }
         On Windows XP, the result is 2048.
         The drawback of this loop is that it allocates memory for a libc
         internal array that is never freed.

         The number N can also be obtained as the upper bound for
         _getmaxstdio ().  _getmaxstdio () returns the maximum number of open
         FILE objects.  The sanity check in _setmaxstdio reveals the maximum
         number of file descriptors.  This too allocates memory, but it is
         freed when we call _setmaxstdio with the original value.  */
      int orig_max_stdio = _getmaxstdio ();
      unsigned int bound;
      for (bound = 0x10000; _setmaxstdio (bound) < 0; bound = bound / 2)
        ;
      _setmaxstdio (orig_max_stdio);
      dtablesize = bound;
    }
  return dtablesize;
}
Exemple #2
0
void
main_pre_dc_init( int, char*[] )
{
	DC_Skip_Auth_Init();
	DC_Skip_Core_Init();
#ifdef WIN32
	_setmaxstdio(2048);
#endif

		// Convert the DAGMan log file name to an absolute path if it's
		// not one already, so that we'll log things to the right file
		// if we change to a different directory.
	const char *	logFile = GetEnv( "_CONDOR_DAGMAN_LOG" );
	if ( logFile && !fullpath( logFile ) ) {
		MyString	currentDir;
		if ( condor_getcwd( currentDir ) ) {
			MyString newLogFile(currentDir);
			newLogFile += DIR_DELIM_STRING;
			newLogFile += logFile;
			SetEnv( "_CONDOR_DAGMAN_LOG", newLogFile.Value() );
		} else {
			debug_printf( DEBUG_NORMAL, "ERROR: unable to get cwd: %d, %s\n",
					errno, strerror(errno) );
		}
	}
}
MONGO_INITIALIZER(Behaviors_Win32)(InitializerContext*) {
    // do not display dialog on abort()
    _set_abort_behavior(0, _CALL_REPORTFAULT | _WRITE_ABORT_MSG);

    // hook the C runtime's error display
    _CrtSetReportHook(crtDebugCallback);

    if (_setmaxstdio(2048) == -1) {
        warning() << "Failed to increase max open files limit from default of 512 to 2048";
    }

    // Let's try to set minimum Windows Kernel quantum length to smallest viable timer resolution in
    // order to allow sleepmillis() to support waiting periods below Windows default quantum length
    // (which can vary per Windows version)
    // See https://msdn.microsoft.com/en-us/library/windows/desktop/dd743626(v=vs.85).aspx
    TIMECAPS tc;
    int targetResolution = 1;
    int timerResolution;

    if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
        warning() << "Failed to read timer resolution range.";
        if (timeBeginPeriod(1) != TIMERR_NOERROR) {
            warning() << "Failed to set minimum timer resolution to 1 millisecond.";
        }
    } else {
        timerResolution =
            std::min(std::max(int(tc.wPeriodMin), targetResolution), int(tc.wPeriodMax));
        invariant(timeBeginPeriod(timerResolution) == TIMERR_NOERROR);
    }

    return Status::OK();
}
Exemple #4
0
static PyObject *
winutil_set_max_stdio(PyObject *self, PyObject *args) {
    int num = 0;
    if (!PyArg_ParseTuple(args, "i", &num)) return NULL;
    if (_setmaxstdio(num) == -1) return PyErr_SetFromErrno(PyExc_ValueError);
    Py_RETURN_NONE;
}
Exemple #5
0
int initialiseWindows(const TRI_win_initialise_e initialiseWhat, const char* data) {


  // ............................................................................
  // The data is used to transport information from the calling function to here
  // it may be NULL (and will be in most cases)
  // ............................................................................

  switch (initialiseWhat) {

    case TRI_WIN_INITIAL_SET_DEBUG_FLAG: {
      _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF)|_CRTDBG_CHECK_ALWAYS_DF);    
      return 0;
    }

    // ...........................................................................
    // Assign a handler for invalid handles 
    // ...........................................................................

    case TRI_WIN_INITIAL_SET_INVALID_HANLE_HANDLER: { 
      newInvalidHandleHandler = InvalidParameterHandler;
      oldInvalidHandleHandler = _set_invalid_parameter_handler(newInvalidHandleHandler);
      return 0;
    }

    case TRI_WIN_INITIAL_SET_MAX_STD_IO: {
      int* newMax = (int*)(data);
      int result = _setmaxstdio(*newMax);
      if (result != *newMax) {
        return -1;
      }
      return 0;  
    }

    case TRI_WIN_INITIAL_WSASTARTUP_FUNCTION_CALL: {
      int errorCode;
      WSADATA wsaData;
      WORD wVersionRequested = MAKEWORD(2,2);
      errorCode = WSAStartup(wVersionRequested, &wsaData);
      if (errorCode != 0) {
        LOG_ERROR("Could not find a usuable Winsock DLL. WSAStartup returned an error.");
        return -1;
      }
      if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
        LOG_ERROR("Could not find a usuable Winsock DLL. WSAStartup did not return version 2.2.");
        WSACleanup();
        return -1;
      }   
      return 0;
    }

    default: {
      LOG_ERROR("Invalid windows initialisation called");
      return -1;
    }
  }

  return -1;

}
void runonce() {
#ifdef _MSC_VER
	if( ! s_hasRunOnceRun ) {
		_setmaxstdio( 2048 );
		s_hasRunOnceRun = true;
	}
#endif
}
Exemple #7
0
void qsInit(void *module)
{
	if (!qsInitialized) {

#if defined(_WINDOWS) || defined(WIN32)
		system("del /q /f __db.??? >nul 2>nul");
		_setmaxstdio(2048);
		_set_sbh_threshold(0);
#endif
		qsInitialized = true;

	}
}
Exemple #8
0
static int
pyuv_setmaxstdio(void)
{
    if (_setmaxstdio(PYUV_MAXSTDIO) != PYUV_MAXSTDIO) {
        if (errno) {
            PyErr_SetFromErrno(PyExc_WindowsError);
        }
        else {
            PyErr_SetString(PyExc_WindowsError, "_setmaxstdio failed");
        }
        return -1;
    }
    return 0;
}
Exemple #9
0
/* set a new maximum for the number of simultaneously open files.
 * if return = -1 error occured
 */
int
pdc_set_maxfilehandles(pdc_core *pdc, int maxfps)
{
    const char *stemp = pdc_errprintf(pdc, "%d", maxfps);

    if (maxfps < _IOB_ENTRIES)
        pdc_error(pdc, PDC_E_IO_TOOFEW_REQFILEHDLS, stemp,
                  pdc_errprintf(pdc, "%d", _IOB_ENTRIES), 0, 0);

    if (maxfps > PDC_MAXFILEHANDLES)
        pdc_error(pdc, PDC_E_IO_TOOMANY_REQFILEHDLS, stemp,
                  pdc_errprintf(pdc, "%d", PDC_MAXFILEHANDLES), 0, 0);

    return _setmaxstdio(maxfps);
}
Exemple #10
0
main (int ac, string *av)
#endif
{
#  ifdef __EMX__
    _wildcard(&ac, &av);
    _response(&ac, &av);
#  endif

#  ifdef WIN32
#    ifdef _MSC_VER
    _set_invalid_parameter_handler(myInvalidParameterHandler);
#    endif
    av[0] = kpse_program_basename (av[0]);
    _setmaxstdio(2048);
/*
    We choose to crash for fatal errors:

    SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
*/
    setmode(fileno(stdin), _O_BINARY);
#  endif

    lua_initialize(ac, av);

#  ifdef WIN32
    if (ac > 1) {
        char *pp;
        if ((strlen(av[ac-1]) > 2) && isalpha(av[ac-1][0]) && (av[ac-1][1] == ':') && (av[ac-1][2] == '\\')) {
            for (pp=av[ac-1]+2; *pp; pp++) {
            if (IS_KANJI(pp)) {
                pp++;
                continue;
            }
            if (*pp == '\\')
                *pp = '/';
            }
        }
    }
#  endif

    /*
        Call the real main program.
    */
    main_body();

    return EXIT_SUCCESS;
}
Exemple #11
0
static inline int
_setmaxstdio_nothrow (int newmax)
{
  int result;

  TRY_MSVC_INVAL
    {
      result = _setmaxstdio (newmax);
    }
  CATCH_MSVC_INVAL
    {
      result = -1;
    }
  DONE_MSVC_INVAL;

  return result;
}
Exemple #12
0
/* The entry point for all the programs except TeX and Metafont, which
   have more to do.  We just have to set up the command line.  web2c
   transforms Pascal's main block into a procedure `main_body'.  */
int
main (int  ac,  string* av)
{
#ifdef __EMX__
  _wildcard (&ac, &av);
  _response (&ac, &av);
#endif

#ifdef WIN32
  _setmaxstdio(2048);
#endif

  argc = ac;
  argv = av;
  mainbody ();
  return EXIT_SUCCESS;
}
Exemple #13
0
SXE_RETURN
sxe_set_file_limit(const unsigned limit)
{
    SXE_RETURN result = SXE_RETURN_ERROR_INTERNAL;

#ifndef _WIN32
    struct rlimit rt;
    rt.rlim_max = limit;
    rt.rlim_cur = limit;
#endif

    if
#ifdef _WIN32
       (_setmaxstdio(limit) == -1)
#else
       (setrlimit(RLIMIT_NOFILE, &rt) == -1)
#endif
    {
        SXEL91("Failed to set file limit to '%u'", limit);
        goto SXE_ERROR_OUT; /* COVERAGE EXCLUSION - TODO: WIN32 COVERAGE */
    }
Exemple #14
0
isc_result_t
isc_resource_setlimit(isc_resource_t resource, isc_resourcevalue_t value) {
	isc_resourcevalue_t rlim_value;
	int wresult;

	if (resource != isc_resource_openfiles)
		return (ISC_R_NOTIMPLEMENTED);


	if (value == ISC_RESOURCE_UNLIMITED)
		rlim_value = WIN32_MAX_OPEN_FILES;
	else
		rlim_value = min(value, WIN32_MAX_OPEN_FILES);

	wresult = _setmaxstdio((int) rlim_value);

	if (wresult > 0)
		return (ISC_R_SUCCESS);
	else
		return (isc__errno2result(errno));
}
Exemple #15
0
/** Inits the File Module
 */
orxSTATUS orxFASTCALL orxFile_Init()
{
  orxSTATUS eResult = orxSTATUS_SUCCESS;

  /* Was not already initialized? */
  if(!(sstFile.u32Flags & orxFILE_KU32_STATIC_FLAG_READY))
  {
    /* Cleans static controller */
    orxMemory_Zero(&sstFile, sizeof(orxFILE_STATIC));

#ifdef __orxWINDOWS__

    /* Increases C runtime stdio limit */
    _setmaxstdio(2048);

#endif /* __orxWINDOWS__ */

    /* Updates status */
    sstFile.u32Flags |= orxFILE_KU32_STATIC_FLAG_READY;
  }

  /* Done! */
  return eResult;
}
Exemple #16
0
int
vips_init( const char *argv0 )
{
	extern GType vips_system_get_type( void );

	static gboolean started = FALSE;
	static gboolean done = FALSE;
	char *prgname;
	const char *prefix;
	const char *libdir;
	char name[256];

	/* Two stage done handling: 'done' means we've completed, 'started'
	 * means we're currently initialising. Use this to prevent recursive
	 * invocation.
	 */
	if( done )
		/* Called more than once, we succeeded, just return OK.
		 */
		return( 0 );
	if( started ) 
		/* Recursive invocation, something has broken horribly.
		 * Hopefully the first init will handle it.
		 */
		return( 0 );
	started = TRUE;

#ifdef OS_WIN32
	/* Windows has a limit of 512 files open at once for the fopen() family
	 * of functions, and 2048 for the _open() family. This raises the limit
	 * of fopen() to the same level as _open().
	 *
	 * It will not go any higher than this, unfortunately.  
	 */
	(void) _setmaxstdio( 2048 );
#endif /*OS_WIN32*/

#ifdef HAVE_TYPE_INIT
	/* Before glib 2.36 you have to call this on startup.
	 */
	g_type_init();
#endif /*HAVE_TYPE_INIT*/

	/* Older glibs need this.
	 */
#ifndef HAVE_THREAD_NEW
	if( !g_thread_supported() ) 
		g_thread_init( NULL );
#endif 

	vips__threadpool_init();
	vips__buffer_init();

	/* This does an unsynchronised static hash table init on first call --
	 * we have to make sure we do this single-threaded. See: 
	 * https://github.com/openslide/openslide/issues/161
	 */
	(void) g_get_language_names(); 

	if( !vips__global_lock )
		vips__global_lock = vips_g_mutex_new();

	VIPS_SETSTR( vips__argv0, argv0 );

	prgname = g_path_get_basename( argv0 );
	g_set_prgname( prgname );
	g_free( prgname );

	vips__thread_profile_attach( "main" );

	/* We can't do VIPS_GATE_START() until command-line processing
	 * happens, since vips__thread_profile may not be set yet. Call
	 * directly. 
	 */
	vips__thread_gate_start( "init: main" ); 
	vips__thread_gate_start( "init: startup" ); 

	/* Try to discover our prefix. 
	 */
	if( !(prefix = vips_guess_prefix( argv0, "VIPSHOME" )) || 
		!(libdir = vips_guess_libdir( argv0, "VIPSHOME" )) ) 
		return( -1 );

	/* Get i18n .mo files from $VIPSHOME/share/locale/.
	 */
	vips_snprintf( name, 256,
		"%s" G_DIR_SEPARATOR_S "share" G_DIR_SEPARATOR_S "locale",
		prefix );
	bindtextdomain( GETTEXT_PACKAGE, name );
	bind_textdomain_codeset( GETTEXT_PACKAGE, "UTF-8" );

	/* Default various settings from env.
	 */
	if( g_getenv( "VIPS_INFO" ) || 
		g_getenv( "IM_INFO" ) ) 
		vips_info_set( TRUE );
	if( g_getenv( "VIPS_TRACE" ) )
		vips_cache_set_trace( TRUE );

	/* Register base vips types.
	 */
	(void) vips_image_get_type();
	(void) vips_region_get_type();
	vips__meta_init_types();
	vips__interpolate_init();
	im__format_init();

	/* Start up operator cache.
	 */
	vips__cache_init();

	/* Start up packages.
	 */
	(void) vips_system_get_type();
	vips_arithmetic_operation_init();
	vips_conversion_operation_init();
	vips_create_operation_init();
	vips_foreign_operation_init();
	vips_resample_operation_init();
	vips_colour_operation_init();
	vips_histogram_operation_init();
	vips_convolution_operation_init();
	vips_freqfilt_operation_init();
	vips_morphology_operation_init();
	vips_draw_operation_init();
	vips_mosaicing_operation_init();

	/* Load any vips8 plugins from the vips libdir. Keep going, even if
	 * some plugins fail to load. 
	 */
	(void) vips_load_plugins( "%s/vips-plugins-%d.%d", 
		libdir, VIPS_MAJOR_VERSION, VIPS_MINOR_VERSION );

	/* Load up any vips7 plugins in the vips libdir. We don't error on 
	 * failure, it's too annoying to have VIPS refuse to start because of 
	 * a broken plugin.
	 */
	if( im_load_plugins( "%s/vips-%d.%d", 
		libdir, VIPS_MAJOR_VERSION, VIPS_MINOR_VERSION ) ) {
		vips_warn( "vips_init", "%s", vips_error_buffer() );
		vips_error_clear();
	}

	/* Also load from libdir. This is old and slightly broken behaviour
	 * :-( kept for back compat convenience.
	 */
	if( im_load_plugins( "%s", libdir ) ) {
		vips_warn( "vips_init", "%s", vips_error_buffer() );
		vips_error_clear();
	}

	/* Get the run-time compiler going.
	 */
	vips_vector_init();

#ifdef HAVE_GSF
	/* Use this for structured file write.
	 */
	gsf_init();
#endif /*HAVE_GSF*/

	/* Register vips_shutdown(). This may well not get called and many
	 * platforms don't support it anyway.
	 */
#ifdef HAVE_ATEXIT
	atexit( vips_shutdown );
#endif /*HAVE_ATEXIT*/

#ifdef DEBUG_LEAK
	vips__image_pixels_quark = 
		g_quark_from_static_string( "vips-image-pixels" ); 
#endif /*DEBUG_LEAK*/

	done = TRUE;

	vips__thread_gate_stop( "init: startup" ); 

	return( 0 );
}
Exemple #17
0
void testMaxHandlersOfFiles()
{
    printf( "maxstdio: %d\n", _getmaxstdio());
    _setmaxstdio(2048);
    printf( "maxstdio: %d\n", _getmaxstdio());
}
Exemple #18
0
int main(int argc, char **argv)
{
    int i,j,cc=0,startpagenum=-1,ecount=0,chkopt=1;
    const char *envbuff;
    UVersionInfo icuVersion;
    char icu_version[U_MAX_VERSION_STRING_LENGTH] = "";

#ifdef WIN32
    char **av;
    int ac;
    _setmaxstdio(2048);
#endif
    kpse_set_program_name(argv[0], "upmendex");

#ifdef WIN32
    file_system_codepage = CP_UTF8;
    is_cp932_system = 0;
    if (get_command_line_args_utf8("utf-8", &ac, &av)) {
        argv = av;
        argc = ac;
    }
#endif

    kp_ist.var_name = "INDEXSTYLE";
    kp_ist.path = DEFAULT_INDEXSTYLES; /* default path. */
    kp_ist.suffix = "ist";
    KP_entry_filetype(&kp_ist);
    kp_dict.var_name = "INDEXDICTIONARY";
    kp_dict.path = DEFAULT_INDEXDICTS; /* default path */
    kp_dict.suffix = "dict";
    KP_entry_filetype(&kp_dict);

    /*   check options   */

    for (i=1,j=0; i<argc && j<256; i++) {
        if ((argv[i][0]=='-')&&(strlen(argv[i])>=2)&&chkopt) {
            switch (argv[i][1]) {
            case 'c':
                bcomp=1;
                break;

            case 'd':
                if ((argv[i][2]=='\0')&&(i+1<argc)) {
                    dicfile=xstrdup(argv[++i]);
                }
                else {
                    dicfile=xstrdup(&argv[i][2]);
                }
                break;

            case 'f':
                force=1;
                break;

            case 'g':
                gflg=1;
                break;

            case 'i':
                fsti=1;
                break;

            case 'l':
                lorder=1;
                break;

            case 'o':
                if ((argv[i][2]=='\0')&&(i+1<argc)) {
                    indfile=xstrdup(argv[++i]);
                }
                else {
                    indfile=xstrdup(&argv[i][2]);
                }
                break;

            case 'p':
                if ((argv[i][2]=='\0')&&(i+1<argc)) {
                    i++;
                    if (strcmp(argv[i],"any")==0) fpage=2;
                    else if (strcmp(argv[i],"odd")==0) fpage=3;
                    else if (strcmp(argv[i],"even")==0) fpage=4;
                    else {
                        fpage=1;
                        startpagenum=atoi(argv[i]);
                    }
                }
                else {
                    if (strcmp(&argv[i][2],"any")==0) fpage=2;
                    else if (strcmp(&argv[i][2],"odd")==0) fpage=3;
                    else if (strcmp(&argv[i][2],"even")==0) fpage=4;
                    else {
                        fpage=1;
                        startpagenum=atoi(&argv[i][2]);
                    }
                }
                break;

            case 'q':
                verb=0;
                break;

            case 't':
                if ((argv[i][2]=='\0')&&(i+1<argc)) {
                    logfile=xstrdup(argv[++i]);
                }
                else {
                    logfile=xstrdup(&argv[i][2]);
                }
                break;

            case 'r':
                prange=0;
                break;

            case 's':
                if ((argv[i][2]=='\0')&&(i+1<argc)) {
                    styfile=xstrdup(argv[++i]);
                }
                else {
                    styfile=xstrdup(&argv[i][2]);
                }
                break;

            case 'v':
                debug=1;
                break;

            case '-':
                if (strlen(argv[i])==2) chkopt=0;
                if (strcmp(argv[i],"--help")!=0) break;

            default:
                u_getVersion(icuVersion);
                u_versionToString(icuVersion, icu_version);
                fprintf(stderr,"upmendex - index processor, %s (%s).\n",VERSION, TL_VERSION);
                fprintf(stderr," Copyright 2009 ASCII MEDIA WORKS, 2015-2016 TANAKA Takuji\n");
                fprintf(stderr," using ICU version %s\n",icu_version);
                fprintf(stderr,"usage:\n");
                fprintf(stderr,"%% upmendex [-ilqrcgf] [-s sty] [-d dic] [-o ind] [-t log] [-p no] [--] [idx0 idx1 ...]\n");
                fprintf(stderr,"options:\n");
                fprintf(stderr,"-i      use stdin as the input file.\n");
                fprintf(stderr,"-l      use letter ordering.\n");
                fprintf(stderr,"-q      quiet mode.\n");
                fprintf(stderr,"-r      disable implicit page formation.\n");
                fprintf(stderr,"-c      compress blanks. (ignore leading and trailing blanks.)\n");
                fprintf(stderr,"-g      make Japanese index head <%s>.\n", AKASATANAutf8);
                fprintf(stderr,"-f      force to output unknown scripts.\n");
                fprintf(stderr,"-s sty  take sty as style file.\n");
                fprintf(stderr,"-d dic  take dic as dictionary file.\n");
                fprintf(stderr,"-o ind  take ind as the output index file.\n");
                fprintf(stderr,"-t log  take log as the error log file.\n");
                fprintf(stderr,"-p no   set the starting page number of index.\n");
                fprintf(stderr,"idx...  input files.\n");
                exit(0);
                break;
            }
        }
        else {
            cc=strlen(argv[i]);
            if (cc<4) cc+=4;
            else if (strcmp(&argv[i][cc-4],".idx")) cc+=4;
            idxfile[j]=xmalloc(cc+1);
            strcpy(idxfile[j++],argv[i]);
        }
    }
    idxcount=j+fsti;

    /*   check option errors   */

    if (idxcount==0) idxcount=fsti=1;

    if (styfile==NULL) {
        envbuff=kpse_var_value("INDEXDEFAULTSTYLE");
        if (envbuff!=NULL) {
            styfile=xstrdup(envbuff);
        }
    }

    /*   init hangul tumunja table   */
    u_strcpy(tumunja,GANADA);

    if (styfile!=NULL) styread(styfile);

    if (!indfile &&(idxcount-fsti>0)) {
        indfile=xmalloc(strlen(idxfile[0]+6));
        for (i=strlen(idxfile[0]); i>=0; i--) {
            if (idxfile[0][i]=='.') {
                strncpy(indfile,idxfile[0],i);
                sprintf(&indfile[i],".ind");
                break;
            }
        }
        if (i==-1) sprintf(indfile,"%s.ind",idxfile[0]);
    }

    if (!logfile && (idxcount-fsti > 0)) {
        logfile=xmalloc(strlen(idxfile[0]+6));
        for (i=strlen(idxfile[0]); i>=0; i--) {
            if (idxfile[0][i]=='.') {
                strncpy(logfile,idxfile[0],i);
                sprintf(&logfile[i],".ilg");
                break;
            }
        }
        if (i==-1) sprintf(logfile,"%s.ilg",idxfile[0]);
    }
    if (logfile && kpse_out_name_ok(logfile))
        efp=fopen(logfile,"wb");
    if(efp == NULL) {
        efp=stderr;
        logfile=xstrdup("stderr");
    }
    set_icu_attributes();

    if (strcmp(argv[0],"makeindex")==0) {
        verb_printf(efp,"This is Not `MAKEINDEX\', But `UPMENDEX\' %s (%s).\n",
                    VERSION, TL_VERSION);
    }
    else {
        verb_printf(efp,"This is upmendex %s (%s).\n",
                    VERSION, TL_VERSION);
    }

    /*   init kanatable   */

    initkanatable();

    /*   read dictionary   */

    ecount+=dicread(dicfile);

    switch (letter_head) {
    case 0:
    case 1:
        if (gflg==1) {
            u_strcpy(atama,akasatana);
        }
        else {
            u_strcpy(atama,aiueo);
        }
        break;

    case 2:
        if (gflg==1) {
            u_strcpy(atama,AKASATANA);
        }
        else {
            u_strcpy(atama,AIUEO);
        }
        break;

    default:
        break;
    }

    /*   read idx file   */

    lines=0;
    ecount=0;
    ind=xmalloc(sizeof(struct index));

    for (i=0; i<idxcount-fsti; i++) {
        ecount+=idxread(idxfile[i],lines);
    }
    if (fsti==1) {
        ecount+=idxread(NULL,lines);
    }
    verb_printf(efp,"%d entries accepted, %d rejected.\n",acc,reject);

    if (ecount!=0) {
        verb_printf(efp,"%d errors, written in %s.\n",ecount,logfile);
        lines=0;
    }
    if (lines==0) {
        verb_printf(efp,"Nothing written in output file.\n");
        if (efp!=stderr) fclose(efp);
        exit(255);
    }

    /*   sort index   */

    verb_printf(efp,"Sorting index.");

    scount=0;
    wsort(ind,lines);

    verb_printf(efp,"...done(%d comparisons).\n",scount);

    /*   sort pages   */

    verb_printf(efp,"Sorting pages.");

    scount=0;
    pagesort(ind,lines);

    verb_printf(efp,"...done(%d comparisons).\n",scount);

    /*   get last page   */

    if ((fpage>1)&&(idxcount-fsti>0)) cc=lastpage(idxfile[0]);

    switch (fpage) {
    case 2:
        startpagenum=cc+1;
        break;

    case 3:
        if ((cc+1)%2==0) startpagenum=cc+2;
        else startpagenum=cc+1;
        break;

    case 4:
        if ((cc+1)%2==1) startpagenum=cc+2;
        else startpagenum=cc+1;
        break;

    default:
        break;
    }

    /*   write indfile   */

    verb_printf(efp,"Making index file.");

    indwrite(indfile,ind,startpagenum);

    verb_printf(efp,"...done.\n");

    if (idxcount-fsti==0) indfile=xstrdup("stdout");

    verb_printf(efp,"%d warnings, written in %s.\n",warn,logfile);
    verb_printf(efp,"Output written in %s.\n",indfile);
    if (efp!=stderr) fclose(efp);

    return 0;
}
Exemple #19
0
int
WIN32_Subsystem_Init(int *argc, char ***argv)
{
    WIN32_OS_version = GetOSVersion();
    if ((WIN32_OS_version == _WIN_OS_UNKNOWN) || (WIN32_OS_version == _WIN_OS_WIN32S))
        return 1;
    if (atexit(WIN32_Exit) != 0)
        return 1;
#if USE_WIN32_SERVICE
    if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) {
        char path[512];
        HKEY hndKey;
        if (signal(SIGABRT, WIN32_Abort) == SIG_ERR)
            return 1;
        /* Register the service Handler function */
        svcHandle = RegisterServiceCtrlHandler(WIN32_Service_name, WIN32_svcHandler);
        if (svcHandle == 0)
            return 1;
        /* Set Process work dir to directory cointaining squid.exe */
        GetModuleFileName(NULL, path, 512);
        WIN32_module_name = xstrdup(path);
        path[strlen(path) - 10] = '\0';
        if (SetCurrentDirectory(path) == 0)
            return 1;
        safe_free(ConfigFile);
        /* get config file from Windows Registry */
        if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY, 0, KEY_QUERY_VALUE, &hndKey) == ERROR_SUCCESS) {
            DWORD Type = 0;
            DWORD Size = 0;
            LONG Result;
            Result = RegQueryValueEx(hndKey, CONFIGFILE, NULL, &Type, NULL, &Size);
            if (Result == ERROR_SUCCESS && Size) {
                ConfigFile = xmalloc(Size);
                RegQueryValueEx(hndKey, CONFIGFILE, NULL, &Type, ConfigFile, &Size);
            } else
                ConfigFile = xstrdup(DefaultConfigFile);
            Size = 0;
            Type = 0;
            Result = RegQueryValueEx(hndKey, COMMANDLINE, NULL, &Type, NULL, &Size);
            if (Result == ERROR_SUCCESS && Size) {
                WIN32_Service_Command_Line = xmalloc(Size);
                RegQueryValueEx(hndKey, COMMANDLINE, NULL, &Type, WIN32_Service_Command_Line, &Size);
            } else
                WIN32_Service_Command_Line = xstrdup("");
            RegCloseKey(hndKey);
        } else {
            ConfigFile = xstrdup(DefaultConfigFile);
            WIN32_Service_Command_Line = xstrdup("");
        }
        WIN32_build_argv(WIN32_Service_Command_Line);
        *argc = WIN32_argc;
        *argv = WIN32_argv;
        /* Set Service Status to SERVICE_START_PENDING */
        svcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
        svcStatus.dwCurrentState = SERVICE_START_PENDING;
        svcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
        svcStatus.dwWin32ExitCode = 0;
        svcStatus.dwServiceSpecificExitCode = 0;
        svcStatus.dwCheckPoint = 0;
        svcStatus.dwWaitHint = 10000;
        SetServiceStatus(svcHandle, &svcStatus);
#ifdef _SQUID_MSWIN_
        _setmaxstdio(Squid_MaxFD);
#endif
    }
#endif
#ifdef _SQUID_MSWIN_
    if (Win32SockInit() < 0)
        return 1;
#endif
    return 0;
}
Exemple #20
0
int main(int argc, char* argv[]) {
#ifndef NDEBUG
    // report we are running with all Asserts turned on
    printf("*** Running in debug mode ***\n");
#endif    
#ifdef EXTENDEDOPENFILES
    // enable maximum number of simultaneously opened files
	_setmaxstdio(2048);
#endif

	try {
		// initialize QMiner environment
		TQm::TEnv::Init();
		// create app environment
		Env = TEnv(argc, argv, TNotify::StdNotify);
		Env.SetNoLine(); // making output prettier
		// command line parameters
		Env.PrepArgs("QMiner " + TQm::TEnv::GetVersion(), 0);
		// read the action
		const bool ConfigP = Env.IsArgStr("config");
		const bool CreateP = Env.IsArgStr("create");
		const bool StartP = Env.IsArgStr("start");
		const bool StopP = Env.IsArgStr("stop");
		//const bool ReloadP = Env.IsArgStr("reload");
		const bool DebugP = Env.IsArgStr("debug");
		// stop if no action given
		const bool ActionP = (ConfigP || CreateP || StartP || StopP /*|| ReloadP*/ || DebugP);
		// provide basic instruction when no action given
		if (!ActionP) {
			printf("\n");
			printf("Usage: qm ACTION [OPTION]...\n");
			printf("\n");
			printf("Actions: config, create, start, stop, reload, debug\n");			
		} else {
			Env.SetSilent();
		}
		// configuration file
		const TStr ConfFNm = Env.GetIfArgPrefixStr("-conf=", "qm.conf", "Configration file");
		// read config-specific parameters
		if (!Env.IsSilent()) { printf("\nConfiguration parameters:\n"); }
		const int PortN = Env.GetIfArgPrefixInt("-port=", 8080, "Port number");
		const int CacheSizeMB = Env.GetIfArgPrefixInt("-cache=", 1024, "Cache size");
		const bool OverwriteP = Env.IsArgStr("-overwrite", "Overwrite existing configuration file");
		// read create-specific parameters
		if (!Env.IsSilent()) { printf("\nCreate parameters:\n"); }
		const TStr SchemaFNm = Env.GetIfArgPrefixStr("-def=", "", "Store definition file");
		// read start-specific parameters
		if (!Env.IsSilent()) { printf("\nStart parameters:\n"); }
		const bool RdOnlyP = Env.IsArgStr("-rdonly", "Open database in Read-only mode");
		const bool NoLoopP = Env.IsArgStr("-noserver", "Do not start server after script execution");
		TStr OnlyScriptNm = Env.GetIfArgPrefixStr("-script=", "", "Only run this script");
		// read stop-specific parameters
		if (!Env.IsSilent()) { printf("\nStop parameters:\n"); }
		const int ReturnCode = Env.GetIfArgPrefixInt("-return=", 0, "Return code");
		// read reload-specific parameters
		//if (!Env.IsSilent()) { printf("\nReload parameters:\n"); }
		//TStrV ReloadNmV = Env.GetIfArgPrefixStrV("-name=", "Script name");
		// read debug request parameters
		if (!Env.IsSilent()) { printf("\nDebug parameters:\n"); }
		TStr DebugFNm = Env.GetIfArgPrefixStr("-prefix=", "Debug-", "Prefix of debug output files");
		TStrV DebugTaskV = Env.GetIfArgPrefixStrV("-task=", "Debug tasks [indexvoc, index, stores, <store>, <store>_ALL]");
		const int JsStatRate = Env.GetIfArgPrefixInt("-jsmemstat=", 0, "Frequency of JavaScript memory statistics");        
		// read logging specific parameters
		if (!Env.IsSilent()) { printf("\nLogging parameters:\n"); }
		TStr LogFPath = Env.GetIfArgPrefixStr("-log=", "std", "Log Folder (std for standard output, null for silent)");
		const bool Verbose = Env.IsArgStr("-v", "Verbose output (used for debugging)");
		if (!Env.IsSilent()) { printf("\nPre-run file:\n"); }		
		const TStr PreRunFNm = Env.GetIfArgPrefixStr("-prerun=", "", "Pre-run file name");
		if (!Env.IsSilent()) { printf("\n"); }

        // execute pre-run command when provided
		if (!PreRunFNm.Empty()) { 
            const int ReturnCd = system(PreRunFNm.CStr());
            if (ReturnCd != 0) { 
                TQm::ErrorLog(TStr::Fmt("Error running prerun script: %d", ReturnCd)); 
            }
        }

		// stop if no action specified
		if (!ActionP) { return 0; }

		// initialize notifier
		TQm::TEnv::InitLogger(Verbose ? 2 : 1, LogFPath, true);
		printf("\n");

		// Create directory structure with basic qm.conf file
		if (ConfigP) {
			// check so we don't overwrite any existing configuration file
			if (TFile::Exists(ConfFNm) && ! OverwriteP) {
				TQm::InfoLog("Configuration file already exists (" + ConfFNm + ")");
				TQm::InfoLog("Use -overwrite to force overwrite");
				return 2;
			}
			// create configuration file
			PJsonVal ConfigVal = TJsonVal::NewObj();
			ConfigVal->AddToObj("port", PortN);
			PJsonVal CacheVal = TJsonVal::NewObj();
			CacheVal->AddToObj("index", CacheSizeMB);
			CacheVal->AddToObj("store", CacheSizeMB);
			ConfigVal->AddToObj("cache", CacheVal);
			// save configuration file
			ConfigVal->SaveStr().SaveTxt(ConfFNm);
			// make folders if needed
			if (!TFile::Exists("db")) { TDir::GenDir("db"); }
			if (!TFile::Exists("src")) { TDir::GenDir("src"); }
			if (!TFile::Exists("src/lib")) { TDir::GenDir("src/lib"); }
			if (!TFile::Exists("sandbox")) { TDir::GenDir("sandbox"); }			
		}

		
		// parse configuration file
		TQmParam Param(ConfFNm);
		// prepare lock
		TFileLock Lock(Param.LockFNm);

		// Initialize empty database
		if (CreateP) {
			// do not mess with folders with existing running qminer instance
			Lock.Lock();
            {
                // parse schema (if no given, create an empty array)
                PJsonVal SchemaVal = SchemaFNm.Empty() ? TJsonVal::NewArr() :
                    TJsonVal::GetValFromStr(TStr::LoadTxt(SchemaFNm));
                // initialize base
                TQm::PBase Base = TQm::TStorage::NewBase(Param.DbFPath, SchemaVal, 16, 16);
                // save base
                TQm::TStorage::SaveBase(Base);
            }
			// remove lock
			Lock.Unlock();
		}

		// Start QMiner engine
		if (StartP) {
			// do not mess with folders with running qminer instance
			Lock.Lock();
			// load database and start the server
			{
				// resolve access type
				TFAccess FAccess = RdOnlyP ? faRdOnly : faUpdate;
				// load base
				TQm::PBase Base = TQm::TStorage::LoadBase(Param.DbFPath, FAccess, 
                    Param.IndexCacheSize, Param.DefStoreCacheSize, Param.StoreNmCacheSizeH);
				// initialize javascript contexts
                TQm::TJsUtil::SetObjStatRate(JsStatRate);
				TVec<TQm::PScript> ScriptV; InitJs(Param, Base, OnlyScriptNm, ScriptV);
				// start server
				if (!NoLoopP) {
                    // prepare server functions 
                    TSAppSrvFunV SrvFunV;
                    // used to stop the server
                    SrvFunV.Add(TSASFunExit::New());
                    // admin webservices
                    TQm::TSrvFun::RegDefFun(Base, SrvFunV);
                    // initialize static content serving thingies
                    for (int WwwRootN = 0; WwwRootN < Param.WwwRootV.Len(); WwwRootN++) {
                        const TStrPr& WwwRoot = Param.WwwRootV[WwwRootN];
                        const TStr& UrlPath = WwwRoot.Val1, FPath = WwwRoot.Val2;
                        TQm::TEnv::Logger->OnStatusFmt("Registering '%s' at '/%s/'", FPath.CStr(), UrlPath.CStr());
                        SrvFunV.Add(TSASFunFPath::New(UrlPath, FPath));
                    }
                    // register admin services
                    SrvFunV.Add(TQm::TJsAdminSrvFun::New(ScriptV, "qm_status"));
					// register javascript contexts
					for (int ScriptN = 0; ScriptN < ScriptV.Len(); ScriptN++) {
						// register server function
						ScriptV[ScriptN]->RegSrvFun(SrvFunV);
					}
					// start server
					PWebSrv WebSrv = TSAppSrv::New(Param.PortN, SrvFunV, TQm::TEnv::Logger, true, true);
					// report we started
					TQm::TEnv::Logger->OnStatusFmt("Server started on port %d", Param.PortN);
					// wait for the end
					TLoop::Run();
				}
                // save base
                TQm::TStorage::SaveBase(Base);

			}
			// remove lock
			Lock.Unlock();
		}

		// Stop QMiner engine
		if (StopP) {
			ExecUrl(TStr::Fmt("http://127.0.0.1:%d/exit?return=%d", Param.PortN, ReturnCode),
                "Server stop procedure initiated", "Error stopping server: ");
		}

		// Reload QMiner script
		//if (ReloadP) {
		//	for (int ReloadNmN = 0; ReloadNmN < ReloadNmV.Len(); ReloadNmN++) {
		//		TStr ScriptNm = ReloadNmV[ReloadNmN];
		//		ExecUrl(TStr::Fmt("http://127.0.0.1:%d/%s/admin/reload", Param.PortN, ScriptNm.CStr()), 
		//			"Initializing reload of script '" + ScriptNm + "'", 
		//			"Error reloading script '" + ScriptNm + "': ");
		//	}
		//}

		// Debug dumps of database and index
		if (DebugP) {
			// do not mess with folders with existing running qminer instance
			Lock.Lock();
            {
                // load base
                TQm::PBase Base = TQm::TStorage::LoadBase(Param.DbFPath, faRdOnly, 
                    Param.IndexCacheSize, Param.DefStoreCacheSize, Param.StoreNmCacheSizeH);
                // go over task lists and prepare outputs
                for (int TaskN = 0; TaskN < DebugTaskV.Len(); TaskN++) {
                    TStr Task = DebugTaskV[TaskN];
                    if (Task == "index") {
                        Base->PrintIndex(DebugFNm + "index.txt", true);
                    } else if (Task == "indexvoc") {
                        Base->PrintIndexVoc(DebugFNm + "indexvoc.txt");
                    } else if (Task == "stores") {
                        Base->PrintStores(DebugFNm + "stores.txt");
                    } else if (Task.IsSuffix("_ALL")) {
                        TStr StoreNm = Task.LeftOfLast('_');
                        Base->GetStoreByStoreNm(StoreNm)->PrintAll(Base, DebugFNm + Task + ".txt");
                    } else if (Base->IsStoreNm(Task)) {
                        Base->GetStoreByStoreNm(Task)->PrintTypes(Base, DebugFNm + Task + ".txt");
                    } else {
                        TQm::InfoLog("Unkown debug task '" + Task + "'");
                    }
                }
            }
			// remove lock
			Lock.Unlock();
		}		
	} catch (const PExcept& Except) {
		// GLib exception
		TQm::ErrorLog("Error: " + Except->GetMsgStr());
		return 2;
	} catch (...) {
		// other exceptions
		TQm::ErrorLog("Unknown error");
		return 1;
	}
	return TQm::TEnv::ReturnCode.Val;
}
Exemple #21
0
/*-------------------------------------------------------------------*/
DLL_EXPORT int impl(int argc, char *argv[])
{
char   *cfgfile;                        /* -> Configuration filename */
char    pathname[MAX_PATH];             /* work area for filenames   */
#if defined ( OPTION_LOCK_CONFIG_FILE )
int     fd_cfg = -1;                    /* fd for config file        */
#if !defined ( _MSVC_ )
struct  flock  fl_cfg;                  /* file lock for conf file   */
#endif
#endif
int     c;                              /* Work area for getopt      */
int     arg_error = 0;                  /* 1=Invalid arguments       */
char   *msgbuf;                         /*                           */
int     msgnum;                         /*                           */
int     msgcnt;                         /*                           */
TID     rctid;                          /* RC file thread identifier */
TID     logcbtid;                       /* RC file thread identifier */
int     rc;
#if defined(EXTERNALGUI)
int     e_gui = FALSE;                  /* EXTERNALGUI parm          */
#endif
#if defined(OPTION_DYNAMIC_LOAD)
#define MAX_DLL_TO_LOAD         50
char   *dll_load[MAX_DLL_TO_LOAD];      /* Pointers to modnames      */
int     dll_count;                      /* index into array          */
#endif

    /* Seed the pseudo-random number generator */
    srand( time(NULL) );

    /* Clear the system configuration block */
    memset( &sysblk, 0, sizeof( SYSBLK ) );

    VERIFY( MLOCK( &sysblk, sizeof( SYSBLK )) == 0);

#if defined (_MSVC_)
    _setmaxstdio(2048);
#endif

    /* Initialize EYE-CATCHERS for SYSBLK       */
    memset(&sysblk.blknam,SPACE,sizeof(sysblk.blknam));
    memset(&sysblk.blkver,SPACE,sizeof(sysblk.blkver));
    memset(&sysblk.blkend,SPACE,sizeof(sysblk.blkend));
    sysblk.blkloc = swap_byte_U64((U64)((uintptr_t)&sysblk));
    memcpy(sysblk.blknam,HDL_NAME_SYSBLK,strlen(HDL_NAME_SYSBLK));
    memcpy(sysblk.blkver,HDL_VERS_SYSBLK,strlen(HDL_VERS_SYSBLK));
    sysblk.blksiz = swap_byte_U32((U32)sizeof(SYSBLK));
    {
        char buf[32];
        MSGBUF( buf, "END%13.13s", HDL_NAME_SYSBLK );

        memcpy(sysblk.blkend, buf, sizeof(sysblk.blkend));
    }

    /* Initialize SETMODE and set user authority */
    SETMODE(INIT);

#if defined(OPTION_DYNAMIC_LOAD)
    for ( dll_count = 0; dll_count < MAX_DLL_TO_LOAD; dll_count++ )
        dll_load[dll_count] = NULL;
    dll_count = -1;
#endif

    SET_THREAD_NAME("impl");

    /* Initialize 'hostinfo' BEFORE display_version is called */
    init_hostinfo( &hostinfo );

#ifdef _MSVC_
    /* Initialize sockets package */
    VERIFY( socket_init() == 0 );
#endif

    /* Ensure hdl_shut is called in case of shutdown
       hdl_shut will ensure entries are only called once */
    atexit(hdl_shut);

    if ( argc > 0 )
    {
        int i,len;

        for (len = 0, i = 0; i < argc; i++ )
            len += (int)strlen( (char *)argv[i] ) + 1;

        sysblk.hercules_cmdline = (char *)malloc( len );

        strlcpy( sysblk.hercules_cmdline, argv[0], len );
        for ( i = 1; i < argc; i++ )
        {
            strlcat( sysblk.hercules_cmdline, " ", len );
            strlcat( sysblk.hercules_cmdline, argv[i], len );
        }
    }

    /* Set program name */
    if ( argc > 0 )
    {
        if ( strlen(argv[0]) == 0 )
        {
            sysblk.hercules_pgmname = strdup("hercules");
            sysblk.hercules_pgmpath = strdup("");
        }
        else
        {
            char path[MAX_PATH];
#if defined( _MSVC_ )
            GetModuleFileName( NULL, path, MAX_PATH );
#else
            strncpy(path,argv[0],sizeof(path)-1);
#endif
            sysblk.hercules_pgmname = strdup(basename(path));
#if !defined( _MSVC_ )
            strncpy(path,argv[0],sizeof(path)-1);
#endif
            sysblk.hercules_pgmpath = strdup(dirname(path));
        }
    }
    else
    {
            sysblk.hercules_pgmname = strdup("hercules");
            sysblk.hercules_pgmpath = strdup("");
    }

#if defined( OPTION_CONFIG_SYMBOLS )

    /* These were moved from console.c to make them available sooner */
    set_symbol( "VERSION", VERSION);
    set_symbol( "BDATE", __DATE__ );
    set_symbol( "BTIME", __TIME__ );

    {
        char num_procs[64];

        if ( hostinfo.num_packages     != 0 &&
             hostinfo.num_physical_cpu != 0 &&
             hostinfo.num_logical_cpu  != 0 )
        {
            MSGBUF( num_procs, "LP=%d, Cores=%d, CPUs=%d", hostinfo.num_logical_cpu,
                                hostinfo.num_physical_cpu, hostinfo.num_packages );
        }
        else
        {
            if ( hostinfo.num_procs > 1 )
                MSGBUF( num_procs, "MP=%d", hostinfo.num_procs );
            else if ( hostinfo.num_procs == 1 )
                strlcpy( num_procs, "UP", sizeof(num_procs) );
            else
                strlcpy( num_procs,   "",  sizeof(num_procs) );
        }

        set_symbol( "HOSTNAME", hostinfo.nodename );
        set_symbol( "HOSTOS", hostinfo.sysname );
        set_symbol( "HOSTOSREL", hostinfo.release );
        set_symbol( "HOSTOSVER", hostinfo.version );
        set_symbol( "HOSTARCH", hostinfo.machine );
        set_symbol( "HOSTNUMCPUS", num_procs );
    }

    set_symbol( "MODNAME", sysblk.hercules_pgmname );
    set_symbol( "MODPATH", sysblk.hercules_pgmpath );

#endif // defined( OPTION_CONFIG_SYMBOLS )

    sysblk.sysgroup = DEFAULT_SYSGROUP;
    sysblk.msglvl   = DEFAULT_MLVL;                 /* Defaults to TERSE and DEVICES */

    /* set default console port address */
    sysblk.cnslport = strdup("3270");

    /* set default tape autoinit value to OFF   */
    sysblk.noautoinit = TRUE;

    /* default for system dasd cache is on */
    sysblk.dasdcache = TRUE;

#if defined(OPTION_MSGCLR) || defined(OPTION_MSGHLD)
    /* set default error message display (emsg) */
    sysblk.emsg = EMSG_ON;
#endif

#if defined( OPTION_SHUTDOWN_CONFIRMATION )
    /* set default quit timeout value (also ssd) */
    sysblk.quitmout = QUITTIME_PERIOD;
#endif

    /* Default command separator to off (NULL) */
    sysblk.cmdsep = NULL;

#if defined(_FEATURE_SYSTEM_CONSOLE)
    /* set default for scpecho to TRUE */
    sysblk.scpecho = TRUE;

    /* set fault for scpimply to FALSE */
    sysblk.scpimply = FALSE;
#endif

    /* set default system state to reset */
    sysblk.sys_reset = TRUE;

    /* set default SHCMDOPT enabled     */
    sysblk.shcmdopt = SHCMDOPT_ENABLE + SHCMDOPT_DIAG8;

    /* Save process ID */
    sysblk.hercules_pid = getpid();

    /* Save thread ID of main program */
    sysblk.impltid = thread_id();

    /* Save TOD of when we were first IMPL'ed */
    time( &sysblk.impltime );

    /* Set to LPAR mode with LPAR 1, LPAR ID of 01, and CPUIDFMT 0   */
    sysblk.lparmode = 1;                /* LPARNUM 1    # LPAR ID 01 */
    sysblk.lparnum = 1;                 /* ...                       */
    sysblk.cpuidfmt = 0;                /* CPUIDFMT 0                */
    sysblk.operation_mode = om_mif;     /* Default to MIF operaitons */

    /* set default CPU identifier */
    sysblk.cpumodel = 0x0586;
    sysblk.cpuversion = 0xFD;
    sysblk.cpuserial = 0x000001;
    sysblk.cpuid = createCpuId(sysblk.cpumodel, sysblk.cpuversion,
                               sysblk.cpuserial, 0);

    /* set default Program Interrupt Trace to NONE */
    sysblk.pgminttr = OS_NONE;

    sysblk.timerint = DEF_TOD_UPDATE_USECS;

    /* set default thread priorities */
    sysblk.hercprio = DEFAULT_HERCPRIO;
    sysblk.todprio  = DEFAULT_TOD_PRIO;
    sysblk.cpuprio  = DEFAULT_CPU_PRIO;
    sysblk.devprio  = DEFAULT_DEV_PRIO;
    sysblk.srvprio  = DEFAULT_SRV_PRIO;

    /* Cap the default priorities at zero if setuid not available */
#if !defined( _MSVC_ )
  #if !defined(NO_SETUID)
    if (sysblk.suid)
  #endif
    {
        if (sysblk.hercprio < 0)
            sysblk.hercprio = 0;
        if (sysblk.todprio < 0)
            sysblk.todprio = 0;
        if (sysblk.cpuprio < 0)
            sysblk.cpuprio = 0;
        if (sysblk.devprio < 0)
            sysblk.devprio = 0;
        if (sysblk.srvprio < 0)
            sysblk.srvprio = 0;
    }
#endif

    /* set default console keep alive values */
    sysblk.kaidle = KEEPALIVE_IDLE_TIME;
    sysblk.kaintv = KEEPALIVE_PROBE_INTERVAL;
    sysblk.kacnt  = KEEPALIVE_PROBE_COUNT;

#if defined(_FEATURE_ECPSVM)
    sysblk.ecpsvm.available = 0;
    sysblk.ecpsvm.level = 20;
#endif

#ifdef PANEL_REFRESH_RATE
    sysblk.panrate = PANEL_REFRESH_RATE_SLOW;
#endif

#if defined( OPTION_SHUTDOWN_CONFIRMATION )
    /* Set the quitmout value */
    sysblk.quitmout = QUITTIME_PERIOD;     /* quit timeout value        */
#endif

#if defined(OPTION_SHARED_DEVICES)
    sysblk.shrdport = 0;
#endif

#ifdef OPTION_MSGHLD
    /* Set the default timeout value */
    sysblk.keep_timeout_secs = 120;
#endif

#if defined(OPTION_CONFIG_SYMBOLS) && defined(OPTION_BUILTIN_SYMBOLS)
    /* setup defaults for BUILTIN symbols  */
    {
        char buf[8];

        set_symbol("LPARNAME", str_lparname());
        set_symbol("LPARNUM", "1");
        set_symbol("CPUIDFMT", "0");

        MSGBUF( buf, "%06X", sysblk.cpuserial );
        set_symbol( "CPUSERIAL", buf );

        MSGBUF( buf, "%04X", sysblk.cpumodel );
        set_symbol( "CPUMODEL", buf );

    }
#endif /* defined(OPTION_CONFIG_SYMBOLS) && defined(OPTION_BUILTIN_SYMBOLS */

#if defined(_FEATURE_CMPSC_ENHANCEMENT_FACILITY)
    sysblk.zpbits  = DEF_CMPSC_ZP_BITS;
#endif

    /* Initialize locks, conditions, and attributes */
    initialize_lock (&sysblk.config);
    initialize_lock (&sysblk.todlock);
    initialize_lock (&sysblk.mainlock);
    sysblk.mainowner = LOCK_OWNER_NONE;
    initialize_lock (&sysblk.intlock);
    initialize_lock (&sysblk.iointqlk);
    sysblk.intowner = LOCK_OWNER_NONE;
    initialize_lock (&sysblk.sigplock);
    initialize_lock (&sysblk.mntlock);
    initialize_lock (&sysblk.scrlock);
    initialize_lock (&sysblk.crwlock);
    initialize_lock (&sysblk.ioqlock);
    initialize_condition (&sysblk.ioqcond);
#if defined(OPTION_CMDSER)
    initialize_lock      (&sysblk.cmdlock);
    initialize_condition (&sysblk.cmdcond);
#endif /*defined(OPTION_CMDSER)*/

#ifdef FEATURE_MESSAGE_SECURITY_ASSIST_EXTENSION_3
    /* Initialize the wrapping key registers lock */
    initialize_rwlock(&sysblk.wklock);
#endif

    /* Initialize thread creation attributes so all of hercules
       can use them at any time when they need to create_thread
    */
    initialize_detach_attr (DETACHED);
    initialize_join_attr   (JOINABLE);

    initialize_condition (&sysblk.cpucond);
    {
        int i;
        for (i = 0; i < MAX_CPU_ENGINES; i++)
            initialize_lock (&sysblk.cpulock[i]);
    }
    initialize_condition (&sysblk.sync_cond);
    initialize_condition (&sysblk.sync_bc_cond);

    /* Copy length for regs */
    sysblk.regs_copy_len = (int)((uintptr_t)&sysblk.dummyregs.regs_copy_end
                               - (uintptr_t)&sysblk.dummyregs);

    /* Set the daemon_mode flag indicating whether we running in
       background/daemon mode or not (meaning both stdout/stderr
       are redirected to a non-tty device). Note that this flag
       needs to be set before logger_init gets called since the
       logger_logfile_write function relies on its setting.
    */
    sysblk.daemon_mode = !isatty(STDERR_FILENO) && !isatty(STDOUT_FILENO);

    /* Initialize the logmsg pipe and associated logger thread.
       This causes all subsequent logmsg's to be redirected to
       the logger facility for handling by virtue of stdout/stderr
       being redirected to the logger facility.
    */
    logger_init();

    /*
       Setup the initial codepage
    */
    set_codepage(NULL);

    /* Now display the version information again after logger_init
       has been called so that either the panel display thread or the
       external gui can see the version which was previously possibly
       only displayed to the actual physical screen the first time we
       did it further above (depending on whether we're running in
       daemon_mode (external gui mode) or not). This it the call that
       the panel thread or the one the external gui actually "sees".
       The first call further above wasn't seen by either since it
       was issued before logger_init was called and thus got written
       directly to the physical screen whereas this one will be inter-
       cepted and handled by the logger facility thereby allowing the
       panel thread or external gui to "see" it and thus display it.
    */
    display_version (stdout, "Hercules", TRUE);

#ifdef EXTERNALGUI
    if (argc >= 1 && strncmp(argv[argc-1],"EXTERNALGUI",11) == 0)
    {
        e_gui = TRUE;
        argc--;
    }
#endif

#if !defined(WIN32) && !defined(HAVE_STRERROR_R)
    strerror_r_init();
#endif

#if defined(OPTION_SCSI_TAPE)
    initialize_lock      ( &sysblk.stape_lock         );
    initialize_condition ( &sysblk.stape_getstat_cond );
    InitializeListHead   ( &sysblk.stape_mount_link   );
    InitializeListHead   ( &sysblk.stape_status_link  );
#endif /* defined(OPTION_SCSI_TAPE) */

    /* Get name of configuration file or default to hercules.cnf */
    if(!(cfgfile = getenv("HERCULES_CNF")))
        cfgfile = "hercules.cnf";

    /* Process the command line options */
    {
#define  HERCULES_BASE_OPTS     "hf:r:db:v"
#define  HERCULES_SYM_OPTS      ""
#define  HERCULES_HDL_OPTS      ""
#if defined(OPTION_CONFIG_SYMBOLS)
#undef   HERCULES_SYM_OPTS
#define  HERCULES_SYM_OPTS      "s:"
#endif
#if defined(OPTION_DYNAMIC_LOAD)
#undef   HERCULES_HDL_OPTS
#define  HERCULES_HDL_OPTS      "p:l:"
#endif
#define  HERCULES_OPTS_STRING   HERCULES_BASE_OPTS  HERCULES_SYM_OPTS  HERCULES_HDL_OPTS

#if defined(HAVE_GETOPT_LONG)
    static struct option longopts[] =
    {
        { "help",     no_argument,       NULL, 'h' },
        { "config",   required_argument, NULL, 'f' },
        { "rcfile",   required_argument, NULL, 'r' },
        { "daemon",   no_argument,       NULL, 'd' },
        { "herclogo", required_argument, NULL, 'b' },
        { "verbose",  no_argument,       NULL, 'v' },
#if defined(OPTION_CONFIG_SYMBOLS)
        { "defsym",   required_argument, NULL, 's' },
#endif
#if defined(OPTION_DYNAMIC_LOAD)
        { "modpath",  required_argument, NULL, 'p' },
        { "ldmod",    required_argument, NULL, 'l' },
#endif
        { NULL,       0,                 NULL,  0  }
    };
    while ((c = getopt_long( argc, argv, HERCULES_OPTS_STRING, longopts, NULL )) != EOF)
#else
    while ((c = getopt( argc, argv, HERCULES_OPTS_STRING )) != EOF)
#endif
    {
        switch (c) {
        case 'h':
            arg_error = 1;
            break;
        case 'f':
            cfgfile = optarg;
            break;
        case 'r':
            rcname = optarg;
            break;
#if defined(OPTION_CONFIG_SYMBOLS)
        case 's':
            {
            char *sym        = NULL;
            char *value      = NULL;
            char *strtok_str = NULL;
                if ( strlen( optarg ) >= 3 )
                {
                    sym   = strtok_r( optarg, "=", &strtok_str);
                    value = strtok_r( NULL,   "=", &strtok_str);
                    if ( sym != NULL && value != NULL )
                    {
                    int j;
                        for( j = 0; j < (int)strlen( sym ); j++ )
                            if ( islower( sym[j] ) )
                            {
                                sym[j] = toupper( sym[j] );
                            }
                        set_symbol(sym, value);
                    }
                    else
                        WRMSG(HHC01419, "E" );
                }
                else
                    WRMSG(HHC01419, "E");
            }
            break;
#endif /* defined(OPTION_CONFIG_SYMBOLS) */
#if defined(OPTION_DYNAMIC_LOAD)
        case 'p':
            if(optarg)
                hdl_setpath(strdup(optarg), FALSE);
            break;
        case 'l':
            {
            char *dllname, *strtok_str = NULL;
                for(dllname = strtok_r(optarg,", ",&strtok_str);
                    dllname;
                    dllname = strtok_r(NULL,", ",&strtok_str))
                {
                    if (dll_count < MAX_DLL_TO_LOAD - 1)
                        dll_load[++dll_count] = strdup(dllname);
                    else
                    {
                        WRMSG(HHC01406, "W", MAX_DLL_TO_LOAD);
                        break;
                    }
                }
            }
            break;
#endif /* defined(OPTION_DYNAMIC_LOAD) */
        case 'b':
            sysblk.logofile = optarg;
            break;
        case 'v':
            sysblk.msglvl |= MLVL_VERBOSE;
            break;
        case 'd':
            sysblk.daemon_mode = 1;
            break;
        default:
            arg_error = 1;

        } /* end switch(c) */
    } /* end while */
    } /* end Process the command line options */

    /* Treat filename None as special */
    if(!strcasecmp(cfgfile,"None"))
        cfgfile = NULL;

    if (optind < argc)
        arg_error = 1;

    /* Terminate if invalid arguments were detected */
    if (arg_error)
    {
        char pgm[MAX_PATH];
        char* strtok_str = NULL;
        strncpy(pgm, sysblk.hercules_pgmname, sizeof(pgm));

        /* Show them all of our command-line arguments... */

        WRMSG (HHC01414, "S", "");   // (blank line)
        WRMSG (HHC01414, "S", "");   // (blank line)

#if defined(OPTION_DYNAMIC_LOAD)
        // "Usage: %s [-f config-filename] [-d] [-b logo-filename] [-s sym=val]%s [> logfile]"
        WRMSG (HHC01407, "S", strtok_r(pgm,".",&strtok_str),
                             " [-p dyn-load-dir] [[-l dynmod-to-load]...]");
#else
        WRMSG (HHC01407, "S", strtok_r(pgm,".", &strtok_str), "");
#endif /* defined(OPTION_DYNAMIC_LOAD) */

        WRMSG (HHC01414, "S", "");   // (blank line)
        WRMSG (HHC01414, "S", "");   // (blank line)

        fflush(stderr);
        fflush(stdout);
        usleep(100000);
        return(1);
    }

    /* Initialize runtime opcode tables */
    init_opcode_tables();

#if defined(OPTION_DYNAMIC_LOAD)
    /* Initialize the hercules dynamic loader */
    hdl_main();

    /* Load modules requested at startup */
    if (dll_count >= 0)
    {
        int hl_err = FALSE;
        for ( dll_count = 0; dll_count < MAX_DLL_TO_LOAD; dll_count++ )
        {
            if (dll_load[dll_count] != NULL)
            {
                if (hdl_load(dll_load[dll_count], HDL_LOAD_DEFAULT) != 0)
                {
                    hl_err = TRUE;
                }
                free(dll_load[dll_count]);
            }
            else
                break;
        }

        if (hl_err)
        {
            usleep(10000);      // give logger time to issue error message
            WRMSG(HHC01408, "S");
            delayed_exit(-1);
            return(1);
        }

    }
#endif /* defined(OPTION_DYNAMIC_LOAD) */

#ifdef EXTERNALGUI
    /* Set GUI flag if specified as final argument */
    if (e_gui)
    {
#if defined(OPTION_DYNAMIC_LOAD)
        if (hdl_load("dyngui",HDL_LOAD_DEFAULT) != 0)
        {
            usleep(10000); /* (give logger thread time to issue
                               preceding HHC01516E message) */
            WRMSG(HHC01409, "S");
            delayed_exit(-1);
            return(1);
        }
#endif /* defined(OPTION_DYNAMIC_LOAD) */
    }
#endif /*EXTERNALGUI*/

    /* Register the SIGINT handler */
    if ( signal (SIGINT, sigint_handler) == SIG_ERR )
    {
        WRMSG(HHC01410, "S", "SIGINT", strerror(errno));
        delayed_exit(-1);
        return(1);
    }

    /* Register the SIGTERM handler */
    if ( signal (SIGTERM, sigterm_handler) == SIG_ERR )
    {
        WRMSG(HHC01410, "S", "SIGTERM", strerror(errno));
        delayed_exit(-1);
        return(1);
    }

#if defined( _MSVC_ )
    /* Register the Window console ctrl handlers */
    if (!IsDebuggerPresent())
    {
        if (!SetConsoleCtrlHandler( console_ctrl_handler, TRUE ))
        {
            WRMSG( HHC01410, "S", "Console-ctrl", strerror( errno ));
            delayed_exit(-1);
            return(1);
        }
    }
#endif

#if defined(HAVE_DECL_SIGPIPE) && HAVE_DECL_SIGPIPE
    /* Ignore the SIGPIPE signal, otherwise Hercules may terminate with
       Broken Pipe error if the printer driver writes to a closed pipe */
    if ( signal (SIGPIPE, SIG_IGN) == SIG_ERR )
    {
        WRMSG(HHC01411, "E", strerror(errno));
    }
#endif

    {
        int fds[2];
        initialize_lock(&sysblk.cnslpipe_lock);
        initialize_lock(&sysblk.sockpipe_lock);
        sysblk.cnslpipe_flag=0;
        sysblk.sockpipe_flag=0;
        VERIFY( create_pipe(fds) >= 0 );
        sysblk.cnslwpipe=fds[1];
        sysblk.cnslrpipe=fds[0];
        VERIFY( create_pipe(fds) >= 0 );
        sysblk.sockwpipe=fds[1];
        sysblk.sockrpipe=fds[0];
    }

#if !defined(NO_SIGABEND_HANDLER)
    {
    struct sigaction sa;
        sa.sa_sigaction = (void*)&sigabend_handler;
#ifdef SA_NODEFER
        sa.sa_flags = SA_NODEFER;
#else
        sa.sa_flags = 0;
#endif

        if( sigaction(SIGILL, &sa, NULL)
         || sigaction(SIGFPE, &sa, NULL)
         || sigaction(SIGSEGV, &sa, NULL)
         || sigaction(SIGBUS, &sa, NULL)
         || sigaction(SIGUSR1, &sa, NULL)
         || sigaction(SIGUSR2, &sa, NULL) )
        {
            WRMSG(HHC01410, "S", "SIGILL/FPE/SEGV/BUS/USR", strerror(errno));
            delayed_exit(-1);
            return(1);
        }
    }
#endif /*!defined(NO_SIGABEND_HANDLER)*/

    if(cfgfile)
    {
        /* attempt to get lock on config file */
        hostpath(pathname, cfgfile, sizeof(pathname));

#if defined( OPTION_LOCK_CONFIG_FILE )

        /* Test that we can get a read the file */

        if ( ( fd_cfg = HOPEN( pathname, O_RDONLY, S_IRUSR | S_IRGRP ) ) < 0 )
        {
            if ( errno == EACCES )
            {
                WRMSG( HHC01453, "S", cfgfile, strerror( errno ) );
                delayed_exit(-1);
                return(1);
            }
        }
        else
        {
            if ( lseek(fd_cfg, 0L, 2) < 0 )
            {
                if ( errno == EACCES )
                {
                    WRMSG( HHC01453, "S", cfgfile, strerror( errno ) );
                    delayed_exit(-1);
                    return(1);
                }
            }
            close( fd_cfg );
        }

        /* File was not lock, therefore we can proceed */
#endif // OPTION_LOCK_CONFIG_FILE
    }

    /* System initialisation time */
    sysblk.todstart = hw_clock() << 8;

#if !defined(NO_SIGABEND_HANDLER)
    /* Start the watchdog */
    rc = create_thread (&sysblk.wdtid, DETACHED,
                        watchdog_thread, NULL, "watchdog_thread");
    if (rc)
    {
        WRMSG(HHC00102, "E", strerror(rc));
        delayed_exit(-1);
        return(1);
    }
#endif /*!defined(NO_SIGABEND_HANDLER)*/

    if(log_callback)
    {
        // 'herclin' called us. IT'S in charge. Create its requested
        // logmsg intercept callback function and return back to it.
        rc = create_thread(&logcbtid,DETACHED,
                      log_do_callback,NULL,"log_do_callback");
        if (rc)
            WRMSG(HHC00102, "E", strerror(rc));
        return(0);
    }

    hdl_adsc("release_config", release_config, NULL);

    /* Build system configuration */
    if ( build_config (cfgfile) )
    {
        delayed_exit(-1);
        return(1);
    }

    /* Start up the RC file processing thread */
    rc = create_thread(&rctid,DETACHED,
                  process_rc_file,NULL,"process_rc_file");
    if (rc)
        WRMSG(HHC00102, "E", strerror(rc));


#if defined( OPTION_LOCK_CONFIG_FILE )
    if(cfgfile)
    {
        if ( ( fd_cfg = HOPEN( pathname, O_RDONLY, S_IRUSR | S_IRGRP ) ) < 0 )
        {
            WRMSG( HHC01432, "S", pathname, "open()", strerror( errno ) );
            delayed_exit(-1);
            return(1);
        }
        else
        {
#if defined( _MSVC_ )
            if( ( rc = _locking( fd_cfg, _LK_NBRLCK, 1L ) ) < 0 )
            {
                int rc = errno;
                WRMSG( HHC01454, "S", pathname, "_locking()", strerror( errno ) );
                delayed_exit(-1);
                return(1);
            }
#else
            fl_cfg.l_type = F_RDLCK;
            fl_cfg.l_whence = SEEK_SET;
            fl_cfg.l_start = 0;
            fl_cfg.l_len = 1;

            if ( fcntl(fd_cfg, F_SETLK, &fl_cfg) == -1 )
            {
                if (errno == EACCES || errno == EAGAIN)
                {
                    WRMSG( HHC01432, "S", pathname, "fcntl()", strerror( errno ) );
                    delayed_exit(-1);
                    return(1);
                }
            }
#endif
        }
    }
#endif // OPTION_LOCK_CONFIG_FILE

    //---------------------------------------------------------------
    // The below functions will not return until Hercules is shutdown
    //---------------------------------------------------------------

    /* Activate the control panel */
    if(!sysblk.daemon_mode)
        panel_display ();
    else
    {
#if defined(OPTION_DYNAMIC_LOAD)
        if(daemon_task)
            daemon_task ();
        else
#endif /* defined(OPTION_DYNAMIC_LOAD) */
        {
            /* Tell RC file and HAO threads they may now proceed */
            sysblk.panel_init = 1;

            /* Retrieve messages from logger and write to stderr */
            while (1)
                if((msgcnt = log_read(&msgbuf, &msgnum, LOG_BLOCK)))
                    if(isatty(STDERR_FILENO))
                        fwrite(msgbuf,msgcnt,1,stderr);
        }
    }

    //  -----------------------------------------------------
    //      *** Hercules has been shutdown (PAST tense) ***
    //  -----------------------------------------------------

#if defined( OPTION_LOCK_CONFIG_FILE )
    if(cfgfile)
        close( fd_cfg );            // release config file lock
#endif //    OPTION_LOCK_CONFIG_FILE

    ASSERT( sysblk.shutdown );  // (why else would we be here?!)

#ifdef _MSVC_
    SetConsoleCtrlHandler(console_ctrl_handler, FALSE);
    socket_deinit();
#endif
#if defined(OPTION_MSGCLR) || defined(OPTION_MSGHLD)
    if ( sysblk.emsg & EMSG_TEXT )
        fprintf(stdout, HHC01412 );
    else
#endif
        fprintf(stdout, MSG(HHC01412, "I"));
    fflush(stdout);
    usleep(10000);
    return 0;
} /* end function impl */
int main(int argc, char* argv[])
{
    _setmaxstdio(2048);
    uint32 threads = 4, extractFlags = 0;
    std::set<uint32> mapIds;

    if (!HandleArgs(argc, argv, threads, mapIds, Constants::Debug, extractFlags))
    {
        PrintUsage();
        return -1;
    }

    if (extractFlags == 0)
    {
        printf("You must provide valid extract flags.\n");
        PrintUsage();
        return -1;
    }

    Cache = new CacheClass();
    MPQHandler = new MPQManager();
    MPQHandler->Initialize();

    if (extractFlags & Constants::EXTRACT_FLAG_DBC)
        ExtractDBCs();

    if (extractFlags & Constants::EXTRACT_FLAG_MMAPS)
        ExtractMMaps(mapIds, threads);

    if (extractFlags & Constants::EXTRACT_FLAG_GOB_MODELS)
        ExtractGameobjectModels();

    if (extractFlags & Constants::EXTRACT_FLAG_TEST)
    {
        float start[] = { 16226.200195f, 16257.000000f, 13.202200f };
        float end[] = { 16245.725586f, 16382.465820f, 47.384956f };

        //
        float m_spos[3];
        m_spos[0] = -start[1];
        m_spos[1] = start[2];
        m_spos[2] = -start[0];

        //
        float m_epos[3];
        m_epos[0] = -end[1];
        m_epos[1] = end[2];
        m_epos[2] = -end[0];

        //
        dtQueryFilter m_filter;
        m_filter.setIncludeFlags(Constants::POLY_AREA_ROAD | Constants::POLY_AREA_TERRAIN);
        m_filter.setExcludeFlags(Constants::POLY_AREA_WATER);

        //
        float m_polyPickExt[3];
        m_polyPickExt[0] = 2.5f;
        m_polyPickExt[1] = 2.5f;
        m_polyPickExt[2] = 2.5f;

        //
        dtPolyRef m_startRef;
        dtPolyRef m_endRef;

        FILE* mmap = fopen("mmaps/001.mmap", "rb");
        dtNavMeshParams params;
        int count = fread(&params, sizeof(dtNavMeshParams), 1, mmap);
        fclose(mmap);
        if (count != 1)
        {
            printf("main: Error reading from .mmap\n");
            return 0;
        }

        dtNavMesh* navMesh = new dtNavMesh();
        dtNavMeshQuery* navMeshQuery = new dtNavMeshQuery();

        navMesh->init(&params);
        for (int i = 0; i <= 32; ++i)
        {
            for (int j = 0; j <= 32; ++j)
            {
                char buff[100];
                sprintf(buff, "mmaps/001%02i%02i.mmtile", i, j);
                LoadTile(navMesh, buff);
            }
        }
        
        navMeshQuery->init(navMesh, 2048);

        float nearestPt[3];

        navMeshQuery->findNearestPoly(m_spos, m_polyPickExt, &m_filter, &m_startRef, nearestPt);
        navMeshQuery->findNearestPoly(m_epos, m_polyPickExt, &m_filter, &m_endRef, nearestPt);

        if ( !m_startRef || !m_endRef )
        {
            std::cerr << "Could not find any nearby poly's (" << m_startRef << "," << m_endRef << ")" << std::endl;
            return 0;
        }

        int hops;
        dtPolyRef* hopBuffer = new dtPolyRef[8192];
        dtStatus status = navMeshQuery->findPath(m_startRef, m_endRef, m_spos, m_epos, &m_filter, hopBuffer, &hops, 8192);
        
        int resultHopCount;
        float* straightPath = new float[2048*3];
        unsigned char* pathFlags = new unsigned char[2048];
        dtPolyRef* pathRefs = new dtPolyRef[2048];

        status = navMeshQuery->findStraightPath(m_spos, m_epos, hopBuffer, hops, straightPath, pathFlags, pathRefs, &resultHopCount, 2048);
        std::vector<Vector3> FinalPath;
        FinalPath.reserve(resultHopCount);
        for (uint32 i = 0; i < resultHopCount; ++i)
        {
            Vector3 finalV = Utils::ToWoWCoords(Vector3(straightPath[i * 3 + 0], straightPath[i * 3 + 1], straightPath[i * 3 + 2]));
            FinalPath.push_back(finalV);
            printf("Point %f %f %f\n", finalV.x, finalV.y, finalV.z);
        }
    }

    return 0;
}