REM @echo off
setlocal ENABLEDELAYEDEXPANSION

SET MINIMUM_R_VERSION=100

set PP=
FOR /f "tokens=2*" %%a IN ('REG query HKLM\SOFTWARE\R-core\R /v InstallPath ^| findstr InstallPath') do (
set PP=%%b
)

IF [!PP!] == [] (
  pushd ..\..
  set R_HOME=!CD!\bin\R-local\R-3.3.1
  popd
  set MAJOR=0
) ELSE (
  set R_HOME=!PP!
  SET PRE_STUB=!R_HOME!
:CLIP
  SET R_HOME_STUB=!PRE_STUB:*\=!
  IF NOT !PRE_STUB!==!R_HOME_STUB! (
    SET PRE_STUB=!R_HOME_STUB!
    GOTO CLIP
  )
  SET MAJOR=!R_HOME_STUB:~2,1!
)


echo R_HOME = !R_HOME!
echo PATH = !PATH!




IF DEFINED EASYNET_HOME (
  echo EASYNET_HOME is !EASYNET_HOME!
) ELSE (
  pushd ..\..
  set EASYNET_HOME=!CD!
  popd
  echo EASYNET_HOME is !EASYNET_HOME!
)

IF DEFINED EASYNET_DATA_HOME (
  echo EASYNET_DATA_HOME is !EASYNET_DATA_HOME!
) ELSE (
  set EASYNET_DATA_HOME=!EASYNET_HOME!
  echo EASYNET_DATA_HOME is !EASYNET_DATA_HOME!
)


IF NOT DEFINED EASYNET_USER_HOME (
  IF NOT [!USERPROFILE!] == [] (
    If NOT EXIST "!USERPROFILE!\easyNet_Files\" (
      md "!USERPROFILE!\easyNet_Files\"
    )
    set EASYNET_USER_HOME="!USERPROFILE!\easyNet_Files\"
  )
)

IF NOT EXIST "!EASYNET_USER_HOME!\" (
  md "!EASYNET_USER_HOME!\"
)
IF NOT EXIST "!EASYNET_USER_HOME!\Outputs\" (
  md "!EASYNET_USER_HOME!\Outputs"
)

IF NOT EXIST "!EASYNET_USER_HOME!\Models\" (
  md "!EASYNET_USER_HOME!\Models"
)

echo EASYNET_USER_HOME is !EASYNET_USER_HOME!

pushd !EASYNET_HOME!
set EASYNET_RLIB=!CD!\bin\R-library
set EASYNET_LIB=!CD!\bin-win64\nm_files
popd

IF !MAJOR! GEQ !MINIMUM_R_VERSION! (

  set NEED_LINSTALL=false

  IF NOT EXIST !R_HOME!\library\Rcpp\ (
echo Installation...
    IF NOT EXIST !EASYNET_RLIB!\Rcpp (
      set NEED_LINSTALL=true
    )
  )
REM  IF NOT EXIST !R_HOME!\library\RInside (
REM   IF NOT EXIST !EASYNET_RLIB!\RInside (
REM      set NEED_LINSTALL=true
REM    )
REM  )

  IF !NEED_LINSTALL!==true (
    R CMD BATCH !EASYNET_RLIB!\install_packages.R
  )
  
  set R_LIBS=!EASYNET_RLIB!;!R_HOME!\library
echo R_LIBS = !R_LIBS!
REM pause  
) ELSE (
  pushd ..\..
  set R_HOME=!CD!\bin\R-local\R-3.3.1
  set R_LIBS=!CD!\bin\R-local\R-3.3.1\library
  popd
  set R_LIBS=!EASYNET_RLIB!;!R_LIBS!
)
set PATH=!R_HOME!\bin\x64;!PATH!
easyNet_simulator.exe
