$ErrorActionPreference = "Stop"

if (Get-Process EXCEL -ErrorAction SilentlyContinue) {
    throw "Excel is running. Close Excel before uninstalling OctaveExcel."
}

function Get-OpenIndex {
    param([string]$Name)

    if ($Name -eq "OPEN") {
        return 0
    }

    if ($Name -match '^OPEN(\d+)$') {
        return [int]$Matches[1]
    }

    return [int]::MaxValue
}

$officeRoot = 'HKCU:\Software\Microsoft\Office'
$removed = 0

if (Test-Path $officeRoot) {
    $optionKeys = Get-ChildItem $officeRoot -ErrorAction SilentlyContinue |
        Where-Object { $_.PSChildName -match '^\d+\.\d+$' } |
        ForEach-Object { Join-Path $_.PSPath "Excel\Options" } |
        Where-Object { Test-Path $_ }

    foreach ($key in $optionKeys) {
        $properties = Get-ItemProperty $key

        $remaining = @(
            $properties.PSObject.Properties |
                Where-Object { $_.Name -match '^OPEN\d*$' } |
                Sort-Object { Get-OpenIndex $_.Name } |
                Where-Object { [string]$_.Value -notlike '*OctaveExcel*' } |
                ForEach-Object { [string]$_.Value }
        )

        $openNames = @(
            $properties.PSObject.Properties |
                Where-Object { $_.Name -match '^OPEN\d*$' } |
                ForEach-Object { $_.Name }
        )

        $removed += @(
            $properties.PSObject.Properties |
                Where-Object { $_.Name -match '^OPEN\d*$' -and [string]$_.Value -like '*OctaveExcel*' }
        ).Count

        foreach ($name in $openNames) {
            Remove-ItemProperty -Path $key -Name $name -ErrorAction SilentlyContinue
        }

        for ($i = 0; $i -lt $remaining.Count; $i++) {
            $name = if ($i -eq 0) { "OPEN" } else { "OPEN$i" }
            New-ItemProperty -Path $key -Name $name -PropertyType String -Value $remaining[$i] -Force | Out-Null
        }
    }
}

if ($removed -gt 0) {
    Write-Host "OctaveExcel startup registration removed." -ForegroundColor Green
} else {
    Write-Host "No OctaveExcel startup registration was found."
}
