function b = ridge(r1)
% b = ridge(r1)
%    r1: output from ridge1
% returns: center locations of each connected ridge set have value 1
%          

[m n] = size(r1);
b = zeros(m,n);
a = r1;
label = 0;

for ii = 2:m-1
  for jj = 2:n-1
    count = 0;
    if a(ii,jj) == 4     % scan for left part
      count = count+1; a(ii,jj) = 0;
      ic = ii; jc = jj; more = 1;
      while more > 0
        more = 0;
        if (jc+1<=n) & (a(ic,jc+1) == 4 | a(ic,jc+1) == 2)
          more = 1; a(ic,jc+1) = 0;
          count = count+1; jc = jc+1;
        elseif (ic-1>0) & (jc+1 <= n) & (a(ic-1,jc+1) == 4 | a(ic-1,jc+1)==2)
            more = 1; a(ic-1,jc+1) = 0; count = count+1;
            ic = ic-1; jc = jc+1;
        elseif (ic+1<=m) & (jc+1<=n) & (a(ic+1,jc+1)==4 | a(ic+1,jc+1)==2)
            more = 1; a(ic+1,jc+1)=0;
            count = count+1; ic = ic+1; jc = jc+1;
        end
      end
      if count < 3
        break;
      end
      marki = ic; markj = jc;
      if a(ic,jc+1) == 16       % peak
        a(ic,jc+1) = 0; jc = jc+1;
      elseif (ic-1>0) & (jc+1<=n) & a(ic-1,jc+1) == 16
        a(ic-1,jc+1) = 0; ic = ic-1; jc = jc+1;
      elseif (ic+1<=m) & (jc+1<=n) & a(ic+1,jc+1) == 16
        a(ic+1,jc+1) = 0; ic = ic+1; jc = jc+1;
      end
      more = 1; count = 0;
      while more > 0
        more = 0;
        if (jc+1<=n) & (a(ic,jc+1) == 8 | a(ic,jc+1) == 2)
          more = 1; a(ic,jc+1) = 0; count = count+1; jc = jc+1;
        elseif (ic-1>0) & (jc+1<=n) & (a(ic-1,jc+1) == 8 | a(ic-1,jc+1) == 2)
          more = 1; a(ic-1,jc+1) = 0; count = count+1; ic = ic-1; jc = jc+1;
        elseif (ic+1<=m) & (jc+1<=n) & (a(ic+1,jc+1) == 8 | a(ic+1,jc+1)==2)
          more = 1; a(ic+1,jc+1) = 0; count = count+1; ic = ic+1; jc = jc+1;
        end
      end
      if count < 3
        break;
      end
      label = label + 1;
      b(marki,markj) = label;
    end
  end
end

          
            