function tgaxCalibrationCDF(sinr,varargin)
%tgaxCalibrationCDF Plot calibration CDF with reference curves
%
%   This is an example helper function.

%   Copyright 2019 The MathWorks, Inc.

s = load('tgaxCalibrationCurves.mat');

if nargin>1
    test = varargin{1};
else
    test = 'SS1Box1Test2';
end

if nargin>2
    titletext = varargin{2};
else
    titletext = test;
end

figure;
hold on;
p1 = plot(s.(test),(1:100)/100,'-','Linewidth',1,'Color',0.7*ones(3,1));
[f,x] = ecdf(sinr(:)); 
p2 = plot(x,f,'-k','Linewidth',1);
hold off
title(['Calibration: ' titletext]);
xlabel('SINR [dB]'), ylabel('CDF')
box on
grid on,grid(gca,'minor')
legend([p1(1),p2(1)],'Calibrated Curves','WLAN Toolbox','Location','southeast');

end

function [F,x] = ecdf(y)
% Empirical (Kaplan-Meier) cumulative distribution function.

    x = y(:);
    
    % Remove any NaNs
    x(isnan(x)) = [];

    % Check arguments
    cens = zeros(size(x));
    freq = ones(size(x));

    % Sort observation data in ascending order.
    [x,t] = sort(x);
    cens = cens(t);

    % Compute cumulative sum of frequencies
    totcumfreq = cumsum(freq);
    obscumfreq = cumsum(freq .* ~cens);
    t = (diff(x) == 0);
    if any(t)
        x(t) = [];
        totcumfreq(t) = [];
        obscumfreq(t) = [];
    end
    totalcount = totcumfreq(end);

    % Get number of deaths and number at risk at each unique X
    D = [obscumfreq(1); diff(obscumfreq)];
    N = totalcount - [0; totcumfreq(1:end-1)];

    % No change in function except at a death, so remove other points
    t = (D>0);
    x = x(t);
    D = D(t);
    N = N(t);

    % Use the product-limit (Kaplan-Meier) estimate of the survivor
    % function, transform to the CDF.
    S = cumprod(1 - D./N);

    Func = 1 - S;
    F0 = 0;       % starting value of this function (at x=-Inf)

    % Include a starting value; required for accurate staircase plot
    x = [min(y); x];
    F = [F0; Func];
end