function l = labelr8(a)
%
% labelr8: recursively label 8-connected components of an image
% On input:
%     a:     2D array of image intensities
% On output:
%     l:    2D array of uniquely and consecutively labeled 8-connected pixels
% Call:
%     l = labelr(a)
%
%  Authors:	Tom Henderson and Scott Morris
%		Univ of Utah
%		5 Sept 1996
%

[m,n] = size(a);
l = zeros(m+2,n+2);   % add zero surround around image which makes it
l(2:m+1,2:n+1) = -a;  %  unnecessary to check image boundaries
count = 0;

for i1 = 2:m+1
  for j1 = 2:n+1
    if l(i1,j1) < 0    % unlabeled pixel
	  count = count+1;   % get next label
	  l(i1,j1) = count;  % label pixel
	  last = 1;          % push pixel on neighbors list
	  nei(last,1) = i1;  nei(last,2) = j1;
	  while last ~= 0
	    i2 = nei(last,1);  j2 = nei(last,2);
		last = last-1;
		if l(i2-1,j2-1) < 0     % upper left
		  last = last+1;
		  nei(last,1) = i2-1;
		  nei(last,2) = j2-1;
		  l(i2-1,j2-1) = count;
		end
		if l(i2-1,j2) < 0     % up
		  last = last+1;
		  nei(last,1) = i2-1;
		  nei(last,2) = j2;
		  l(i2-1,j2) = count;
		end
		if l(i2-1,j2+1) < 0     % upper right
		  last = last+1;
		  nei(last,1) = i2-1;
		  nei(last,2) = j2+1;
		  l(i2-1,j2+1) = count;
		end
		if l(i2,j2-1) < 0     % left
		  last = last+1;
		  nei(last,1) = i2;
		  nei(last,2) = j2-1;
		  l(i2,j2-1) = count;
		end
		if l(i2,j2+1) < 0     % right
		  last = last+1;
		  nei(last,1) = i2;
		  nei(last,2) = j2+1;
		  l(i2,j2+1) = count;
		end
		if l(i2+1,j2-1) < 0     % lower left
		  last = last+1;
		  nei(last,1) = i2+1;
		  nei(last,2) = j2-1;
		  l(i2+1,j2-1) = count;
		end
		if l(i2+1,j2) < 0     % lower
		  last = last+1;
		  nei(last,1) = i2+1;
		  nei(last,2) = j2;
		  l(i2+1,j2) = count;
		end
		if l(i2+1,j2+1) < 0     % lower right
		  last = last+1;
		  nei(last,1) = i2+1;
		  nei(last,2) = j2+1;
		  l(i2+1,j2+1) = count;
		end
	  end
	end
  end
end
l = l(2:m+1,2:n+1);  % eliminate boundary around image
