@echo off
rem
rem Setup variables for temp directory and path to PDP-11 simulator
rem
rem set cpu11_tmp=R:\TEMP
rem set cpu11_sim=D:\ECC\PDP11

if "%cpu11_tmp%"=="" goto blank_tmp
if "%cpu11_sim%"=="" goto blank_sim
if "%cpu11_git%"=="" goto blank_git

if "%~1"=="" goto blank
if "%~1"=="all" goto all

call :ci %1
@echo SUCCESS
exit


:all
if exist .\a.mac call :ci a
if exist .\b.mac call :ci b
if exist .\c.mac call :ci c
if exist .\h.mac call :ci h
if exist .\j.mac call :ci j
if exist .\t.mac call :ci t
@echo SUCCESS
exit


:blank
echo.
echo Windows batch file to perform full CI cycle
echo.
echo Usage: ci test_name
echo Example: ci a - run a.mac test only ./vm1 project folder
echo          ci all - run all tests
exit


:blank_tmp
echo.
echo Environment variable cpu11_tmp should be set to temorary folder
exit


:blank_sim
echo.
echo Environment variable cpu11_sim should be set to RT11 simulator folder
exit


:blank_git
echo.
echo Environment variable cpu11_git should be set to the folder of cpu11 repo
exit


:ci
if "%~1"=="a" set sim_halt="# HALT @ 026044"
if "%~1"=="b" set sim_halt="# HALT @ 015560"
if "%~1"=="c" set sim_halt="# HALT @ 016376" 
if "%~1"=="h" set sim_halt="# HALT @ 004030"
if "%~1"=="j" set sim_halt="# HALT @ 034034" 
if "%~1"=="t" set sim_halt="# HALT @ 034616" 

if "%~1"=="a" set sim_time="#    Time: 2697350 ns"
if "%~1"=="b" set sim_time="#    Time: 2821630 ns"
if "%~1"=="c" set sim_time="#    Time: 3242330 ns" 
if "%~1"=="h" set sim_time="#    Time: 575910 ns"
if "%~1"=="j" set sim_time="#    Time: 3864530 ns" 
if "%~1"=="t" set sim_time="#    Time: 8797950 ns" 

call :build %1
@echo Simulating %1.mac
vsim -c -do ci.do > NULL
if %errorlevel% neq 0 exit
findstr -c:%sim_halt% transcript > NUL
if %errorlevel% neq 0 exit
findstr -c:%sim_time% transcript > NUL
if %errorlevel% neq 0 exit

set "lastoccur="
for /F "delims=" %%G in ('findstr -c:"# End time:" transcript') do set "lastoccur=%%G"
echo "%lastoccur%"
exit /b


:build
rem @echo Building %1.mac
if exist %cpu11_tmp%\%1.bin goto :tcopy

copy %1.mac %cpu11_tmp%\%1.mac >>NUL
echo macro hd2:%1.mac /list:hd2:%1.lst /object:hd2:%1.obj >%cpu11_tmp%\build.com
echo link hd2:%1.obj /execute:hd2:%1.lda /lda >>%cpu11_tmp%\build.com
%cpu11_sim%\pdp11.exe @hd2:build.com

srec_cat %cpu11_tmp%\%1.lda -dec_binary -o %cpu11_tmp%\%1.bin -binary
if %errorlevel% neq 0 exit
move vt52.log %cpu11_tmp%\vt52.log >>NUL

:tcopy
rem @echo Copying %1.bin
if not exist ..\..\..\..\tst\out mkdir ..\..\..\..\tst\out
srec_cat %cpu11_tmp%\%1.bin -binary --fill 0x00 0x0000 0x8000 -byte-swap 2 -o ..\..\..\..\tst\out\test.mem --VMem 16
srec_cat %cpu11_tmp%\%1.bin -binary --fill 0x00 0x0000 0x8000 -byte-swap 2 -o ..\..\..\..\tst\out\\test.hex -Intel
srec_cat %cpu11_tmp%\%1.bin -binary --fill 0x00 0x0000 0x8000 -byte-swap 2 -o ..\..\..\..\tst\out\\test.mif -Memory_Initialization_File 16 -obs=2
exit /b
