function r = ridge1(h)
% r = ridge1(h)
%    h: height image
% returns: valleys                labeled as 1
%          ridges flat            labeled as 2
%          ridges rising to right labeled as 4
%          ridges rising to  left labeled as 8
%          peaks                  labeled as 16
%          

[m n] = size(h);
r = zeros(m,n);

for indexi = 2:m-1
  for indexj = 2:n-1
   if h(indexi,indexj) ~= 0       % only do non-zero pixels
    a = h(indexi-1,indexj-1);     %    
    b = h(indexi,indexj-1);       %      a     d
    c = h(indexi+1,indexj-1);     %      b  x  e
    x = h(indexi,indexj);         %      c     f
    d = h(indexi-1,indexj+1);     %
    e = h(indexi,indexj+1);       % compare x to b (if non-zero) else a, then c
    f = h(indexi+1,indexj+1);     % likewise  to e, else d, then f
    left = 0;
    if b ~= 0
      left = b;
    end
    if left == 0 & a ~= 0
      left = a;
    end
    if left == 0
      left = c;
    end
    right = 0;
    if e ~= 0
      right = e;
    end
    if right == 0 & d ~= 0
      right = d;
    end
    if right == 0
      right = f;
    end
    if left<=x & x<=right       % rising from left to right
      r(indexi,indexj) = 4;
    end
    if left>=x & x>=right       % rising from right to left
      r(indexi,indexj) = 8;
    end
    if left<x & x>right         % peak
       r(indexi,indexj) = 16;
    end
    if left>x & x<right         % valley
       r(indexi,indexj) = 1;
    end
    if left==x & x==right         % flat
       r(indexi,indexj) = 2;
    end
   end
  end
end
