function cout = dilate(u,b,n)
%DILATE	Dilate a binary image.
%	BWOUT = DILATE(BW,'method') dilates the binary Image BW 
%	using 'method'. Possible methods are 'dilate','fatten',
%	or 'thicken'.  The method 'dilate' adds 8-connected pixels
%	around all objects.  'fatten' is the same as dilate except
%	that objects are not allowed to bridge. 'thicken' adds
%	pixels to the boundary of objects while preserving the
%	Euler number. The default method is 'thicken'.  BW must
%	be a binary image (it can only contain the values 0 and 1).
%
%	BWOUT = DILATE(BW, SE) performs a generalized dilation of 
%	the binary image BW with the structuring element SE.  The
%	image will be dilated wherever pixels in the image BW 
%	intersect the non-zero elements in the structuring element
%	SE.  SE must contain only 1's or 0's.  
%
%	DILATE(BW,'method',N), DILATE(BW,SE,N), or DILATE(BW,N) 
%	performs DILATE N times.
%
%	See also ERODE, BWMORPH, BWEULER.

%	Clay M. Thompson 8-9-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.9 $  $Date: 1993/10/21 12:59:32 $

error(nargchk(1,3,nargin));

if nargin==1, b = 'thick'; n = 1; end
if nargin==2,
  if ~isstr(b) & max(size(b))==1, 
    n = b; b = 'thick';
  else
    n = 1;
  end
end

if isstr(b), % method string
  method = [lower(b) '    ']; % Protect against short method string.
  if method(1)=='d' | method(1)=='f' | method(1)=='t',
    c = bwmorph(u,method,n);
  else
    error([deblank(method),' is an unknown method.']);
  end

else
  if prod(size(u))<prod(size(b)), % Switch arguments for faster computation.
    tmp = u; u = b; b = tmp;
    switched = 1;
  else
    switched = 0;
  end

  [mu,nu] = size(u);
  sten = rot90(b,2);
  [ms,ns] = size(sten);

  % Determine indexes into central part that is the same size as the original U.
  if switched,
    rows = floor((mu-1)/2) + (1:ms);
    cols = floor((nu-1)/2) + (1:ns);
  else
    rows = floor((ms-1)/2) + (1:mu);
    cols = floor((ns-1)/2) + (1:nu);
  end

  c = zeros(ms+mu-1,ns+nu-1);
  for i=1:ms
    for j=1:ns
      w = sten(ms-i+1,ns-j+1);
      if w~=0,
        c(i:i+mu-1,j:j+nu-1) = c(i:i+mu-1,j:j+nu-1) | u;
      end
    end
  end

  for i=2:n,
    a = c(rows,cols);
    c = zeros(ms+mu-1,ns+nu-1);
    for i=1:ms
  	  for j=1:ns
        w = sten(ms-i+1,ns-j+1);
        if w~=0,
          c(i:i+mu-1,j:j+nu-1) = c(i:i+mu-1,j:j+nu-1) | a;
  		end
      end
    end
  end

  % Return central part that is the same size as u.
  c = c(rows,cols);
end

if nargout==0, imshow(c,2), return, end
cout = c;
