@echo OFF
goto :main

:readInfo
	set sdkInfoPath=%em_path%\..\..\..\sdk.info
	set JDK_PATH=%em_path%\..\..\..\jdk

	rem extracting the paths from sdk.info
	for /F "delims=" %%a in (!sdkInfoPath!) do (
		set paths=%%a
		for /f "tokens=1,2 delims==" %%b in ("!paths!") do (
	 		if %%b==TIZEN_SDK_DATA_PATH (
				set sdkDataPath=%%c
	 		)
	 		if %%b==JDK_PATH (
				set sdkInfoJDKPath=%%c
	 		)
	 		if %%b==TIZEN_SDK_INSTALLED_PATH (
				set sdkPath=%%c
	 		)
		)		
	)
	goto :eof

:createLogFile
	set hour=%time:~0,2%
	if "%hour:~0,1%" == " " set hour=0%hour:~1,1%

	set min=%time:~3,2%
	if "%min:~0,1%" == " " set min=0%min:~1,1%

	set secs=%time:~6,2%
	if "%secs:~0,1%" == " " set secs=0%secs:~1,1%

	set year=%date:~-4%

	set month=%date:~3,2%
	if "%month:~0,1%" == " " set month=0%month:~1,1%

	set day=%date:~0,2%
	if "%day:~0,1%" == " " set day=0%day:~1,1%

	set fileName=emCli%year%%month%%day%%hour%%min%%secs%.txt
	set "logFilePath=%sdkDataPath%\emulator"
	if not exist %logFilePath% (
		mkdir -p "%logFilePath%\%fileName%"
	)
	set "logFile=%logFilePath%\%fileName%"
	set logFileCreated=true
	goto :eof

:updateLogFile
	if !logFileCreated!==false (
		call :createLogFile
	)
	call echo %1>>!logFile!
	goto :eof

:setExecPath
	rem set the java exec path to be used
	rem update javaExec if JDK_PATH specified and exists in sdk.info
	set "logFileCreated=false"
	if exist "%sdkInfoJDKPath%" (
		set JDK_PATH=%sdkInfoJDKPath%
		call :updateLogFile "Using Sdk.info java at !JDK_PATH!"
	) else (
		if not !sdkInfoJDKPath!==!emptyVar! (
			call :updateLogFile "Jdk specified in sdk.info:!sdkInfoJDKPath! does not exist."
		)
	)
	if not exist "!JDK_PATH!" (
		set javaExec=java
		call :updateLogFile "Using System java"
	) else (
		set javaExec=!JDK_PATH!\bin\java
	)

	goto :eof


:main
setlocal enabledelayedexpansion
set argC=0
for %%x in (%*) do Set /A argC+=1
IF "%argC%" == "0" (
   echo Error: Argument missing. use '-h' for help.
   goto end
)

set sdk_path=%~dp0

IF EXIST !sdk_path! (
	set em_path=!sdk_path!
) ELSE (
	set em_path=.
)

IF %em_path:~-1%==\ SET em_path=%em_path:~0,-1%

set current_path=%CD%\em-cli.jar
set current_path_dir=%CD%

for /F "usebackq tokens=1,2* delims=: " %%V in (`mode con`) do (
    if .%%V==.Columns (
        set COLUMNS=%%W
        goto done
    )
)

:done

call :readInfo
call :setExecPath

rem Added fallbacks from here

IF EXIST "%current_path%" (
	"%javaExec%" -jar "%current_path%" %*
) ELSE (
	"%javaExec%" -jar "%em_path%\em-cli.jar" %*
)

:end