import subprocess
import re
from math import sqrt

frequencies = [28.0 + i * 0.05 for i in range(21)]  # 28.0 bis 29.0 MHz in 50kHz Schritten
z0 = 50.0  # Bezugsimpedanz

print(f"{'Freq (MHz)':<10} | {'R (Ohm)':<8} | {'X (Ohm)':<8} | {'SWR':<6}")
print("-" * 42)

for f in frequencies:
    # 1. FR-Zeile anpassen
    with open("delta_loop.nec", "r") as f_in:
        content = f_in.read()
    
    content_mod = re.sub(r"FR 0 1 0 0 \d+\.?\d* 0", f"FR 0 1 0 0 {f:.3f} 0", content)
    
    with open("temp.nec", "w") as f_out:
        f_out.write(content_mod)
        
    # 2. Simulation ausführen
    subprocess.run(["nec2c", "-i", "temp.nec", "-o", "temp.out"], stdout=subprocess.DEVNULL)
    
    # 3. temp.out auslesen
    r, x = None, None
    with open("temp.out", "r") as res:
        lines = res.readlines()
        for i, line in enumerate(lines):
            if "ANTENNA INPUT PARAMETERS" in line:
                # Suche in den folgenden 10 Zeilen nach der echten Datenzeile
                for target_line in lines[i+1:i+10]:
                    parts = target_line.strip().split()
                    # Die Datenzeile unter "IMPEDANCE (OHMS)" hat 10 Elemente:
                    # TAG, SEG, V_REAL, V_IMAG, I_REAL, I_IMAG, R, X, G, B
                    if len(parts) >= 8 and parts[0].isdigit():
                        try:
                            r = float(parts[6])  # Spalte 6: IMPEDANCE REAL
                            x = float(parts[7])  # Spalte 7: IMPEDANCE IMAG
                            break
                        except (ValueError, IndexError):
                            continue
                if r is not None:
                    break

    # 4. SWR berechnen und ausgeben
    if r is not None and x is not None:
        z_mag_sq = (r - z0)**2 + x**2
        z_sum_sq = (r + z0)**2 + x**2
        gamma = sqrt(z_mag_sq / z_sum_sq)
        
        swr = (1 + gamma) / (1 - gamma) if gamma < 0.99 else 99.9
        print(f"{f:<10.3f} | {r:<8.2f} | {x:<8.2f} | {swr:<6.2f}")
    else:
        print(f"{f:<10.3f} | Konnte Werte nicht lesen")
