clc; clear all; close all;

%% Figure light theme

set(0, "defaultAxesColorOrder", [
        1.0000 0.0000 0.0000;  # red
        0.0000 0.0000 1.0000;  # blue
        1.0000 0.4980 0.0549;  # orange
        0.1725 0.6275 0.1725;  # green
        0.5804 0.4039 0.7412;  # purple
        0.5490 0.3373 0.2941;  # brown
        0.8902 0.4667 0.7608;  # pink
        0.4980 0.4980 0.4980;  # gray
]);

set(0, "DefaultFigureColor", [1 1 1]);
set(0, "DefaultAxesColor", [1 1 1]);
set(0, "DefaultAxesXColor", [0 0 0]);
set(0, "DefaultAxesYColor", [0 0 0]);
set(0, "DefaultTextColor", [0 0 0]);

set(0, "DefaultAxesGridColor", [0 0 0]);
set(0, 'DefaultAxesGridAlpha', 1.00);

set(0, "DefaultAxesMinorGridColor", [0 0 0]);
set(0, 'DefaultAxesMinorGridAlpha', 0.20);

set(0, "DefaultLineLinewidth", 3.00);
set(0, "DefaultAxesFontSize", 16);
set(0, "DefaultTextFontSize", 16);
set(0, "DefaultAxesLineWidth", 1.00);

set(0, "DefaultAxesXGrid", "on");
set(0, "DefaultAxesYGrid", "on");
set(0, "DefaultAxesZGrid", "on");
set(0, "DefaultAxesXMinorGrid", "on");
set(0, "DefaultAxesYMinorGrid", "on");
set(0, "DefaultAxesXMinorTick", "on");
set(0, "DefaultAxesYMinorTick", "on");

set(0, 'DefaultAxesGridAlpha', 0.50);

set(0, "defaultAxesFontName", "Nimbus Sans");

% exported ltspice data
filename = "passive_highpass_normalized_utf8.txt";

fid = fopen(filename, "r");

% Skip header
fgetl(fid);

% Read frequency and complex string
data = textscan(fid, "%f %s", "Delimiter", "\t");

fclose(fid);

freq = data{1};
response = data{2};

N = numel(freq);

mag = zeros(N,1);
phase = zeros(N,1);

for k = 1:N
    tokens = regexp(response{k}, ...
        '\(([-+0-9.eE]+)dB,([-+0-9.eE]+)°\)', ...
        'tokens');

    mag(k)   = str2double(tokens{1}{1});
    phase(k) = str2double(tokens{1}{2});
end

figure(1);
grid on;
set(gcf, "paperunits", "inches");
set(gcf, "papersize", [10 5]);
set(gcf, "paperposition", [0 0 10 5]);

% theorical transfer function

H1=tf([1 250], [1 500])
bode(H1);
[mag_the, pha_the, freq] = bode(H1, freq);
max(freq)

% bode functions returns linear scale y-axis
mag_the = squeeze(mag_the);
pha_the = squeeze(pha_the);
mag_the = 20*log10(mag_the);

% theorical normalized transfer function

H1_norm = tf([1 252.52], [1 505.05])
[mag_the_norm, pha_the_norm, freq] = bode(H1_norm, freq);

% bode functions returns linear scale y-axis
mag_the_norm = squeeze(mag_the_norm);
pha_the_norm = squeeze(pha_the_norm);
mag_the_norm = 20*log10(mag_the_norm);

%% Magnitude
ax1 = subplot(2, 1, 1)
y1 = semilogx(freq*2*pi, mag, "LineWidth", 3.5);
grid on;
hold on;
y2 = semilogx(freq, mag_the, "LineWidth", 2.75);
y3 = semilogx(freq, mag_the_norm, "LineWidth", 2);

ylim([-6.5 0.5])
yticks([-6 -3 0]);
xlim([1 1e5])
% xlabel("Frequency [Hz]");
ylabel("MAGNITUD [dB]");
% title("Bode Magnitude");
% legend("Normalizado", "Teórica", "Location", "southeast");

% Remove x tick labels from upper plot
set(ax1, "XTickLabel", []);

%% Phase
ax2 = subplot(2, 1, 2)
semilogx(freq*2*pi, phase, "LineWidth", 3.5);
grid on;
hold on;
semilogx(freq, pha_the, "LineWidth", 2.75);
semilogx(freq, pha_the_norm, "LineWidth", 2);

xlim([1 1e5])
xlabel('FRECUENCIA  [rad/s]');
ylabel("FASE  [grados]");
% title("Bode Phase");
% legend("Normalizado", "Teórica", "Location", "northeast");

% Create legend on top axes
% lgd = legend(ax1, [y1 y2], ...
%              "Respuesta en frecuencia circuito", ...
%              'Transferencia H_{1}(j\omega)')

% Invisible axes covering the whole figure
axL = axes("Position", [0 0 1 1], ...
           "Visible", "off", ...
           "Units", "normalized");

lgd = legend(axL, [y1 y2 y3], ...
             {"Pasa altos de primer orden",...
                 "H_{1}", ...
                 "H_{1} normalizada"});

% Move legend between plots
set(lgd, "position", [0.555 0.54 -0.50 -0.50]);
set(lgd, "numcolumns", 1);

% Reduce vertical spacing
set(ax1, "Position", [0.13 0.58 0.80 0.38]);
set(ax2, "Position", [0.13 0.13 0.80 0.38]);

print("bode_passive_highpass.png", "-dpng", "-r500");

