%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% .m script of web demo "Insert title here" 
% Written for GNU Octave
% 
% INSTITUTE OF TELECOMMUNICATIONS  
% University of Stuttgart 
% www.inue-uni-stuttgart.de 
% author: Your Name   
% date: DD.MM.YYYY   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% This example script just prints the values of the given parameters.
% Make sure that the function prototype matches the prototype defined
% in the XML config file. (Parameter names are arbitrary but should be the same
% for better readability)

function [] = Capacity_G9701_fun(Bandwidth, delta_f, idx, Length, reflection_r1, reflection_r2, X, TX_Power_all_db, filename)


% define formats
landscape = "-S930,350";
portrait  = "-S640,480";

% select format
output_format = portrait;

% Create an invisible figure.
fh = figure(1);
set(fh, "visible", "off");

% define style
set(0, "defaultlinelinewidth", 5);
set(0, "defaultaxesfontsize", 16);
set(0, "defaultaxesfontname", "Helvetica");
set(0, "defaulttextfontsize", 16);
set(0, "defaulttextfontname", "Helvetica");


%% Parameter
%delta_f = 4.3125e3;
%Bandwidth = 17.664e6;
Annex_Freq_Offset = 138e3;
KilometerPerMiles = 1.609344;
%TX_Power_all_db = 14.5;%dBm
TX_Power = 10*log10(((10^(TX_Power_all_db/10))/Bandwidth)*delta_f);
%TX_Power=1; % in dBm/deltaf ~ -36dBm/Hz
ThermalNoisePerCarrier = -174+10*log10(delta_f); %in dB
%distance = 3.7; %in km
MaxSNR_dB = 45.15; % in dB

%% Calculate frequencies
freq = Annex_Freq_Offset:delta_f:(Annex_Freq_Offset+Bandwidth);

%% get cable parameters
F = freq;
[Zs,Yp,Name] = get_cable_parameterG9071(F,idx);
%Zs = Zs*1000;
%Yp = Yp*1000;

%% Telegraphen equation
gamma = sqrt(Zs.*Yp);
alpha = real(gamma);

ZL = sqrt(Zs./Yp);

Z1 = ZL*(1+reflection_r1)/(1-reflection_r1);
Z2 = ZL*(1+reflection_r2)/(1-reflection_r2);


F_omega= (ZL./(Z1+ZL)).*(1./(1-reflection_r1.*reflection_r2.*exp(-2.*gamma.*Length))).*(exp(-1.*gamma.*X)+reflection_r2.*exp(-1.*gamma.*(2.*Length-X)));


Amplitude = abs(F_omega);
H_dB = 20*log10(Amplitude);
SNR_dB = TX_Power+H_dB-ThermalNoisePerCarrier;
SNR_dB_clipped=SNR_dB;
SNR_dB_clipped(SNR_dB_clipped>MaxSNR_dB)=MaxSNR_dB;
SNR_dB_clipped_lin = 10.^((SNR_dB_clipped)/10);
Capacity = log2(1+SNR_dB_clipped_lin);
Capacity_Mbitps = sum(Capacity*delta_f)/1e6;
%% plot
 %SNR
% plot(F/1e6,H_dB);
% xlabel('F in MHz')
% ylabel('|H|^2 in dB')
% 
% %Capacity
 ax= plotyy(F/1e6,SNR_dB,F/1e6,Capacity);
 ylabel(ax(1),'SNR [dB]');
 ylabel(ax(2),'bit/symbol/tone');
 title(sprintf('Cable: %s Capacity: %.0f Mbit/s',Name,Capacity_Mbitps));
 set(ax(2),'xtick',[])
 xlabel('f [MHz]')
 set(ax(1),'Xgrid','on')
 set(ax(1),'Ygrid','on')
 set(ax(2),'Ygrid','on')
 %text(mean(F/1e6),max(Capacity)-0.5, sprintf('%.0f MBit/s',Capacity_Mbitps));






% Create an image file. This png image is displayed on the webpage. Its size 
% must be 640x480.
print(filename, "-dpng", output_format);


end
