tg = slrt;

%%
f = SimulinkRealTime.openFTP(tg);
mget(f, 'apa95ml.dat');
% remove file on RT-target
% removefile(f, 'C:\data\data_001.dat')
close(f);

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

%%
figure;
subplot(1,2,1);
plot(data(:, 3), data(:, 1))
subplot(1,2,2);
plot(data(:, 3), data(:, 2))

%%
run setup;

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

[tf_est, f] = tfestimate(data(:, 1), data(:, 2), win, [], [], 1/Ts);
[co_est, ~] = mscohere(data(:, 1), data(:, 2), 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]');
  legend();
  hold off;

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