# Define the registry path where R versions are typically installed
$rRegistryPath = "C:\Programme\R\"
# Get all subkeys (versions) under the R registry path
$rVersions = Get-ChildItem -Path $rRegistryPath | Where-Object { $_.PSChildName -like "R-*" }

if ($rVersions.Count -gt 0) {
	# sort for the latest version
	$latestVersion = $rVersions | Sort-Object PSChildName -Descending | Select-Object -First 1
	$latestVersionPath = Join-Path -Path $rRegistryPath -ChildPath $latestVersion.PSChildName
	
	#combine the relative and the absolute path
	$rScriptPath = Join-Path -Path $latestVersionPath -ChildPath "bin\Rscript.exe"
    
    Write-Host "Hello User:"
    Write-Host "You are using the following Version of R:: $($latestVersion.PSChildName)"
    Write-Host "###################################################"
    Write-Host "After new installation of R and if you see the following output:"
    Write-Host "Fehler in ... Ausfuehrung angehalten"
    Write-Host "You have to open the Script over R-Studio and install the packages over it."
    Write-Host "###########################################################################"
    Write-Host ""

    # Use Start-Process to execute the R script using Rscript.exe
	# Start-Process -FilePath $rScriptPath -ArgumentList $rScriptFileWithCompletePath
	#-> this command didnt work 

	# Specify the argument to pass to the R script
	$argument = "TRUE"

	# Use & operator to execute the R script using Rscript.exe with the file path and argument
	#Specify the path to the R script file

	#Full path:
	#$rScriptFileWithCompletePath = "P:/IMEBI/DigiHero_Teilnehmerdaten/Massenmails/_neu_TOKENAUFBEREITER_Umfrageteilnehmertabellen/main.R"
	#& $rScriptPath $rScriptFileWithCompletePath $argument

	#path with the file in the current working directory
	$rScriptFile ="main.R"
	& $rScriptPath $rScriptFile $argument






} else {
    Write-Host "No R version found in:: C:\Programme\R\"
}