@echo off
setlocal enabledelayedexpansion
set BASE=%~dp0
set CMD=%BASE%cmd.txt
set STATUS=%BASE%status.txt

:loop
    if exist "%CMD%" (
        for /f "tokens=* delims=" %%A in (%CMD%) do set COMMAND=%%A
        del "%CMD%"

        if "!COMMAND!"=="start" sc start KeyenceTCPListener >nul
        if "!COMMAND!"=="stop" sc stop KeyenceTCPListener >nul
        if "!COMMAND!"=="restart" (
            sc stop KeyenceTCPListener >nul
            timeout /t 2 >nul
            sc start KeyenceTCPListener >nul
        )
    )

    for /f "tokens=3 delims=: " %%S in ('sc query KeyenceTCPListener ^| find "STATE"') do set SVCSTATE=%%S
    echo Service status: !SVCSTATE! > "%STATUS%"

    timeout /t 2 >nul
goto loop
