function err = func6_objectiveFunction(JA_vec, model, t, I_exp, U_exp, debug)
    % Zielfunktion: normierter RMSE-Fehler zwischen Simulation und Messung
    % inkl. Phasenkorrektur per Kreuzkorrelation 

    if nargin < 6
        debug = false;
    end

    JA_params = JA_vec(1:5);
    Vexc = JA_vec(6);

    % === COMSOL-Simulation durchführen ===
    [I_sim, U_sim] = func7_simulateCOMSOL(model, JA_params, Vexc, t);

    % === Phasenkorrektur über Kreuzkorrelation (bezogen auf Imag) ===
    [acor, lag] = xcorr(U_sim - mean(U_sim), U_exp - mean(U_exp));
    [~, Umax] = max(abs(acor));
    lag_shift = lag(Umax);  % Zeitindex-Verschiebung
    
    % === Zyklische Verschiebung des Signals ===
    I_exp_corr = circshift(I_exp, lag_shift);
    % I_sim_recalculated_corr = circshift(I_sim_recalculated, lag_shift);
    U_exp_corr = circshift(U_exp, lag_shift);
    % U_sim_recalculated_corr = circshift(U_sim_recalculated, lag_shift);
    
    % === RMSE berechnen ===
    err_I = sqrt(mean((I_sim - I_exp_corr).^2)) / rms(I_exp_corr);
    err_U = sqrt(mean((U_sim - U_exp_corr).^2)) / rms(U_exp_corr);
    err = err_U+err_I;

    % === Optionaler Plot zur Kontrolle ===
    if 1
        figure('Name','Phasenkorrektur-Prüfung');
        subplot(2,1,1);
        plot(t, I_exp_corr, 'k', 'LineWidth', 1.5); hold on;
        plot(t, I_sim, 'r--', 'LineWidth', 1.5);
        legend('I_{exp}', 'I_{sim, korrigiert}');
        title(sprintf('Magnetisierungsstrom (RMSE = %.3g)', err_I));
        xlabel('t (s)'); ylabel('I (A)'); grid on;

        subplot(2,1,2);
        plot(t, U_exp_corr, 'k', 'LineWidth', 1.5); hold on;
        plot(t, U_sim, 'r--', 'LineWidth', 1.5);
        legend('U_{exp}', 'U_{sim, korrigiert}');
        title(sprintf('PUC-Spannung (RMSE = %.3g)', err_U));
        xlabel('t (s)'); ylabel('U (V)'); grid on;
    end
end
