@echo off
setlocal enabledelayedexpansion

set ID=
set INF=
set INVALIDPARAM=
set REVERSE=FALSE
set RESULT=0
set RETURN_CODE=0

set MYSELF=%~nx0
set MYPATH=%~dp0
set CKDEV=%MYPATH%CkDev.exe


:PARSE_ARGS
call :CHECK_OPTION %*


:VERIFY
if defined INVALIDPARAM (
	call :ERROR_INVALID_PARAM
	goto HELP
)
	
if defined ID (
	if not exist !ID! (
		call :ERROR_FILE_NOT_EXIST
		goto end
	)
) else (
	if not defined INF (
		call :ERROR_INVALID_PARAM
		goto end
	)
)
	
if not exist !CKDEV! (
	call :ERROR_FILE_NOT_EXIST !CKDEV!
	goto end
)


:EXECUTE
if defined ID (
	set CKDEV=!CKDEV! /ID=!ID!
)
if defined INF (
	set CKDEV=!CKDEV! !INF!
)
start /w !CKDEV! /C /S /L=0
set RESULT=%ERRORLEVEL%

rem echo !RESULT!

if !REVERSE!==FALSE (
	if %RESULT%==1 (
		set RETURN_CODE=0
	) else (
		set RETURN_CODE=1
	)
)
if !REVERSE!==TRUE (
	if not %RESULT%==1 (
		set RETURN_CODE=0
	) else (
		set RETURN_CODE=1
	)
)



goto END



rem =============================================================================================

:CHECK_OPTION

if "%~1"=="" goto :EOF
if /i "%~1"=="/r" (
	set REVERSE=TRUE
) else if /i "%~1"=="/id" (
	set ID="!MYPATH!%~2"
	if not !ID!=="!MYPATH!%~2" set INVALIDPARAM=TRUE
	if "%~2"=="" set INVALIDPARAM=TRUE
	if defined INF set INVALIDPARAM=TRUE
) else if /i "%~1"=="/inf" (
	set INF="!MYPATH!%~2"
	if not !INF!=="!MYPATH!%~2" set INVALIDPARAM=TRUE
	if "%~2"=="" set INVALIDPARAM=TRUE
	if defined ID set INVALIDPARAM=TRUE
)
shift
goto CHECK_OPTION


:ERROR_FILE_NOT_EXIST
set RETURN_CODE=1
goto :EOF

:ERROR_INVALID_PARAM
set RETURN_CODE=1
goto :EOF

:HELP
echo.
echo %MYSELF% [/r] /id "devid.txt" /inf "dev.inf"
echo.
echo   /r    Reverse Flag
echo   /id   DeviceID text file
echo   /inf  DeviceID inf file
echo.
echo Examples:
echo.
echo   (ID)        Q:\Common\tools\bin\%MYSELF% /id "devid.txt" 
echo.
echo   (INF)       Q:\Common\tools\bin\%MYSELF% /inf "dev.inf"
echo.
echo   (REVERSE)   Q:\Common\tools\bin\%MYSELF% /r /id "dev.inf"
echo.
echo.
set RETURN_CODE=2
goto END

rem =============================================================================================

:END
rem echo RETURN_CODE : %RETURN_CODE%
exit /b %RETURN_CODE%
