function [b,bm] = bands3(b2,bpks,dmin)
% [b,bm] = bands3(b2,bpks,dmin)
%
% Merges bands that are close and have same label
%
% On input: 
%           b2: bands matrix of dimension # bands by 20
%         bpks: a mask image which is non-zero wherever there's a peak
%         bmin: threshold distance to merge neighboring peaks
%
%  if two peak points are close in Euclidean distance and have the
%  same label (from the ridge grouping and labeling), then merge them
%
[mp np] = size(bpks);
bm = zeros(mp,np);
[m n] = size(b2);
b = b2;
maxl = max(b2(:,14));
labels = zeros(maxl);

for i1 = 1:m
  if b(i1,20)==0       % equivalence not set to anything yet
    l1 = b2(i1,14);    % get label
    if l1~= 0          % if there is a (ridge component) label,
      b(i1,20) = i1;   % set equivalent to self, else not a peak
      bm(b2(i1,15),b2(i1,16)) = 255;   % set pixel on in mask image
      for i2 = i1+1:m    % check for other peaks with common label
        l2 = b2(i2,14);  % and set equivalent if close enough
        if l1==l2
          drow = b2(i1,15)-b2(i2,15);
          dcol = b2(i1,16)-b2(i2,16);
          dist = sqrt(drow*drow+dcol*dcol);
          if dist<dmin
            b(i2,20) = i1;
          end
        end
      end
    end
  end
end
