@echo off

setlocal

set scr="g"

:parse
set arg=%1
if /I "%1" == "" (
    rem done
) else if /I .%arg%==./1394 (
    set ConnectArgs=1394:channel=0
    shift
    goto parse
) else if /I .%arg%==./com1 (
    set ConnectArgs=com:port=\\.\com1,baud=115200
    shift
    goto parse
) else if /I .%arg%==./com2 (
    set ConnectArgs=com:port=\\.\com2,baud=115200
    shift
    goto parse
) else if /I .%arg%==./com3 (
    set ConnectArgs=com:port=\\.\com3,baud=115200
    shift
    goto parse
) else if /I .%arg%==./pipe (
    set ConnectArgs=com:pipe,port=\\.\pipe\kd,resets=0,reconnect
    shift
    goto parse
) else if /I .%arg%==./f (
    set scr="sxe vcpp;g"
    shift
    goto parse
)

if not defined ConnectArgs (
    call :Usage %0
    exit /b 1
)

if not defined SINGULARITY_BUILD_SETTINGS (
    echo The environment variable SINGULARITY_BUILD_SETTINGS is not defined,
    echo this script has no way to devine paths without it!  Run setenv.cmd.
    exit /b 1
)

@rem Read object file paths generated by build process
call %SINGULARITY_BUILD_SETTINGS%
if ErrorLevel 1 (
    echo %SINGULARITY_BUILD_SETTINGS% failed.
    exit /b 1
)

set DebuggerTitle=%TITLE% %arg:~1%

taskkill /F /FI "IMAGENAME EQ windbg.exe" /FI "WINDOWTITLE EQ %DebuggerTitle%*" 2>NUL 1>&2

start windbg.exe -k %ConnectArgs% -T "%DebuggerTitle%" -WX -W %SINGULARITY_ROOT%:%SINGULARITY_DISTRO_SUFFIX% -d -c %scr% %1 %2 %3 %4 %5 %6 %7 %8 %9

exit /b 0

:Usage

echo.Usage:
echo.    %~nx1 [options] ^<connectionType^>
echo.
echo.where ^<connectionType^> is one of:
echo.    /1394    Fire-wire.
echo.    /com1    Serial port 1.
echo.    /com2    Serial port 2.
echo.    /com3    Serial port 3.
echo.    /pipe    Named pipe to Virtual PC at \\.\pipe\kd.
echo.
echo.Options:
echo.    /f       Break on first chance exceptions.
