tasklist | find /i "HYP.exe"
if %errorlevel% equ 0 taskkill /F /IM HYP.exe /T
tasklist | find /i "HYPHelper.exe"
if %errorlevel% equ 0 taskkill /F /IM HYPHelper.exe /T

REM Record the newest version number, then rename that folder to HYP so the game exe path stays fixed
set "hyp_rec_file=%~dp0hyp_version.txt"
set "hyp_out_file=%TEMP%\hyp_maxver.txt"
del /f /q "%hyp_out_file%" >nul 2>&1
powershell -NoProfile -Command "Get-ChildItem -LiteralPath '%~dp0' -Directory -Name | Where-Object { $_ -match '^\d+(\.\d+)+$' } | Sort-Object { [version]$_ } -Descending | Select-Object -First 1 | Out-File -Encoding ASCII -FilePath '%hyp_out_file%'"
set "hyp_max="
if exist "%hyp_out_file%" set /p hyp_max=<"%hyp_out_file%"
del /f /q "%hyp_out_file%" >nul 2>&1

if defined hyp_max (
    >"%hyp_rec_file%" echo %hyp_max%
    if exist "%hyp_rec_file%" (
        if exist "%~dp0HYP" rmdir /S /Q "%~dp0HYP"
        if not exist "%~dp0HYP" ren "%~dp0%hyp_max%" "HYP"
    )
)

REM Drop the leftover older version folders, they are replaced by HYP
if exist "%~dp0HYP" powershell -NoProfile -Command "$d = '%~dp0'; Get-ChildItem -LiteralPath $d -Directory -Name | Where-Object { $_ -match '^\d+(\.\d+)+$' -and $_ -ne '%hyp_max%' } | ForEach-Object { Remove-Item -LiteralPath (Join-Path $d $_) -Recurse -Force }"

rmdir /S /Q "%~dp0ICafeCloud" 2>nul
rmdir /S /Q "%~dp0games" 2>nul

xcopy /E /I /Y "%AppData%\Cognosphere" "%~dp0ICafeCloud\AppData\Cognosphere"

if not exist "pkg_match_only.dat" (
    type nul > "pkg_match_only.dat"
)
