@echo off
::设置Keil执行文件位置
::set UV=D:\Keil_v5\UV4\UV4.exe
::或者添加Keil_v5\UV4文件夹路径到系统环境变量中
set UV=UV4

set SRC_DIR=.\
echo "start..." > result.log
echo "" > failed.txt
setlocal enabledelayedexpansion

:: 获取命令行输入参数，如果没有参数则默认为0（即不跳过任何工程）
set skip_count=0
if "%~1" NEQ "" (
    set /a skip_count=%~1
    if %skip_count% lss 0 (
        echo "输入的跳过数量不能为负数，按默认设置执行（不跳过任何工程）"
        set skip_count=0
    )
)
set current_skip=0
for /r "%SRC_DIR%" %%f in (*.uvproj) do (
    set /a current_skip+=1
    setlocal
    if !current_skip! geq %skip_count% (
        set LOG_FILE=%%~dpfbuild.log
        echo Compiling project: %%f
        echo !LOG_FILE!
        
        %UV% -r "%%f" -l "!LOG_FILE!" -j0 -t "Target 1"
        
        if errorlevel 2 (
            echo "errorlevel:" !errorlevel!
            echo %%f >> failed.txt
            echo Error occurred while compiling: %%f
            echo Error occurred while compiling: %%f >> result.log
            echo See build.log for details: !LOG_FILE! >> result.log
            echo !current_skip!
            endlocal
            goto :end
        )
    ) else (
        echo Skipping project: %%f !current_skip!
        echo Skipping project: %%f >> result.log
        
    )
    endlocal
)
echo Total: !current_skip!
endlocal
:end

if %errorlevel% neq 0 (
    echo Build failed. See build.log for details.
    exit /b 1
)
echo Build successful.
exit /b 0