@echo off
setlocal enabledelayedexpansion

REM Change current directory to the location of this batch file
cd /d %~dp0

REM Remove old input and output data
rmdir /s /q ..\SRC\Excel2MaiMLProtocol\INPUT\excel
rmdir /s /q ..\SRC\Excel2MaiMLProtocol\INPUT\others
rmdir /s /q ..\SRC\Excel2MaiMLProtocol\OUTPUT

mkdir ..\SRC\Excel2MaiMLProtocol\INPUT\excel
mkdir ..\SRC\Excel2MaiMLProtocol\INPUT\others
mkdir ..\SRC\Excel2MaiMLProtocol\OUTPUT

REM Copy new input data files from DATAFILES to SRC
xcopy /Y /Q .\DATAFILES\Excel2MaiMLProtocol\INPUT\excel\* ..\SRC\Excel2MaiMLProtocol\INPUT\excel\
xcopy /Y /Q .\DATAFILES\Excel2MaiMLProtocol\INPUT\others\* ..\SRC\Excel2MaiMLProtocol\INPUT\others\
xcopy /Y /Q .\DATAFILES\Excel2MaiMLProtocol\INPUT\users\usersettings.py ..\SRC\Excel2MaiMLProtocol\USERS\

REM Get the first Excel filename from the input folder
for %%f in (.\DATAFILES\Excel2MaiMLProtocol\INPUT\excel\*.xlsx) do (
    set "EXCEL=%%~nxf"
    goto :found_excel
)
:found_excel

REM Rewrite usersettings.py with the selected Excel filename
powershell -Command "(Get-Content -Encoding UTF8 ..\SRC\Excel2MaiMLProtocol\USERS\usersettings.py) -replace '(_IN_EXCEL_FILENAME = ).*', '$1\"%EXCEL%\"' | Set-Content -Encoding UTF8 ..\SRC\Excel2MaiMLProtocol\USERS\usersettings.py"

REM Activate virtual environment and run Python script
call ..\SRC\Handson_venv\Scripts\activate.bat
echo on
python ..\SRC\Excel2MaiMLProtocol\excel2protocolMaiML2.py

REM Copy output files to DATAFILES
xcopy /Y /Q ..\SRC\Excel2MaiMLProtocol\OUTPUT\*.maiml .\DATAFILES\Excel2MaiMLProtocol\OUTPUT\

REM Deactivate virtual environment
call deactivate

echo completed.
pause
