import_sparam; % run script to import and parse s-parameters from file.
close all % Close all previous figures.

%%%%%%%%%%%%%%% Anonymous Functions %%%%%%%%%%%%%%%%%%

% Return Loss 
RL = @(x) (-20.*log10(abs(x(freq_range,1))));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Combine real and imag. parts in standard (rectangular) complex form.
S11_rec = reS11 + j*imS11;
S21_rec = reS21 + j*imS21;
S12_rec = reS12 + j*imS12;
S22_rec = reS22 + j*imS22;

%% Convert to polar form, in order to plot magnitude.
S11_pol = to_pd(S11_rec);
S21_pol = to_pd(S21_rec);
S12_pol = to_pd(S12_rec);
S22_pol = to_pd(S22_rec);

%% Plot s-parameters vs. freq

% Limit freq. range

% To change frequency range, simply select the corresponding subset of
% freq.

% freq contains 501 sample points, spanning [1-6]GHz.
% Therefore freq(1) == 1.0e+9 and freq(501) == 6.0e+9

freq_range = 1:size(freq); % full range
% freq_range = 1:201 % [1-3]GHz
% freq_range = 51:151 % [1.5-2.5]GHz

%% Inidividual subplots %%
ax1 = subplot(2,2,1);
plot(freq(freq_range), mag2db(S11_pol(freq_range,1)),'DisplayName','S11' )
ylim([-8 8])
ylabel(ax1,'S11 [dB]')
xlabel(ax1,'Freq')
grid on

ax2 = subplot(2,2,2);
plot(freq(freq_range), mag2db(S12_pol(freq_range,1)),'DisplayName','S12' )
ylim([-90 10])
ylabel(ax2,'S12 [dB]')
xlabel(ax2,'Freq')
grid on

ax3 = subplot(2,2,3);
plot(freq(freq_range), mag2db(S21_pol(freq_range,1)),'DisplayName','S21' )
ylim([-56 44])
ylabel(ax3,'S21 [dB]')
xlabel(ax3,'Freq')
grid on

ax4 = subplot(2,2,4);
plot(freq(freq_range), mag2db(S22_pol(freq_range,1)),'DisplayName','S22' )
ylim([-45 5])
ylabel(ax4,'S22 [dB]')
xlabel(ax4,'Freq')
grid on

% %% Collated Plot %%
% figure
% hold on
% plot(freq(freq_range), mag2db(S11_pol(freq_range,1)),'DisplayName','S11' )
% plot(freq(freq_range), mag2db(S12_pol(freq_range,1)),'DisplayName','S12' )
% plot(freq(freq_range), mag2db(S21_pol(freq_range,1)),'DisplayName','S21' )
% plot(freq(freq_range), mag2db(S22_pol(freq_range,1)),'DisplayName','S22' )
% grid on
% ylabel('Mag [dB]')
% xlabel('Freq [Hz]')
% legend('show')
% hold off

%% Return Loss Plots %%
figure
hold on
plot(freq(freq_range), mag2db(S11_pol(freq_range,1)),'DisplayName','S11' )
plot(freq(freq_range), RL(S11_pol), 'DisplayName','Return Loss (S11)' )
grid on
ylabel('Mag [dB]')
xlabel('Freq [Hz]')
legend('show')
hold off

%% Smithchart s-parameters %%
% Takes arguments (s-parameters) in rectangular complex form ie. 1+j*2.
figure
smithchart(S11_rec(freq_range))
hold on
smithchart(S22_rec(freq_range))
legend('S11','S22')
hold off