function obj = update_seg2seg_conflict( obj,sketchdata,database )
% find out conflicting segments, that is, those that cover the same portion
% of a component

seglbs_per_line = sketchdata.seglinegroups;
nline = length(seglbs_per_line);
seglbs2line = false(max(obj.m_seglbs_per_sample),nline);
for i=1:length(seglbs_per_line)
    seglbs = seglbs_per_line{i};
    if ~isempty(seglbs)
        seglbs2line(seglbs,i) = true;
    end
end

ncomp = length(obj.m_complabels);
% seglist = srec_seglist_from_solution(1:ncomp,obj,database);
seglist = util_get_segment_by_segids(obj.m_segid_per_compts,database);
comp2sample = obj.m_adjmat_comp2sample_fullcover ...
    | obj.m_adjmat_comp2sample ...
    | obj.m_adjmat_comp2sample_justenough;
ptsketch = obj.m_samplepts;
dirsketch = obj.gdxy;
kpts = 20;
nseglbs = max(obj.m_seglbs_per_sample);
topncover = 1; %each point in sketch only covers topn points in segment
ndilatepts = 4;
coverlen_seg2comp = zeros(nseglbs,length(seglist));
coverdist_seg2comp = nan(nseglbs,length(seglist));
coverconflict_seg2seg2comp = false(nseglbs,nseglbs,length(seglist));
short_seglbs = srec_find_short_2dseg(obj.m_seglbs_per_sample,2);

thres_conflict_overlap_ratio = 0.7;
boxlens = util_make_aabb_from_pts(ptsketch);
disthres = norm(boxlens)*GLOBALCONST.THRES_COVERPTS_MAXDIST_TO_GLOBAL_DIAG;
for i=1:length(seglist)
    fprintf(1,'seg2seg conflict for component %d/%d\n',i,length(seglist));
    seg = seglist{i};
    ptseg = util_pts_from_bwimg(seg.m_sketchimg);
    dirseg = seg.gdxy;
    dftransmat = obj.m_dftransmat_per_compts{i};
    
    ptseg = util_transform_pts(ptseg,dftransmat);
    dirseg = util_transform_tangents(dirseg,dftransmat);
    
    %     boxlens = util_make_aabb_from_pts(ptseg);
    %     diaglen = norm(boxlens);
    %     disthres = diaglen * GLOBALCONST.THRES_COVERPTS_MAXDIST_TO_DIAG;
    
    % points on the sketch that are believed to cover this segment
    masksample = comp2sample(i,:);
    seglbs = obj.m_seglbs_per_sample(masksample);
    ptsample = ptsketch(:,masksample);
    dirsample = dirsketch(:,masksample);
    
    % match from sketch to segment
    [covermat_sketch2seg,scoremat_sketch2seg,distmat_sketch2seg] = ...
        srec_cover_pts2pts(ptsample,dirsample,ptseg,dirseg,...
        'allcover',false,'kpts',kpts,'ncovermin',topncover);
    
    % a point in sketch only covers topn points in segment
    [distsort,idxsort] = sort(distmat_sketch2seg,2);
    idxuse = idxsort(:,1:min(length(idxsort),topncover));
    distuse = distsort(:,1:size(idxuse,2));
    jmat = idxuse;
    imat = repmat((1:size(idxuse,1))',1,size(idxuse,2));
    maskuse = ~isnan(distuse);
    induse = sub2ind(size(covermat_sketch2seg),imat(maskuse),jmat(maskuse));
    covermat_sketch2seg(:) = false; %filter out points outside of topn coverage
    covermat_sketch2seg(induse) = true;
    distmat_sketch2seg(~covermat_sketch2seg) = nan;
    
    % dilate coverage
    [is,js] = find(covermat_sketch2seg);
    ptseg_covered = ptseg(:,js);
    [jjs,dmat] = knnsearch(ptseg',ptseg_covered','K',ndilatepts);
    iis = repmat(is(:),1,size(jjs,2));
    inds = sub2ind(size(covermat_sketch2seg),iis(:),jjs(:));
    covermat_sketch2seg(inds) = true;
    distmat_sketch2seg(inds) = dmat(:);
    
    % extract coverage information for each segment
    % make the seglbs2ptseg covermat
    useglbs = unique(seglbs);
    covermat_seglbs2ptseg = false(nseglbs,size(ptseg,2));
    for s = useglbs(:)'
        masksampleinseg = seglbs == s;
        maskptseg_covered = any(covermat_sketch2seg(masksampleinseg,:),1);
        covermat_seglbs2ptseg(s,:) = maskptseg_covered;
        
        coverlen_seg2comp(s,i) = mean(maskptseg_covered);
        dist_sample2seg = nanmean(distmat_sketch2seg(masksampleinseg,:),2);
        coverdist_seg2comp(s,i) = nanmean(dist_sample2seg);
    end
    
    % compute confliction by first grouping seglbs by lines
    idxline_touch = find(any(seglbs2line(useglbs,:),1)); %the seglbs covering this component touches these lines
    seglbs_group_by_line = cell(1,length(idxline_touch));
    for k=1:length(seglbs_group_by_line)
        idx = find(seglbs2line(useglbs,idxline_touch(k)));
        seglbs_group_by_line{k} = useglbs(idx);
    end
    
    % compute confliction for each pair of group
    coverconflict_seg2seg = false(nseglbs,nseglbs);
    distmat_seglbs2seglbs = srec_distfunc_overlap_by_sample(covermat_seglbs2ptseg);
    distmat_seglbs2seglbs(eye(size(distmat_seglbs2seglbs))>0) = inf;
    distmat_seglbs2seglbs(distmat_seglbs2seglbs==1) = inf;
    for g1 = 1:length(seglbs_group_by_line)
        for g2 = g1+1:length(seglbs_group_by_line)
            s1 = seglbs_group_by_line{g1};
            s2 = seglbs_group_by_line{g2};
            c1 = any(covermat_seglbs2ptseg(s1,:),1);
            c2 = any(covermat_seglbs2ptseg(s2,:),1);
            ovrate = sum(c1&c2)/min(sum(c1),sum(c2));
            
%             if i==111
%                 tmp_pts_sketch1 = ptsketch(:,ismember(obj.m_seglbs_per_sample,s1));
%                 tmp_pts_sketch2 = ptsketch(:,ismember(obj.m_seglbs_per_sample,s2));
%                 tmp_pts_seg1 = ptseg(:,c1);
%                 tmp_pts_seg2 = ptseg(:,c2);
% 
%                 close all;
%                 figure;hold on;
%                 util_scatter_pts(ptsketch,'k.');
%                 util_scatter_pts(ptseg,'bo');
%                 util_scatter_pts(tmp_pts_sketch1,'rx');
%                 util_scatter_pts(tmp_pts_seg1,'rh');
%                 util_scatter_pts(tmp_pts_sketch2,'gx');
%                 util_scatter_pts(tmp_pts_seg2,'gh');
%                 axis tight
%             end
            
            if isnan(ovrate) %abnormal situation
                ovrate = 0;
            end
            if ovrate > thres_conflict_overlap_ratio
                %confliction occurs, record it
                
                % each seglbs in s1 conflicts with the seglbs in s2 that
                % overlaps the most
                [dist_conf,idx_conf] = min(distmat_seglbs2seglbs(s1,:),[],2);
                useconf = ~isnan(dist_conf) & dist_conf~=inf;
                s1_from = s1(useconf);
                s1_to = idx_conf(useconf);
                idx = sub2ind(size(coverconflict_seg2seg),s1_from(:),s1_to(:));
                coverconflict_seg2seg(idx) = true;
                
                % similarly for s2
                [dist_conf,idx_conf] = min(distmat_seglbs2seglbs(s2,:),[],2);
                useconf = ~isnan(dist_conf);
                s2_from = s2(useconf);
                s2_to = idx_conf(useconf);
                idx = sub2ind(size(coverconflict_seg2seg),s2_from(:),s2_to(:));
                coverconflict_seg2seg(idx) = true;
            end
        end
    end
    
    %     % compute confliction
    %     coverconflict_seg2seg = false(nseglbs,nseglbs);
    %     for s1 = useglbs(:)'
    %         for s2 = useglbs(:)'
    %             c1 = covermat_seglbs2ptseg(s1,:);
    %             c2 = covermat_seglbs2ptseg(s2,:);
    %             ovrate = sum(c1&c2)/min(sum(c1),sum(c2));
    %             if isnan(ovrate) %abnormal situation
    %                 ovrate = 0;
    %             end
    %             if ovrate > thres_conflict_overlap_ratio
    %                 %confliction occurs
    %                 coverconflict_seg2seg(s1,s2) = true;
    %             end
    %         end
    %     end
    coverconflict_seg2seg = coverconflict_seg2seg | coverconflict_seg2seg';
    coverconflict_seg2seg(eye(size(coverconflict_seg2seg))>0) = 0; %don't conflict with self
    
    % short segments do not conflict with others
    coverconflict_seg2seg(short_seglbs,:) = 0;
    coverconflict_seg2seg(:,short_seglbs) = 0;
    coverconflict_seg2seg2comp(:,:,i) = coverconflict_seg2seg;
    
    % compute coverlen by matching segment pts to sketch pts, we prefer
    % this because sometimes the sketch uses a single line to match a
    % double line component, and we do this for each segment
    for s=useglbs(:)'
        % sample in sketch
        masksampleinseg = seglbs == s;
        ptsketch_thiseg = ptsample(:,masksampleinseg);
        dirsketch_thiseg = dirsample(:,masksampleinseg);
        
        covermat_seg2sketch = srec_cover_pts2pts(...
            ptseg,dirseg,ptsketch_thiseg,dirsketch_thiseg,...
            'allcover',false,'kpts',kpts,'disthres',disthres);
        ncoverseg = sum(any(covermat_seg2sketch,2));
        coverlen_seg2comp(s,i) = ncoverseg/size(ptseg,2);
    end
end

% cost to score conversion
maskinvalid = isnan(coverdist_seg2comp);
vals = coverdist_seg2comp(~maskinvalid);
vals = 1-mat2gray(vals.^2)+0.01;
coverfitness_seg2comp = zeros(size(maskinvalid));
coverfitness_seg2comp(~maskinvalid) = vals;
% coverfitness_seg2comp = 1-mat2gray(coverdist_seg2comp)+0.01;
% coverfitness_seg2comp(maskinvalid) = 0;

% record result
obj.m_coverfitness_seg2comp = coverfitness_seg2comp;
obj.m_coverlen_seg2comp = coverlen_seg2comp;
obj.m_conflict_seg2seg2comp = coverconflict_seg2seg2comp;

end

