function [obj,invalidmask] = update_invalid_edges_comp2comp(obj,varargin)
% invalid by struct, match or overlap
pp = inputParser;
pp.addParamValue('topn',inf); %keep top n compts for each label
pp.addParamValue('disable_label',GLOBALCONST.DISABLED_LABELS);
pp.addParamValue('useconn',true);
pp.addParamValue('useoverlap',true);
pp.parse(varargin{:});

if ~isempty(obj.m_idxcompts_supergraph)
    warning('be careful, updating invalid edges on a subgraph might enable egdes not found in the supergraph');
end

overlapcost_comp2comp = obj.m_overlapcost_comp2comp;
structscore_comp2comp = obj.m_structscore_comp2comp_raw;
if pp.Results.useoverlap
    thres_max_overlapcost = GLOBALCONST.THRES_MAX_OVERLAP_COST_ACCEPTABLE;
else
    thres_max_overlapcost = 1;
end
thres_min_structscore = GLOBALCONST.THRES_MIN_STRUCTURE_SCORE_ACCEPTABLE;

svals = tril(structscore_comp2comp);
svals = svals(svals~=0);
svals = sort(svals,'descend');
topn_struct = min(10000,length(svals));%at least take 10000 edges
thres_min_conflictscore = min(0.9,svals(topn_struct));
% thres_min_structscore = 0;

invalidmask = overlapcost_comp2comp > thres_max_overlapcost;
if pp.Results.useconn
    invalidmask = invalidmask | structscore_comp2comp < thres_min_conflictscore;
end
          
% if ~isempty(obj.m_conflictscore_comp2comp)
%     invalidmask = invalidmask | obj.m_conflictscore_comp2comp<thres_min_conflictscore;
% end

topn = pp.Results.topn;
complbs = obj.m_complabels;
compscores = obj.m_compscores;
ulbs = unique(complbs);
maskvalid = false(1,length(complbs));
for i=1:length(ulbs)
    thislb = ulbs(i);
    idxthis = find(complbs == thislb);
    scores = compscores(idxthis);
    [~,idxsort] = sort(scores,'descend');
    idxuse = idxsort(1:min(topn,end));
    idxuse = idxthis(idxuse);
    maskvalid(idxuse) = true;
end

% disable some label
dslbs = pp.Results.disable_label;
if ~isempty(dslbs)
    maskds = ismember(complbs,dslbs);
    maskvalid = maskvalid & ~maskds;
end

invalidmask(~maskvalid,:) = true;
invalidmask(:,~maskvalid) = true;

invalidmask = invalidmask | invalidmask' | eye(size(invalidmask))>0;
obj.m_adjmat_invalid_comp2comp = invalidmask;
obj.m_structscore_comp2comp(invalidmask) = 0;

end

