function [activeTx,activeRx] = tgaxCCA(ss,ccaLevel)
%tgaxCCA Clear channel assessment (CCA) rule
%
%   This is an example helper function.
%
%   [ACTIVETX,ACTIVERX] = tgaxCCA(SS,CCALEVEL) returns logical vectors of
%   active transmitters and receivers according to the clear channel
%   assessment rules specified in the 11ax Evaluation Methodology, Figure
%   4. It selects 0 or 1 transmitters per BSS based on the instantaneous
%   interference level compared to a given threshold (CCALEVEL).
%   Correspondingly, one receiver is also selected per BSS.
%
%   SS is an [numTx, numRx] array of signal strengths between all
%   transmitters and receivers in dBm.
%
%   CCALEVEL is the channel access threshold in dBm.

%   Copyright 2019 The MathWorks, Inc.

ccaLevelmW = 10^(ccaLevel/10); % convert from dBm to mW
ssmW = 10.^(ss/10); % convert from dBm to mW

[numTx,numRx] = size(ssmW);
assert(mod(numRx,numTx)==0); % Expect at least one receiver per transmitter

% Activate Transmitters

activeTx = false(numTx,1);
ind = randperm(numTx)'; % create a vector of randomly permuted indices

while ~isempty(ind) % while set is not empty
    idx = ind(1); % pick index of interest
    if sum(ssmW(activeTx,idx)) < ccaLevelmW
        activeTx(idx) = true; % set index to be transmitter
    end
     
    ind(1) = []; % delete this index
end

% Activate Receivers

% If a transmitter is active - the randomly select a receiver in the same 
% room to be active. 

activeRx = false(numRx,1);
numRxPerRoom = numRx/numTx;
for txIdx = 1:numTx
    if activeTx(txIdx)
        rxIdx = txIdx + (0:numRxPerRoom-1)*numTx;
        if numel(rxIdx) == 1
            activeRx(rxIdx) = true;
        else
            activeRx(rxIdx(randi([1 numRxPerRoom]))) = true; % pick one of these to be active
        end
    end
end

end