tg = slrt;

%%
f = SimulinkRealTime.openFTP(tg);
mget(f, 'apa95ml.dat', 'data');
close(f);

%% Convert the Data
data = SimulinkRealTime.utils.getFileScopeData('data/apa95ml.dat').data;

V_in = data(:, 1);
V_out = data(:, 2);
t = data(:, 3);

%% Save Data
save('mat/cedrat_la75b_med_3_stack.mat', 't', 'V_in', 'V_out');

%%
run setup;

win = hann(ceil(10/Ts));

[tf_est, f] = tfestimate(V_in, V_out, win, [], [], 1/Ts);
[co_est, ~] = mscohere(V_in, V_out, win, [], [], 1/Ts);

%%
figure;

hold on;
plot(f, co_est, 'k-')
set(gca, 'Xscale', 'log'); set(gca, 'Yscale', 'lin');
ylabel('Coherence'); xlabel('Frequency [Hz]');
hold off;

%%
figure;
ax1 = subplot(2, 1, 1);
hold on;
plot(f, abs(tf_est), 'k-', 'DisplayName', 'Identified')
set(gca, 'Xscale', 'log'); set(gca, 'Yscale', 'log');
ylabel('Amplitude'); xlabel('Frequency [Hz]');
hold off;

ax2 = subplot(2, 1, 2);
hold on;
plot(f, 180/pi*unwrap(angle(tf_est)), 'k-')
set(gca, 'Xscale', 'log'); set(gca, 'Yscale', 'lin');
ylabel('Phase'); xlabel('Frequency [Hz]');
hold off;

linkaxes([ax1,ax2], 'x');
xlim([10, 5000]);

%%
run setup;

win = hann(ceil(1/Ts));

[tf_est, f] = tfestimate(u, um, win, [], [], 1/Ts);
[co_est, ~] = mscohere(u, um, win, [], [], 1/Ts);
