Saturday, April 12, 2025

Build labels resolving script for MSX Basic with chatGpt

<#
.SYNOPSIS
    Processes a text file by adding line numbers and replacing label-based GOTO/GOSUB commands.

.DESCRIPTION
    - Each line is numbered sequentially starting from a given Start, with an increment of Step.
    - Labels (lines starting with ':') are replaced with a numbered line containing "REM :label".
    - GOSUB and GOTO commands referencing a label (e.g., "gosub myLabel") are replaced with the numeric line.
    - Case-insensitive matching for labels and commands.

.PARAMETER FilePath
    Path to the file to process.

.PARAMETER Start
    Starting number for line numbering (default: 10).

.PARAMETER Step
    Increment step for line numbering (default: 10).

.EXAMPLE
    .RenumberWithLabels.ps1 -FilePath "C:codescript.bas" -Start 10 -Step 10
#>

param(
    [string]$FilePath,
    [int]$Start = 10,
    [int]$Step = 10
)

if (-not (Test-Path $FilePath)) {
    Write-Error "File not found: $FilePath"
    exit 1
}

$lines = Get-Content $FilePath
$output = @()
$labelMap = @{}
$lineNumber = $Start

# First pass: assign line numbers and store label mappings
foreach ($line in $lines) {
    $trimmed = $line.Trim()
    if ($trimmed -match '^:([a-zA-Z_][w]*)$') {
        $label = $matches[1]
        $labelMap[$label.ToLower()] = $lineNumber
        $output += "$lineNumber REM :$label"
    }
    else {
        $output += "$lineNumber $line"
    }
    $lineNumber += $Step
}

# Second pass: replace GOSUB/GOTO label references
for ($i = 0; $i -lt $output.Count; $i++) {
    $line = $output[$i]
    foreach ($label in $labelMap.Keys) {
        $line = $line -replace "(?i)bgosubs+:?$labelb", "gosub $($labelMap[$label])"
        $line = $line -replace "(?i)bgotos+:?$labelb", "GOTO $($labelMap[$label])"
    }
    $output[$i] = $line
}

# Save to file or print
$output | Set-Content "$FilePath.processed"
Write-Host "Processed file saved as: $FilePath.processed"