@echo off
setlocal enabledelayedexpansion

:: Buffer Reader Batch Script
:: Calls the RP2350 Buffer Reader Python script with various options

echo ===============================================
echo    RP2350 Display Buffer Reader
echo ===============================================
echo.

:: Check if Python is available
python --version >nul 2>&1
if errorlevel 1 (
    echo ERROR: Python is not installed or not in PATH
    echo Please install Python and try again.
    pause
    exit /b 1
)

:: Check if Buffer_Reader.py exists
if not exist "Buffer_Reader.py" (
    echo ERROR: Buffer_Reader.py not found in current directory
    echo Please make sure the script is in the same folder as this batch file.
    pause
    exit /b 1
)

:: Initialize Repeat_Counter for file naming
set /a repeat_counter=1

:: Check command line arguments
if "%~1"=="" goto :interactive_mode
if "%~1"=="/?" goto :show_help
if "%~1"=="--help" goto :show_help

:: Direct mode - use command line arguments
set "port_input=%~1"
set "image_file_base=%~2"
set "csv_file_base=%~3"

:: Process port input - add COM prefix if not present
if "!port_input:~0,3!"=="COM" (
    set "serial_port=!port_input!"
) else (
    set "serial_port=COM!port_input!"
)

goto :set_default_files

:interactive_mode
echo Interactive Mode
echo ================
echo.

:: Get serial port number
set "port_input="
set /p "port_input=Enter COM port number (e.g., 3 for COM3): "
if "!port_input!"=="" (
    echo ERROR: Port number is required
    pause
    exit /b 1
)

:: Add COM prefix if not already present
if "!port_input:~0,3!"=="COM" (
    set "serial_port=!port_input!"
) else (
    set "serial_port=COM!port_input!"
)

:: Get image filename (optional)
set "image_file_base="
set /p "image_file_base=Enter image filename (press Enter for default): "

:: Get CSV filename (optional)
set "csv_file_base="
set /p "csv_file_base=Enter CSV filename (press Enter for default): "


:set_default_files
if "!image_file_base!"=="" set "image_file_base=capture"
if "!csv_file_base!"=="" set "csv_file_base=pixels"

:: Check if image_file_base has an extension and remove it
for %%f in ("!image_file_base!") do (
    set "image_file_base=%%~nf"
)

:: Check if image_file_base has an extension and remove it
for %%f in ("!csv_file_base!") do (
    set "csv_file_base=%%~nf"
)

set "image_file=!image_file_base!_!repeat_counter!.png"
set "csv_file=!csv_file_base!_!repeat_counter!.csv"


:main_loop
echo.
echo Configuration:
echo   Serial Port: !serial_port!
echo   Image File:  !image_file!
echo   CSV File:    !csv_file!
echo.

:run_script
echo.
echo Starting buffer read...
echo Command: python Buffer_Reader.py "!serial_port!" "!image_file!" "!csv_file!"
echo.

:: Run the Python script
python Buffer_Reader.py "!serial_port!" "!image_file!" "!csv_file!"

:: Check if the script ran successfully
if errorlevel 1 (
    echo.
    echo ERROR: Script execution failed
    goto :ask_repeat
) else (
    echo.
    echo SUCCESS: Buffer read completed successfully!
    echo   Image saved to: !image_file!
    echo   CSV saved to:   !csv_file!
    
    :: Automatically open image with GIMP
    if exist "!image_file!" (
        echo.
        echo Opening image with GIMP...
        start "" "gimp" "!image_file!" 2>nul
        if errorlevel 1 (
            echo Warning: Could not open GIMP. Please check if GIMP is installed and in PATH.
            echo You can manually open the file: !image_file!
        )
    )
)

:ask_repeat
echo.
echo Press ENTER to repeat readout with same settings
echo Press ESC or N + ENTER to exit
set /p "repeat_choice="

:: Check if user pressed just Enter (empty input)
if "!repeat_choice!"=="" (
    :: Increment counter for repeat runs
    set /a repeat_counter+=1
    
	set "image_file=!image_file_base!_!repeat_counter!.png"
	set "csv_file=!csv_file_base!_!repeat_counter!.csv"
	  
    goto :main_loop
)

:: Check for exit conditions
if /i "!repeat_choice!"=="N" goto :exit_script
if "!repeat_choice!"=="" goto :exit_script

:: If user entered something else, treat as exit
goto :exit_script

:exit_script
echo.
echo Exiting...
pause
exit /b 0

:increment_filename
:: Function to increment filename counter intelligently
:: %1 = input filename, %2 = variable name to store result
setlocal enabledelayedexpansion
set "filename=%~1"
set "return_var=%~2"

:: Extract name and extension
for %%f in ("!filename!") do (
    set "name=%%~nf"
    set "ext=%%~xf"
)

:: Check if filename ends with _number pattern
set "counter=1"
set "base_name=!name!"

:: Look for _number at the end of the filename
for /f "tokens=1,2 delims=_" %%a in ("!name!") do (
    set "potential_base=%%a"
    set "potential_counter=%%b"
    
    if "!potential_counter!" neq "" (
        :: Check if the part after _ is a number
        set "is_number=1"
        for /f "delims=0123456789" %%x in ("!potential_counter!") do set "is_number=0"
        
        if !is_number! equ 1 (
            :: It's a number, so increment it
            set /a counter=!potential_counter!+1
            set "base_name=!potential_base!"
        )
    )
)

:: Build new filename
set "new_filename=!base_name!_!counter!!ext!"

:: Return the result
endlocal & set "%return_var%=%new_filename%"
goto :eof

:show_help
echo.
echo USAGE:
echo   %~nx0                           - Interactive mode
echo   %~nx0 [port_number]             - Use default filenames (e.g., %~nx0 3)
echo   %~nx0 [port_number] [image]     - Specify image filename (e.g., %~nx0 3 my_screen.png)
echo   %~nx0 [port_number] [image] [csv] - Specify both filenames
echo.
echo EXAMPLES:
echo   %~nx0
echo   %~nx0 3                         (will use COM3)
echo   %~nx0 4 my_screen.png          (will use COM4)
echo   %~nx0 3 my_screen.png data.csv (will use COM3)
echo.
echo Note: You can enter just the port number (e.g., 3) and COM will be added automatically
echo      Generated images will automatically open in GIMP
echo.
echo OPTIONS:
echo   /?     Show this help
echo   --help Show this help
echo.
pause
exit /b 0