@REM ============================================================================
@REM CreateS19_Unified_V2.bat - Unified S19 File Generator for TC23X/TC33X/TC36X
@REM ============================================================================
@REM Version: V2 - Uses pre-calculated CRC FlashDriver files
@REM ============================================================================
@REM
@REM IMPORTANT: Before using this script, run CreateFlashDriverCRC.bat once to
@REM generate FlashDriver files with pre-calculated RAM CRC:
@REM   - Tc234_Project_FLS_CRC.hex (TC23X)
@REM   - Tc334_Project_FLS_CRC.hex (TC33X)
@REM   - Tc364_Project_FLS_CRC.hex (TC36X)
@REM
@REM This version skips RAM CRC calculation during build, only calculating PFlash CRC.
@REM ============================================================================
@REM
@REM Usage:
@REM   CreateS19_Unified_V2.bat <ProjDirPath> <BuildArtifactFileBaseName> <WorkspaceLoc> [ConfigName] [ChipType]
@REM
@REM Parameters:
@REM   %1 - Project directory path (ADS: ${ProjDirPath})
@REM   %2 - Build artifact base name without extension (ADS: ${BuildArtifactFileBaseName})
@REM   %3 - Workspace root directory path (ADS: ${workspace_loc})
@REM   %4 - Build configuration directory name (ADS: ${ConfigName}), default: Debug
@REM   %5 - Chip type (TC23X/TC33X/TC36X), auto-detected from ADS CPU field if not specified
@REM
@REM ADS Post-build steps configuration example:
@REM   TC23X: cmd /c "${workspace_loc}\S19_gen\CreateS19_Unified_V2.bat" "${ProjDirPath}" "${BuildArtifactFileBaseName}" "${workspace_loc}" "${ConfigName}" "TC23X"
@REM   TC33X: cmd /c "${workspace_loc}\S19_gen\CreateS19_Unified_V2.bat" "${ProjDirPath}" "${BuildArtifactFileBaseName}" "${workspace_loc}" "${ConfigName}" "TC33X"
@REM   TC36X: cmd /c "${workspace_loc}\S19_gen\CreateS19_Unified_V2.bat" "${ProjDirPath}" "${BuildArtifactFileBaseName}" "${workspace_loc}" "${ConfigName}" "TC36X"
@REM
@REM ============================================================================

@echo off
@REM Use call :main to isolate parameter expansion from parsing context
call :main %*
exit /b %errorlevel%

:main
setlocal enabledelayedexpansion

@REM ============================================================================
@REM Capture all parameters at the very beginning of :main subroutine
@REM ============================================================================
set "ARG1=%~1"
set "ARG2=%~2"
set "ARG3=%~3"
set "ARG4=%~4"
set "ARG5=%~5"

@REM ============================================================================
@REM Parameter validation - using goto instead of if blocks
@REM ============================================================================
if not "!ARG1!"=="" goto :arg1_ok
echo [ERROR] Missing parameter: Project directory path
echo.
echo Usage:
echo   CreateS19_Unified_V2.bat ^<ProjDirPath^> ^<BuildArtifactFileBaseName^> ^<WorkspaceLoc^> [ConfigName] [ChipType]
echo.
echo ADS Post-build steps example:
echo   cmd /c "${workspace_loc}\S19_gen\CreateS19_Unified_V2.bat" "${ProjDirPath}" "${BuildArtifactFileBaseName}" "${workspace_loc}" "${ConfigName}" "TC23X"
exit /b 1
:arg1_ok

if not "!ARG2!"=="" goto :arg2_ok
echo [ERROR] Missing parameter: Build artifact base name
exit /b 1
:arg2_ok

if not "!ARG3!"=="" goto :arg3_ok
echo [ERROR] Missing parameter: Workspace root directory
exit /b 1
:arg3_ok

@REM ============================================================================
@REM Path configuration
@REM ============================================================================
set "PROJ_DIR=!ARG1!"
set "BUILD_NAME=!ARG2!"
set "WORKSPACE=!ARG3!"

@REM Build configuration directory name (default: Debug)
set "CONFIG_NAME=!ARG4!"
if "!CONFIG_NAME!"=="" set "CONFIG_NAME=Debug"

@REM Convert forward slashes to backslashes (ADS uses forward slashes)
set "PROJ_DIR=!PROJ_DIR:/=\!"
set "WORKSPACE=!WORKSPACE:/=\!"

@REM ============================================================================
@REM Chip type detection - using goto instead of if/else if chain
@REM Priority: explicit parameter > ADS .cproject CPU field
@REM ============================================================================
set "CHIP_TYPE="

@REM Priority 1: explicit parameter (TC23X/TC33X/TC36X format)
if /i "!ARG5!"=="TC23X" set "CHIP_TYPE=TC23X" & goto :chip_detected
if /i "!ARG5!"=="TC33X" set "CHIP_TYPE=TC33X" & goto :chip_detected
if /i "!ARG5!"=="TC36X" set "CHIP_TYPE=TC36X" & goto :chip_detected

@REM Priority 2: detect from ADS .cproject file CPU field
@REM Use piped findstr to avoid echo issues with XML special characters (< > &)
set "CPROJECT_FILE=!PROJ_DIR!\.cproject"
if not exist "!CPROJECT_FILE!" goto :chip_detect_failed

findstr /i "com.tasking.ctc.cpu" "!CPROJECT_FILE!" 2>nul | findstr /i "value=\"tc23x\"" >nul
if !errorlevel! equ 0 set "CHIP_TYPE=TC23X" & goto :chip_detected
findstr /i "com.tasking.ctc.cpu" "!CPROJECT_FILE!" 2>nul | findstr /i "value=\"tc33x\"" >nul
if !errorlevel! equ 0 set "CHIP_TYPE=TC33X" & goto :chip_detected
findstr /i "com.tasking.ctc.cpu" "!CPROJECT_FILE!" 2>nul | findstr /i "value=\"tc36x\"" >nul
if !errorlevel! equ 0 set "CHIP_TYPE=TC36X" & goto :chip_detected

:chip_detect_failed
echo [ERROR] Cannot detect chip type. Please specify as 5th parameter ^(TC23X/TC33X/TC36X^) or ensure ADS .cproject file exists with CPU field.
exit /b 1

:chip_detected
echo [INFO] Chip type: !CHIP_TYPE!

@REM ============================================================================
@REM Chip-specific configuration - using goto instead of if/else if
@REM Uses pre-calculated CRC FlashDriver files (*_CRC.hex)
@REM ============================================================================
goto :config_!CHIP_TYPE!

:config_TC23X
set "FLS_DRV_NAME=Tc234_Project_FLS_CRC.hex"
set "DUAL_PFLASH=0"
goto :config_done

:config_TC33X
set "FLS_DRV_NAME=Tc334_Project_FLS_CRC.hex"
set "DUAL_PFLASH=0"
goto :config_done

:config_TC36X
set "FLS_DRV_NAME=Tc364_Project_FLS_CRC.hex"
set "DUAL_PFLASH=1"
goto :config_done

:config_done

@REM Common configuration
set "PFLASH0_START=0x80010000"
set "PFLASH0_END=0x801fffff"
set "PFLASH0_CRC_ADDR=0x801ffffc"
set "PFLASH1_START=0x80300000"
set "PFLASH1_END=0x804fffff"
set "PFLASH1_CRC_ADDR=0x804ffffc"

@REM ============================================================================
@REM Base variable setup
@REM ============================================================================
set "HEXVIEW_EXE=!WORKSPACE!\S19_gen\Hexview\hexview.exe"
set "FLS_DRV_FILE=!WORKSPACE!\S19_gen\FlashDriver\!FLS_DRV_NAME!"
set "APP_HEX_FILE=!PROJ_DIR!\!CONFIG_NAME!\!BUILD_NAME!.hex"
set "OUTPUT_FILE=!PROJ_DIR!\!CONFIG_NAME!\!BUILD_NAME!.s19"

echo ============================================================================
echo CreateS19 Unified V2 - S19 File Generator for !CHIP_TYPE! [Pre-calculated CRC]
echo ============================================================================
echo.
echo [INFO] Project directory: "!PROJ_DIR!"
echo [INFO] Build name: "!BUILD_NAME!"
echo [INFO] Workspace: "!WORKSPACE!"
echo [INFO] Config name: "!CONFIG_NAME!"
echo [INFO] Chip type: !CHIP_TYPE!
echo [INFO] Output file: "!OUTPUT_FILE!"
echo.

@REM ============================================================================
@REM File existence check - using goto instead of if blocks
@REM ============================================================================
echo [CHECK] Verifying required files...

if exist "!HEXVIEW_EXE!" goto :hexview_ok
echo [ERROR] HexView.exe not found: "!HEXVIEW_EXE!"
exit /b 1
:hexview_ok
echo [OK] HexView.exe found

if exist "!FLS_DRV_FILE!" goto :flsdrv_ok
echo [ERROR] Flash driver file not found: "!FLS_DRV_FILE!"
echo [HINT] Run CreateFlashDriverCRC.bat first to generate pre-calculated CRC files.
exit /b 1
:flsdrv_ok
echo [OK] Flash driver file found: !FLS_DRV_NAME!

if exist "!APP_HEX_FILE!" goto :apphex_ok
echo [ERROR] Application HEX file not found: "!APP_HEX_FILE!"
exit /b 1
:apphex_ok
echo [OK] Application HEX file found

@REM ============================================================================
@REM Check if PFlash first segment starts at 0x80010000
@REM Verify the first Extended Linear Address record in PFlash range is 0x8001
@REM ============================================================================
set "FIRST_PFLASH_EA="
for /f "tokens=*" %%a in ('findstr /c:":0200000480" /c:":02000004A0" "!APP_HEX_FILE!" 2^>nul') do (
    if not defined FIRST_PFLASH_EA set "FIRST_PFLASH_EA=%%a"
)
if not defined FIRST_PFLASH_EA goto :pflash_addr_fail
echo !FIRST_PFLASH_EA! | findstr ":020000048001" >nul
if !errorlevel! equ 0 goto :pflash_addr_ok

:pflash_addr_fail
echo [ERROR] PFlash first segment does not start at 0x80010000.
echo [ERROR] The application HEX file may be compiled with non-cacheable address space ^(0xA0^).
echo [ERROR] Please verify linker configuration. Aborting S19 generation.
exit /b 1
:pflash_addr_ok
echo [OK] PFlash address verified: first segment starts at 0x80010000

echo.

@REM ============================================================================
@REM Copy Flash Driver to build output directory
@REM ============================================================================
echo [GENERATE] Creating S19 file with merged commands...

copy "!FLS_DRV_FILE!" "!PROJ_DIR!\!CONFIG_NAME!\!FLS_DRV_NAME!" >nul
if !errorlevel! equ 0 goto :copy_ok
echo [ERROR] Failed to copy flash driver file
exit /b 1
:copy_ok

@REM ============================================================================
@REM Generate S19 file with merged hexview command - using goto for branching
@REM RAM CRC is pre-calculated in FlashDriver, only calculate PFlash CRC here
@REM ============================================================================
pushd "!PROJ_DIR!\!CONFIG_NAME!"

if "!DUAL_PFLASH!"=="1" goto :run_dual_pflash
goto :run_single_pflash

:run_single_pflash
@REM TC23X/TC33X single PFLASH configuration (PFlash CRC only, RAM CRC pre-calculated)
"!HEXVIEW_EXE!" /MO:!FLS_DRV_NAME!;0x00+!BUILD_NAME!.hex;0x00:!PFLASH0_START!-!PFLASH0_END! /FP:FF /FR:!PFLASH0_START!-!PFLASH0_END! /CS9:@!PFLASH0_CRC_ADDR!;!PFLASH0_START!-0x801ffffb /s /XS:32 -o"!BUILD_NAME!.s19"
goto :hexview_done

:run_dual_pflash
@REM TC36X dual PFLASH configuration (PFlash CRC only, RAM CRC pre-calculated)
"!HEXVIEW_EXE!" /MO:!FLS_DRV_NAME!;0x00+!BUILD_NAME!.hex;0x00:!PFLASH0_START!-!PFLASH0_END!+!BUILD_NAME!.hex;0x00:!PFLASH1_START!-!PFLASH1_END! /FP:FF /FR:!PFLASH0_START!-!PFLASH0_END!:!PFLASH1_START!-!PFLASH1_END! /CS9:@!PFLASH0_CRC_ADDR!;!PFLASH0_START!-0x801ffffb:@!PFLASH1_CRC_ADDR!;!PFLASH1_START!-0x804ffffb /s /XS:32 -o"!BUILD_NAME!.s19"
goto :hexview_done

:hexview_done
if !errorlevel! equ 0 goto :hexview_success
del /f /q !FLS_DRV_NAME! >nul 2>&1
popd
echo [ERROR] Failed to generate S19 file
exit /b 1
:hexview_success
popd

@REM ============================================================================
@REM Clean up temporary files
@REM ============================================================================
del /f /q "!PROJ_DIR!\!CONFIG_NAME!\!FLS_DRV_NAME!" >nul 2>&1
echo [OK] S19 file generated successfully

@REM ============================================================================
@REM Verify output file - using goto instead of if blocks
@REM ============================================================================
echo.
echo [CHECK] Verifying output file...
if exist "!OUTPUT_FILE!" goto :output_ok
echo [ERROR] Output file was not created: "!OUTPUT_FILE!"
exit /b 1
:output_ok
echo [OK] Output file created successfully

echo.
echo ============================================================================
echo [SUCCESS] S19 file generated successfully for !CHIP_TYPE!
echo Output: "!OUTPUT_FILE!"
echo ============================================================================

endlocal
exit /b 0
