@echo off
setlocal
for /f "tokens=2 delims=:" %%a in ('chcp') do set ACTIVE_CP=%%a
call :Trim ACTIVE_CP %ACTIVE_CP%
chcp 65001>nul

set path=%path%;%~dp0\bin
set src=%~dp0WebP
set dst=%~dp0PNG
call :strlen length src
for /r "%src%" %%a in (*.webp) do call :ConvertToPNG "%%a"
call :strlen length dst
for /d /r "%dst%" %%a in (*) do call :CopyTimestamp "%%a"
CopyTimestamp.exe "%src%" "%dst%"
pause

chcp %ACTIVE_CP%>nul
endlocal
exit /b

:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b

:ConvertToPNG
setlocal
set dir=%~dp1
call set dir=%dst%%%dir:~%length%%%
if not exist "%dir%" md "%dir%" >nul
set src=%~1
set name=%~dpn1.png
call set dst=%dst%%%name:~%length%%%
dwebp.exe -mt "%src%" -o "%dst%"
CopyTimestamp.exe "%src%" "%dst%"
endlocal
exit /b

:CopyTimestamp
setlocal
set dst=%~1
call set src=%src%%%dst:~%length%%%
CopyTimestamp.exe "%src%" "%dst%"
endlocal
exit /b

:strlen <result> <string>
(
	setlocal EnableDelayedExpansion
	set tmp=!%~2!
	if defined tmp (
		set len=1
		for %%i in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
			if not "!tmp:~%%i,1!" == "" (
				set /a len+=%%i
				set tmp=!tmp:~%%i!
			)
		)
	) else (
		set len=0
	)
)
(
	endlocal
	set %~1=%len%
	exit /b
)
