@echo off

:: initialise colored text output... batch coloring is much much harder than it
::  should be (http://stackoverflow.com/a/5344911)
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)
goto afterColorInit
:color
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
echo.
exit /b 
:afterColorInit

:: -

:: Build pxl to exe

set NASM=binary_dependencies\nasm.exe
set LD=binary_dependencies\ld.exe
set LIB_PATH=binary_dependencies\
set RTL_PATH=%~dp0rtl\

:: FIXME: Everything gets assembled with everything
set NASM_ARGS=-DOS_WINDOWS -f win32 -i%RTL_PATH% -p rtl\pexl_rtl.h.asm

:: FIXME: Everything gets linked with everything
:: Adding '--as-needed --gc-sections --print-gc-sections' doesn't help
set LINK_ARGS=rtl\pexl_rtl_memory.o rtl\pexl_rtl_pxobject.o rtl\pexl_rtl_pxstring.o rtl\pexl_rtl_pxvector.o stdlib\conio.o stdlib\file.o stdlib\proc.o stdlib\string.o -nostdlib -epxlmain -s "%LIB_PATH%libkernel32.a" "%LIB_PATH%libmsvcrt.a"

if not exist %1.pxl (
	echo File %1.pxl doesn't exist!
	goto :EOF
)

if exist %1.exe del %1.exe
if exist %1.obj del %1.obj
if exist %1.asm del %1.asm

..\Debug\pexl-D.exe -i %1.pxl > %1.asm

%NASM% %NASM_ARGS% -o %1.obj %1.asm
if not "%ERRORLEVEL%" == "0" (
	call :maybefailure %1 "ASSEMBLING FAILED"
	goto :EOF
)

%LD% %1.obj %LINK_ARGS% -o %1.exe
if not "%ERRORLEVEL%" == "0" (
	call :maybefailure %1 "LINKING FAILED"
	goto :EOF
)

del %1.obj
%1

set BUILDRES=%ERRORLEVEL%
echo Return: %BUILDRES%

if not exist %1.expect goto noexpect
	set /P EXPECTED=< "%1.expect"
	if "%EXPECTED%" == "%BUILDRES%" (
		:: echo Test passed
		call :color 0a "Test Passed"
	) else (
		call :maybefailure %1 "TEST FAILED"
	)
:noexpect

goto :EOF


:maybefailure
if exist %1.xfail goto maybefailure_xfail
call :color 0c %2
goto :maybefailure_end
:maybefailure_xfail
call :color 0e "Test expected to fail"
:maybefailure_end
exit /b