@echo off

:menu
cls
echo ==========================
echo    NesGlitcher Launcher
echo ==========================
echo.

set count=0
echo Found ROM files:
echo ----------------
echo 0. CONTINUE SEARCHING
echo.

dir /b *.nes *.fds *.bin *.rom 2>nul > temp_list.txt

for /f "tokens=*" %%f in (temp_list.txt) do (
    set /a count+=1
    call echo %%count%%. %%f
    call set "file_%%count%%=%%f"
)

del temp_list.txt 2>nul

echo.

if %count%==0 (
    echo No NES ROM files found.
    echo Supported: .nes .fds .bin .rom
    echo.
    pause
    exit /b
)

:input
set choice=
set /p "choice=Enter file number (0~%count%) or 'q' to quit: "

if "%choice%"=="q" exit /b
if "%choice%"=="0" goto launch
if "%choice%"=="" goto input

set valid=0
for /l %%i in (1,1,%count%) do (
    if "%choice%"=="%%i" set valid=1
)

if "%valid%"=="0" goto invalid

call set selectedFile=%%file_%choice%%%

echo.
echo Launching: %selectedFile%
echo.

:launch
set glitcherExe=
for %%e in (nesglitcher*.exe) do set glitcherExe=%%e

if "%glitcherExe%"=="" (
    echo Error: nesglitcher*.exe not found!
    echo.
    pause
    exit /b
)

if "%choice%"=="0" "%glitcherExe%"&goto menu

echo Running: %glitcherExe% "%selectedFile%"
echo.
"%glitcherExe%" "%selectedFile%"

goto menu

:invalid
echo Invalid input. Please enter a number between 0 and %count%.
goto input