@echo off
set /a MINMEM="512"
set /a DEFAULTMEM="1024"

REM Test for var length > 2
if "%2"=="" (
	REM empty we know there is less than 2 args
) else (
	echo           Wrong Usage
	goto usage
)

if "%1"=="" (
	echo Running without arguments, Cassis starts with default memory %DEFAULTMEM% MB
	set /a MEM=DEFAULTMEM
	goto cmd
) else (
	goto searchHelp
)

REM just a security
goto usage

REM We parse the uniq argument here
:searchHelp
if "%1"=="-h" (
	goto usage
)
if "%1"=="-help" (
	goto usage
) 
:parseArg
set /a MEM="%1"
if "%1"=="0" (
	REM if zero same case as leth than 512
	set /a MEM=MINMEM
	goto cmd
) else (
	if "%MEM%"=="0" (
		echo 		Wrong usage : %1 is not a number
		goto usage
	) else (
		goto parseNumber
	)
)
goto out

REM Case for less than %MINMEM%
:parseNumber
if %MEM% GEQ %MINMEM% (
	echo Cassis starts with %MEM% MB of memory
	goto cmd
)
echo Cassis can't start with less than %MINMEM% MB of memory, force value to %MINMEM%
set /a MEM=%MINMEM%
goto cmd

REM We execute the command with %MEM% value
:cmd
REM Test Java version
PATH %PATH%;%JAVA_HOME%\bin\

set currentDir=%CD%
cd /d %0\..

set JAVA_MAJOR=
for /f "tokens=3 delims=. " %%a in ('java -version 2^>^&1 ^| findstr /i "version"') do (
    set JAVA_MAJOR=%%a
    goto :done
)

:done

set JAVA_MAJOR=!JAVA_MAJOR:"=!

set JAVA_OPTS=
if !JAVA_MAJOR! GEQ 17 (
    set JAVA_OPTS=--add-opens java.base/java.lang=ALL-UNNAMED
)

java !JAVA_OPTS! -Xss1024k -Xms512m -Xmx%MEM%m -jar .\bin\cassis.cassisAlone.jar


cd %currentDir%
goto out

REM print the help
:usage
	echo Usage : cassis.run [MEMORY]
        echo 	Allow to run cassis with the specified memory in MBytes
	echo 	If no argument is given, the default value is %DEFAULTMEM% MBytes
	echo 	Minimum value is %MINMEM%
	echo Arguments :
	echo 	-h or -help, print this help
	echo Examples :
	echo 	cassis.run : Run with default value %DEFAULTMEM% MB
	echo 	cassis.run 2048 : Run with value 2048MB

:out
