function d = eightdir(gc,gr)
%
% eightdir: converts gradient direction into eight neighbors direction
%    d = eightdir(gc,gr)
%
%        3 2 1
%        4 . 0
%        5 6 7

[m,n] = size(gc);
d = zeros(m,n);
t1 = atan2(0.5,1); t2 = atan2(1,0.5); t3 = atan2(1,-0.5);
t4 = atan2(0.5,-1); t5 = atan2(-0.5,-1); t6 = atan2(-1,-0.5);
t7 = atan2(-1,0.5); t8 = atan2(-0.5,1);
t1 = posori(t1); t2 = posori(t2); t3 = posori(t3); t4 = posori(t4); 
t5 = posori(t5); t6 = posori(t6); t7 = posori(t7); t8 = posori(t8); 

for r = 1:m
  for c = 1:n
    theta = atan2(gr(r,c),gc(r,c));
    theta = posori(theta);
    if ((0<=theta) & (theta<t1)) | (t8<theta)
      d(r,c) = 0;
    elseif (t1<=theta) & (theta<t2)
      d(r,c) = 7;
    elseif (t2<=theta) & (theta<t3)
      d(r,c) = 6;
    elseif (t3<=theta) & (theta<t4)
      d(r,c) = 5;
    elseif (t4<=theta) & (theta<t5)
      d(r,c) = 4;
    elseif (t5<=theta) & (theta<t6)
      d(r,c) = 3;
    elseif (t6<=theta) & (theta<t7)
      d(r,c) = 2;
    elseif (t7<=theta) & (theta<t8)
      d(r,c) = 1;
    end
  end
end
