@ECHO OFF

SET PIN.LOG=C:\System.sav\Logs\OSEnh\%~n0.log
IF NOT EXIST C:\System.sav\LOGS\OSEnh MD C:\System.sav\LOGS\OSEnh


@REM -----------------
@REM Step1: Get the Latest xxHx.flg
@REM -----------------
SET LatestOSCycleFile=
SET OSCYCLE=
SET PIN.Path=C:\System.sav\Flags\
For /F %%a IN ('DIR /B /A %PIN.Path%??H?.flg') DO (
	SETLOCAL ENABLEDELAYEDEXPANSION
	CALL :CheckFormat_XXHX %%a
	IF [!bMatch!]==[1] (
		endlocal
		ECHO [%time%][%~nx0] Find [%%a] --- Match --- >> %PIN.LOG%
		SET LatestOSCycleFile=%%a
	) ELSE (
		endlocal
		ECHO [%time%][%~nx0] Find [%%a] >> %PIN.LOG%
	)
)

IF NOT DEFINED LatestOSCycleFile (
	ECHO [%time%][%~nx0] ***************** Error : Cannot Find xxHx.flg ***************** >> %PIN.LOG%
	Exit /B
)


ECHO LatestOSCycleFile=[%LatestOSCycleFile%] >> %PIN.LOG%
SET OSCYCLE=%LatestOSCycleFile:~0,4%
ECHO OSCYCLE=[%OSCYCLE%] >> %PIN.LOG%


:END
ECHO [%time%][%~nx0] ------------------------------------------------------------------------------------------------------------ >> %PIN.LOG%

EXIT /B


:CheckFormat_XXHX
SET Var=%1
SET bMatch=0

SET FirstChar=%Var:~0,1%
SET SecondChar=%Var:~1,1%
SET ThirdChar=%Var:~2,1%
SET ForthChar=%Var:~3,1%
SET FileExtension=%Var:~-4%


SET x=%FirstChar%
IF 1%x% NEQ +1%x% (
	EXIT /B 1
)


SET x=%SecondChar%
IF 1%x% NEQ +1%x% (
	EXIT /B 1
)

SET x=%ThirdChar%
IF /I NOT ["%x%"]==["H"] (
	EXIT /B 1
)

SET x=%ForthChar%
IF 1%x% NEQ +1%x% (
	EXIT /B 1
)

SET x=%FileExtension%
IF /I NOT ["%x%"]==[".FLG"] (
	EXIT /B 1
)

CALL :GetLength %Var%
IF NOT [%Length%]==[8] (
	EXIT /B 1
)
SET bMatch=1

EXIT /B 0



:GetLength
SET Length=0
Set "s=#%~1"
Set "len=0"
For %%N in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
  if "!s:~%%N,1!" neq "" (
    set /a "len+=%%N"
    set "s=!s:~%%N!"
  )
)
Endlocal&if "%~2" neq "" (set %~2=%len%) else (SET Length=%len%)
Exit /B
