:: This script finds out the path to the current installation of R from the registry.
:: It then finds out if the current machine is a 32-bit or 64-bit machine and uses this to define the path of Rscript.exe.
:: It then writes out the path of Rscript.exe to the file RscriptPath.txt

:: Turn off echo so that only error messages will be seen
@echo off

:: Step 1: query the registry to find the install path of R (most recently installed version)
reg query HKEY_LOCAL_MACHINE\Software\R-core\R /v InstallPath > temp1.txt
If not %ERRORLEVEL% == 0 (
    :: Problem checking registry; maybe R was not installed as administrator, try user key instead
    reg query HKEY_CURRENT_USER\Software\R-core\R /v InstallPath > temp1.txt
)
If not %ERRORLEVEL% == 0 goto keyerror
for /f "delims=" %%x in (temp1.txt) do set LastLine=%%x
set Rpath=%LastLine:    InstallPath    REG_SZ    =%

:: Step 2: query the registry to find whether the system is 32-bit or 64-bit
reg query HKLM\Hardware\Description\System\CentralProcessor\0 > temp2.txt
Find /i "x86" < temp2.txt
If %ERRORLEVEL% == 0 (
    :: 32-bit
    set OSbatch=i386
) ELSE (
    :: 64-bit
    set OSbatch=x64
)

:: Step 3: Construct the path to Rscript and write out to file
set RscriptPath=%Rpath%\bin\%OSbatch%\Rscript.exe
echo %RscriptPath% > RscriptPath.txt

:: Delete temporary files
del temp1.txt
del temp2.txt
goto done

:: Neither the global or local user R registry keys could be found
:keyerror
echo R installation not found. R must be installed in order to run the Model Evaluation Toolkit.
pause

:: Finish
:done