@echo off
REM ======================================
REM CAN BIN to MDF Batch Converter (Advanced)
REM ======================================

REM Find DBC file
set DBC_FILE=
for %%f in (*.dbc) do (
    set DBC_FILE=%%f
    goto found_dbc
)

:found_dbc
if "%DBC_FILE%"=="" (
    echo [ERROR] DBC file not found!
    pause
    exit /b 1
)

echo DBC File: %DBC_FILE%
echo.

REM Count BIN files
set COUNT=0
for %%f in (*.bin) do set /a COUNT+=1

if %COUNT%==0 (
    echo [ERROR] No BIN files to convert!
    pause
    exit /b 1
)

echo Total files: %COUNT%
echo.

REM Select compression level
echo Select compression level:
echo ======================================
echo [0] No compression (Fast read, Large file)
echo     - Read speed: ***** (Very fast)
echo     - File size: 171MB
echo     - Use case: Immediate analysis
echo.
echo [1] deflate compression (Balanced)
echo     - Read speed: *** (Normal)
echo     - File size: 3.6MB (98%% compression)
echo     - Use case: General use
echo.
echo [2] transposed compression (Maximum)
echo     - Read speed: * (Slow)
echo     - File size: 1.2MB (99%% compression)
echo     - Use case: Long-term archiving
echo ======================================
echo.

set /p COMPRESSION="Select (0/1/2) [default=0]: "
if "%COMPRESSION%"=="" set COMPRESSION=0

if "%COMPRESSION%"=="0" (
    echo Selected: No compression - Fast read
) else if "%COMPRESSION%"=="1" (
    echo Selected: deflate - Balanced
) else if "%COMPRESSION%"=="2" (
    echo Selected: transposed - Maximum compression
) else (
    echo [ERROR] Invalid selection. Please select 0, 1, or 2.
    pause
    exit /b 1
)

echo.
echo Starting conversion...
echo ======================================
echo.

REM Record start time
set START_TIME=%TIME%

REM Convert each BIN file
setlocal enabledelayedexpansion
set PROCESSED=0
set SUCCESS=0
set FAILED=0

for %%f in (*.bin) do (
    set /a PROCESSED+=1
    echo [!PROCESSED!/%COUNT%] Converting: %%f
    
    python can_bin_to_mdf.py -d "%DBC_FILE%" -i "%%f" -o "./" -c %COMPRESSION%
    
    if errorlevel 1 (
        echo   [FAIL] %%f
        set /a FAILED+=1
    ) else (
        echo   [OK] %%f
        set /a SUCCESS+=1
    )
    echo.
)

REM Record end time
set END_TIME=%TIME%

echo ======================================
echo Conversion Complete!
echo ======================================
echo Total:    %COUNT%
echo Success:  %SUCCESS%
echo Failed:   %FAILED%
echo Start:    %START_TIME%
echo End:      %END_TIME%
echo ======================================
echo.

REM List generated MDF files with size
echo Generated MDF files:
for %%f in (*.mf4) do (
    set SIZE=%%~zf
    set /a SIZE_MB=!SIZE! / 1048576
    echo   - %%f (!SIZE_MB! MB^)
)
echo.

REM Calculate total MDF file size
set TOTAL_SIZE=0
for %%f in (*.mf4) do (
    set SIZE=%%~zf
    set /a TOTAL_SIZE+=!SIZE!
)
set /a TOTAL_MB=!TOTAL_SIZE! / 1048576
echo Total MDF size: !TOTAL_MB! MB
echo.

pause
