#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np

try:
    # ngspice wrdata exportiert Spalten paarweise: [Zeit, Wert1, Zeit, Wert2]
    data = np.loadtxt("rectifier_data.txt")
    time = data[:, 0] * 1000  # Umrechnung in Millisekunden (ms)
    v_in = data[:, 1]
    v_out = data[:, 3]

    plt.figure(figsize=(10, 6))
    plt.plot(time, v_in, label="Eingangssignal v(/signal_in)", color="#1f77b4", linewidth=1.5)
    plt.plot(time, v_out, label="Gleichgerichteter Ausgang v(/rect_out)", color="#ff7f0e", linewidth=2.0)
    
    plt.title("Gleichrichter Simulation (ngspice Ergebnisse)", fontsize=14, fontweight='bold', pad=15)
    plt.xlabel("Zeit (ms)", fontsize=12)
    plt.ylabel("Spannung (V)", fontsize=12)
    plt.grid(True, linestyle="--", alpha=0.7)
    plt.legend(loc="upper right", frameon=True, facecolor="white", edgecolor="none")
    plt.xlim(0, 10)  # Entpricht der .tran 10m Vorgabe
    
    plt.tight_layout()
    plt.savefig("rectifier_simulation_results.png", dpi=300)
    print("Graph erfolgreich als 'rectifier_simulation_results.png' gespeichert.")

except FileNotFoundError:
    print("Fehler: 'rectifier_data.txt' wurde nicht gefunden. Bitte führe ngspice zuerst aus.")
