function ConnPCA_Plot_Pct_Top_Links (LR, Fac, nbelecs, chanlocs, pct2display, cmap)
%
% ConnPCA_Plot_Pct_Top_Links - Create functional connectivity plot using
%                              CSDfcPCA factor loadings as described in
%                              Supplement A of Smith EE, Bel-Bahar T, Kayser J 2022
%             
%   Input:   LR   rotated loadings matrix (variables-by-factors)
%           Fac   factor range (e.g., [1:3 5] for factors 1, 2, 3 and 5)
%       nbelecs   number of electrode sites
%      chanlocs   EEGlab channel locations structure
%   pct2display   cut-off point [%] to display factor loadings
%          cmap   color map matrix
%
% (c) Ezra E. Smith 2021
% Copyright (C) 2021 by Ezra E. Smith (Email: ezraesmith@gmail.com)
% GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
% Updated: $Date: 2021/04/21 19:05:00 $ $Author: ees $
%   - adapted from funtions developed by Johann (2022). Easy Plot EEG Brain
%     Network Matlab (ersion 1.0.0.0). MATLAB Central File Exchange.
%     https://www.mathworks.com/matlabcentral/fileexchange/57372-easy-plot-eeg-brain-network-matlab
% 
% Updated: $Date: 2022/02/02 11:39:00 $ $Author: jk $
%   - added: structured comments and documentation

% identify suprathreshold connections for a single factor
[B, I] = sort(LR,1,'descend');
topidx = 1:round([ (pct2display / 100) * size(LR,1)  ]);

node_degree = NaN(size(LR,2), nbelecs);
for ii = 1:size(LR,2)
    top_loads = I(topidx,ii);
    nLR = nan(size(LR,1),1);
    nLR(top_loads,1) = LR(top_loads,ii);
    % BINARIZE
    binarizedLR = nLR(:,1);
    binarizedLR(~isnan(binarizedLR)) = 1;
    adjmat = nan(nbelecs,nbelecs);
    c = 1;
    for ie = 1:nbelecs;
        for je = ie+1:nbelecs
            adjmat(ie,je) = binarizedLR(c,1);
            c = c+1;
        end
    end
    node_degree(ii,:) = nansum(adjmat);
end

% connectivity strength / reorient loadings into adjacency matrix
eLR = nan(size(LR,1),1);
top_loads = I(topidx,Fac);
eLR(top_loads,1) = LR(top_loads,Fac);
edgemat = nan(nbelecs,nbelecs);
c = 1;
for ie = 1:nbelecs
    for je = ie+1:nbelecs
        edgemat(ie,je) = eLR(c,1); % has already been thresholded above
        c = c+1;
    end
end

% only plot if the matrix is not entirely filled with zeros and nans
if (sum(isnan(edgemat(:))) + sum(edgemat(:)==0))  ~= numel(edgemat)
    % assign
    edges_to_plot = edgemat;

    % reorient adjmat to columns
    ijw = adj2edgeL(triu(edges_to_plot));

    [~, ii] = sort(ijw(:,3));
    ijw = ijw(ii,:);
    w_atribut = ijw(:, 3);
    linealpha = nan(size(w_atribut));
    linewid = nan(size(w_atribut));

    % convert loadings to ranks
    temp = abs(w_atribut);
    ranks = tiedrank(temp);

    % discretize line transparency
    Xbins = ceil(5 * ranks / length(ranks));

    % Xbins = discretize(X,3);
    linealpha(Xbins == 5) = 0;
    linealpha(Xbins == 4) = .2;
    linealpha(Xbins == 3) = .4;
    linealpha(Xbins == 2) = .6;
    linealpha(Xbins == 1) = .8;
    
    % convert ranks to rgb
    linecol = squeeze(double2rgb(ranks, colormap(cmap), [min(ranks) max(ranks)]));
    
    % line width
    linewid(Xbins >= 0) = 1.5;
    
    % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
    % % % % % % % % % % % % % %  STARTING TO DISPLAY THE FIGURE  % % % % % % % % % %
    axis square;                                    % making it square
    axis off;                                       % avoiding the axis
    hold on;
    
    % use eeglab to provide correct coords
    [~,x,y] = topoplot_MG([],chanlocs,'electrodes','off');
    
    % swap x and y
    xy = [y' x'];
    hold on

    % plotting links and nodes
    for lk = 1 : size(ijw, 1)           % along all links
        xynodes = zeros(2, 2);          % choose the position XY of nodes of one link
        for nd = 1:2                             % for the two nodes of a link
            xynodes(nd, :) = xy(ijw(lk,nd), :);  % hold the positions
        end
        if ~isnan(linealpha(lk,1))
            if w_atribut(lk)>0
                line(xynodes(:, 1), xynodes(:, 2),1-repmat(linealpha(lk,1),[2 1]),...
                    'LineWidth', abs(linewid(lk)), 'Color', linecol(lk,:));
            elseif w_atribut(lk)<0
                line(xynodes(:, 1), xynodes(:, 2),1-repmat(linealpha(lk,1),[2 1]),...
                    'LineWidth', abs(linewid(lk)),'LineStyle',':', 'Color', linecol(lk,:));
            end
        end
    end
    set(gca,'XTick',[],'YTick',[]); % avoiding the tick labels of axis
    set(gcf,'color','w','renderer','painter');
    % set(gcf,'renderer','painter');
    axis vis3d;                     % setting axis limits to the range of data
    % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
    %
else
    topoplot_MG([],chanlocs,'electrodes','off', 'whitebk','on');
end

end
