@echo off
setlocal

SET HPSUM_ROOT="%~dp0"
SET HPSUM_CMD_ARGS=%*
set newcmdcmdline=%cmdcmdline:"=-%
set withincmd=1
echo %newcmdcmdline% | find /i "cmd /c --%~dpf0%-"
if %errorlevel% EQU 0 set withincmd=0
:: if %withincmd% EQU 0 echo This batch-file: %~dpf0 was executed directly (from Windows Explorer, ...).
:: if %withincmd% EQU 1 echo This batch-file: %~dpf0 was executed from within a Command Prompt

:: Select 32-bit or 64-bit
SET HostIs64Bit=%ProgramFiles(x86)%
IF "%HostIs64Bit%"=="" (
    set HPSUM_ARCH=x86
) ELSE (
    set HPSUM_ARCH=x64
)
set DEBUGLOGDIR=0
set LOGDIR=0
:loop
IF NOT "%~1"=="" (
rem Handle debuglog directory
    IF "%~1"=="/debuglogdir" (
        SET DEBUGLOGDIR=1
		echo %DEBUGLOGDIR%
        SHIFT
    )
	rem Handleuser log directory
    IF "%~1"=="/logdir" (
        SET LOGDIR=1
		echo %LOGDIR%
        SHIFT
    )
	SHIFT   
	GOTO :loop
)

IF %DEBUGLOGDIR% NEQ 1 (
  SET "HPSUM_CMD_ARGS=!HPSUM_CMD_ARGS! /debuglogdir !HPSUM_ROOT!" 
)
IF %LOGDIR% NEQ 1 (
  SET "HPSUM_CMD_ARGS=!HPSUM_CMD_ARGS! /logdir !HPSUM_ROOT!" 
)
set GATHERLOGS=%HPSUM_ROOT%%HPSUM_ARCH%\gatherlogs_%HPSUM_ARCH%.exe

IF NOT EXIST %GATHERLOGS% (
    @echo Unable to locate %GATHERLOGS%
    if %withincmd% EQU 0 (
        call :delay
    )
    set ERRORCODE=-4
    goto :Exit
)

:run
%GATHERLOGS% %*
set ERRORCODE=%ERRORLEVEL%

:: the acutal binary should have displayed an error
:: message.  We still want to delay to allow
:: people who started by clicking on the icon
:: a chance to see the message
IF %ERRORCODE% NEQ 0 (
    if %withincmd% EQU 0 (
        call :delay
    )
    goto :Exit
)    

goto :Exit

:delay
where ping > nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
    pause
) else (
    @echo Pausing for 10 seconds ...
    ping -n 11 127.0.0.1 > nul
)
goto :EOF

:Exit
exit /b %ERRORCODE%
