@echo off
setlocal enableextensions

:: Countermeasure vs tainted build environment by known third party utilities
set FIND=find
find /? >nul 2>&1
if errorlevel 1 (
	echo WARNING: GNU utilities in PATH can break MSVC
	echo.
	set FIND=findstr
)

:: Anchor to the project file path, otherwise the arguments would be invalid:
::
:: * In theory this is unnecessary, but it makes the process more transparent
::   to people unfamiliar with VS's not-so-well-explained behaviors
::
pushd "%~dp0..\projects\msvc\"
if errorlevel 1 exit /b 101

:: Validating arguments passed from Visual Studio to use as variables:
::
:: * Arguments with conflicting syntax can terminate the script abruptly
:: * 'GAS_EXTRA' argument isn't used in some cases
::
set GAS_SRCDIR=
set GAS_OBJDIR=
set GAS_EXTRA=
for /f "tokens=1,2*" %%A in ('echo %*') do (
	set GAS_SRCDIR=%%A
	set GAS_OBJDIR=%%B
	set GAS_EXTRA=%%C
)
set GAS_CLARG=%GAS_OBJDIR%
if defined GAS_EXTRA set GAS_CLARG=%GAS_OBJDIR% %GAS_EXTRA%

:: "Anti-PEBCAK":
::
:: * Ensure that 'GAS_SRCDIR' and 'GAS_OBJDIR' exist or are defined and send an
::   error signal if not
::
if not exist "%GAS_SRCDIR%asm_defines.c" exit /b 202
if not defined GAS_OBJDIR exit /b 303

:: Legacy code adaptation for this script:
::
:: * Delete the libraries previously generated by 'gawk' or this script
:: * CL's stuff/witchcraft, if all goes well it will generate 'asm_defines.obj'
::
del /f /q "%GAS_SRCDIR%asm_defines_*" 2>nul
cl /c /Fo%GAS_CLARG% /I ..\..\src "%GAS_SRCDIR%asm_defines.c"

:: If 'asm_defines.obj' does not exist, send error
if not exist "%GAS_OBJDIR%asm_defines.obj" exit /b 404
if "%USE_GAWK%" NEQ "1" goto native

:: Legacy code adaptation for 'gawk':
::
:: * Define 'USE_GAWK=1' to use 'gawk'
:: * A POSIX version of 'GAS_SRCDIR' is required for 'dest_dir' argument
::
set "GAS_SRCDIR2=%GAS_SRCDIR:\=/%"
set GAWK=..\..\..\mupen64plus-win32-deps\gawk-3.1.6-1\bin\gawk.exe
"%GAWK%" -v dest_dir="%GAS_SRCDIR2%" -f "%~dp0gen_asm_defines.awk" "%GAS_OBJDIR%asm_defines.obj"
goto log
:native

:: Adaptation of 'gen_asm_defines.awk' / 'gen_asm_script.sh':
::
:: 1. Display 'asm_defines.obj' as a list, looking only for patterns
::    '@ASM_DEFINE'
:: 2. Sort for easy reading, the result is interpreted as an array
::    with ' ' as default delimiter in the 'for' command
:: 3. The for's 'tokens=2,3' ignores pattern "1" (@ASM_DEFINE) and anything
::    beyond "3", take "2" (offset* value) as 'J' and "3" (hex* value) as 'K'
:: 4. Print current values and repeat steps 3 and 4 on the next line
::    until EOL is reached
::
for /f "tokens=2,3" %%J in ('type "%GAS_OBJDIR%asm_defines.obj" ^| %FIND% "@ASM_DEFINE" ^| sort') do (
	echo %%define %%J ^(%%K^)>>"%GAS_SRCDIR%asm_defines_nasm.h"
	echo #define %%J ^(%%K^)>>"%GAS_SRCDIR%asm_defines_gas.h"
)
:log

:: Display 'asm_defines_nasm.h' in the log
echo.
type "%GAS_SRCDIR%asm_defines_nasm.h"
echo.
exit /b 0
