%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% .m script of web demo 'Multiuser Capacity' 
% Written for Matlab
% 
% INSTITUTE OF TELECOMMUNICATIONS  
% University of Stuttgart 
% www.inue-uni-stuttgart.de 
% author: Wei Wang, Jintong JU   
% date: 14.12.2020   
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% 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 [] = demo_1_function(p_1,p_2,sic,fdma,tdma,cdma,webdemo_en,filename)

% Create an invisible figure.
if (webdemo_en)
   fig = figure(1); set(fig, 'visible', 'off');
else
    fig = figure(1); set(fig, 'visible', 'on');
end

% set default Fontsize and name
set(gca, 'defaultlinelinewidth', 2);
set(gca, 'fontname','Helvetica');
set(gca, 'fontsize', 17);

p_1 = 10.^(p_1/10);
p_2 = 10.^(p_2/10); % dBm -> milliwatt
r_1 = log2(1+p_1);
r_2 = log2(1+p_2); % boundry
r_1_left = log2(1+p_1+p_2)-r_2;
r_2_down = log2(1+p_1+p_2)-r_1; 
R_1 = 0:r_1/1000:r_1;
R_2 = r_2.*(R_1<r_1_left)+(log2(1+p_1+p_2)-R_1).*(R_1>=r_1_left&R_1<r_1)+0.*(R_1>=r_1_left);

% Prepare plot
xlabel('R_1 in bits/s/Hz');
ylabel('R_2 in bits/s/Hz');
if (r_1 > r_2)
    axis([0,r_1*1.5,0,r_1*1.5]);
else
    axis([0,r_2*1.5,0,r_2*1.5]);
end
grid on;
box on;
hold on;
h1 = plot(R_1,R_2,'r','DisplayName','NOMA');

if (sic)
    R_1 = r_1_left:r_1/1000:r_1;
    R_2 = log2(1+p_1+p_2)-R_1;
    h6 = plot([r_1_left,r_1],[r_2,r_2_down],'k.','MarkerSize',30,'DisplayName','SIC');
    A=['A(R_1=',num2str(r_1_left),', R_2=',num2str(r_2),')'];
    B=['B(R_1=',num2str(r_1),', R_2=',num2str(r_2_down),')'];
    text(r_1_left*1.03,r_2*1.03,A,'FontSize',14);
    text(r_1,r_2_down*1.1,B,'FontSize',14);
end

if (fdma)
    p_1_plot=p_1*ones(1,201);
    p_2_plot=p_2*ones(1,201);
    alpha=0:0.005:1; % 201 points
    r_1 = alpha.*log2(1+p_1_plot./alpha);
    r_2 = (1-alpha).*log2(1+p_2_plot./(1-alpha));
    h7 = plot(r_1,r_2,'b','DisplayName','FDMA');
end
if (tdma)
    alpha=0:0.005:1;
    r_1 = alpha.*log2(1+p_1);
    r_2 = (1-alpha).*log2(1+p_2);
    h8 = plot(r_1,r_2,'m','DisplayName','TDMA');
end
if (cdma)
    r_1=0.5*log2(1+2*p_1);
    r_2=0.5*log2(1+2*p_2);
    h9 = plot(r_1,r_2,'g.','MarkerSize',30,'DisplayName','CDMA');
    text(r_1*1.05,r_2*1.05,'C','FontSize',15);
end

legend;

if (webdemo_en)
    print(filename,'-dpng','-r83'); % generate the picture results
end

end