@echo off

rem %1% = SciteDefaultHome
rem %2% = Command
rem %3% = IP Address
rem %4% = Filepath
rem %5% = Filebasepath
rem %6% = Slot Number
rem %7% = SDOInfo 1
rem %8% = SDOInfo 2

FOR /F %%i IN ('dir /b "%~f1\toolchain\arm*"') DO set armpath=%%i

SET PATH=%~f1\toolchain;%~f1\toolchain\%armpath%\bin;%~f1\toolchain\%armpath%\arm-none-eabi\bin;%PATH%

IF "%2%" == "compile" (
 	if exist "%~f5\mapping.h" del "%~f5\mapping.h"
	if exist "%~f5\mapping.cpp" del "%~f5\mapping.cpp"
 	if exist "%~f5\mapping.txt" del "%~f5\mapping.txt"
 	if exist "%~f5\%~n4.elf" del "%~f5\%~n4.elf"
 	if exist "%~f5\%~n4.bin" del "%~f5\%~n4.bin"
 	if exist "%~f5\%~n4.usr" del "%~f5\%~n4.usr"
	mapvars.exe "%~f1\toolchain" "%~4" "%~5"
	if errorlevel 1 goto mappingerror
	arm-none-eabi-gcc -nostdlib -fno-exceptions -fmessage-length=0 -fno-common -mcpu=cortex-m3 -O2 -mthumb -Wall -static -fno-common -fgcse-after-reload -fno-builtin -fomit-frame-pointer -fdata-sections -ffunction-sections -Wl,--gc-sections -I "%~f1\toolchain" -I "%~f5" -T "%~f1\toolchain\user.ld" -o "%~f5\%~n4.elf" "%~f5\build.cpp" "%~f5\mapping.cpp" "%~f1\toolchain\wrapper.o"
	if errorlevel 1 goto compilererror
	del "%~f5\build.cpp"
	objcopy -O binary "%~f5\%~n4.elf" "%~f5\%~n4.bin"
	vmm_tool "%~f5\%~n4.bin" "%~f5\mapping.txt" "%~f5\%~n4.usr"
	if errorlevel 1 goto linkererror
	goto end
)

IF "%2%" == "startNanoIP" (
	start http://%3%
	goto end
)

IF "%2%" == "transfer" (
	upload "%~f5\%~n4.usr" %~3 /fs/config/%~n4.usr
	if errorlevel 1 goto connectionerror
	IF "%6%" == "00" goto end
	NanoRESTQuery %~3 2304 %~7%
	if errorlevel 1 goto communicationerror
	NanoRESTQuery %~3 2304 %~8%
	goto end
)

IF "%2%" == "start" (
	IF "%6%" == "00" goto sloterror
	NanoRESTQuery %~3 2303 00 %6%
	if errorlevel 1 goto communicationerror
	NanoRESTQuery %~3 2300 00 00000001
	echo Start command successfully sent!
	goto end
	:sloterror
	echo Please select a program slot!
	goto end
)

IF "%2%" == "stop" (
	NanoRESTQuery %~3 2300 00 00000000
	if errorlevel 1 goto communicationerror
	echo Stop command successfully sent!
	goto end
)

:mappingerror
echo !!! Mapping Error !!!
del "%~f5\build.cpp"
echo.
exit 1

:compilererror
echo !!! Compiler Error !!!
del "%~f5\build.cpp"
echo.
exit 1

:linkererror
echo !!! Linker Error !!!
echo.
exit 1

:connectionerror
echo !!! Connection Error !!!
echo.
exit 1

:communicationerror
echo !!! Communication Error !!!
echo.
exit 1

:end
echo.
exit 0
