@echo off
rem XileRetro: lets the patcher open xile3.grf again (clients downloaded since Oct 23 2026).
rem Changes only bytes 16-29 of xile3.grf, and only when they hold the value the patcher cannot read.
rem Put this file in the XileRetro folder (next to xile3.grf) and double-click it, then run the patcher.
rem It works on the xile3.grf in its own folder and deletes itself after a successful run.
cd /d "%~dp0"
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
 "$p = Join-Path (Get-Location) 'xile3.grf';" ^
 "if (-not (Test-Path $p)) { Write-Host 'xile3.grf not found. Put FixPatcher.bat in your XileRetro folder (next to xile3.grf) and run it there.'; exit 1 }" ^
 "try { $f = [IO.File]::Open($p, 'Open', 'ReadWrite') } catch { Write-Host 'Cannot change xile3.grf: close the game and the patcher first, then run this again. If the game is in Program Files, right-click FixPatcher.bat and choose Run as administrator.'; exit 1 }; $h = New-Object byte[] 30; [void]$f.Read($h, 0, 30);" ^
 "$magic = [Text.Encoding]::ASCII.GetString($h, 0, 15);" ^
 "$bad = -join ($h[16..29] | %% { $_.ToString('x2') });" ^
 "if ($magic -ne 'Master of Magic') { $f.Close(); Write-Host 'xile3.grf is not a GRF file, nothing changed.'; exit 1 }" ^
 "if ($bad -eq '0102030405060708090a0b0c0d0e') { $f.Close(); Write-Host 'Already fixed, nothing to do.'; exit 0 }" ^
 "if ($bad -ne '000102030405060708090a0b0c0d') { $f.Close(); Write-Host 'Unexpected header, nothing changed.'; exit 1 }" ^
 "[void]$f.Seek(16, 0); $f.Write([byte[]](1..14), 0, 14); $f.Close(); Write-Host 'Fixed. You can run the patcher now.'"
set "rc=%errorlevel%"
if not "%rc%"=="0" (
  echo.
  echo FixPatcher.bat stays here so you can run it again.
  pause
  exit /b %rc%
)
echo.
echo This file will now delete itself.
pause
(goto) 2>nul & del "%~f0"
