%% Clear Workspace and Close figures
clear; close all; clc;

%% Intialize Laplace variable
s = zpk('s');

addpath('./src/');

% Test with one APA

%% Load measurement data for APA number 1
load(sprintf('mat/frf_data_%i_sweep_lf.mat', 2), 't', 'Va', 'Vs', 'de', 'da');

% Compute transfer functions:

Ts = (t(end) - t(1))/(length(t)-1);
Fs = 1/Ts;

win = hanning(ceil(1*Fs)); % Hannning Windows

[G_dvf, f] = tfestimate(Va, de, win, [], [], 1/Ts);
[G_d,   ~] = tfestimate(Va, da, win, [], [], 1/Ts);
[G_iff, ~] = tfestimate(Va, Vs, win, [], [], 1/Ts);

[coh_dvf, ~] = mscohere(Va, de, win, [], [], 1/Ts);
[coh_d,   ~] = mscohere(Va, da, win, [], [], 1/Ts);
[coh_iff, ~] = mscohere(Va, Vs, win, [], [], 1/Ts);

%%
figure;
hold on;
plot(f, coh_dvf);
plot(f, coh_d);
plot(f, coh_iff);
hold off;
set(gca, 'XScale', 'log');

%%
figure;
tiledlayout(2, 1, 'TileSpacing', 'None', 'Padding', 'None');

ax1 = nexttile;
hold on;
plot(f, abs(G_dvf));
plot(f, abs(G_d));
hold off;
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'log');
ylabel('Amplitude $V_{out}/V_{in}$ [V/V]'); set(gca, 'XTickLabel',[]);
hold off;

ax2 = nexttile;
hold on;
plot(f, 180/pi*angle(G_dvf));
plot(f, 180/pi*angle(G_d));
hold off;
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'lin');
xlabel('Frequency [Hz]'); ylabel('Phase [deg]');
hold off;
yticks(-360:90:360);

linkaxes([ax1,ax2],'x');
xlim([5, 5e3]);

figure;
tiledlayout(2, 1, 'TileSpacing', 'None', 'Padding', 'None');

ax1 = nexttile;
plot(f, abs(G_iff));
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'log');
ylabel('Amplitude $V_{out}/V_{in}$ [V/V]'); set(gca, 'XTickLabel',[]);
hold off;

ax2 = nexttile;
plot(f, 180/pi*angle(G_iff));
set(gca, 'XScale', 'log'); set(gca, 'YScale', 'lin');
xlabel('Frequency [Hz]'); ylabel('Phase [deg]');
hold off;
yticks(-360:90:360);

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

% Comparison of all APA

%% Load all the measurements
meas_data = {};
for i = 1:7
    meas_data(i) = {load(sprintf('mat/frf_data_%i.mat', i), 't', 'Va', 'Vs', 'de', 'da')};
end
