function c = conv2(u,b,shape)
%CONV2	Two dimensional convolution.
%	C = CONV2(A, B) performs the 2-D convolution of matrices
%	A and B.   If [ma,na] = size(A) and [mb,nb] = size(B), then 
%	size(C) = [ma+mb-1,na+nb-1]. 
%
%	C = CONV2(A,B,'shape') returns a subsection of the 2-D
%	convolution with size specified by 'shape':
%	  'full'  - (default) returns the full 2-D convolution, 
%	  'same'  - returns the central part of the convolution 
%	            that is the same size as A.
%	  'valid' - returns only those parts of the convolution
%	            that are computed without the zero-padded
%	            edges, size(C) = [ma-mb+1,na-nb+1] when
%	            size(A) > size(B).
%	CONV2 is fastest when size(A) > size(B).
%
%	See also XCORR2, CONV, XCORR, DECONV, FILTER2.

%	Marc Ullman   2-6-86
%	Revised 2-18-87 J.N. Little
%	Revised 10-22-91 L. Shure, C. Thompson
%	Copyright (c) 1984-93 by The MathWorks, Inc.

error(nargchk(2,3,nargin));
if nargin<3, shape = 'full'; end

code = [shape,' ']; code = code(1);
if isempty(find(code=='svf')), error('Unknown shape parameter.'); end

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);

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) + w*u;
		end
	end
end

if code=='s',
  % Return the 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);
    c = c(rows,cols);
  else
    rows = floor((ms-1)/2) + (1:mu);
    cols = floor((ns-1)/2) + (1:nu);
    c = c(rows,cols);
  end

elseif code == 'v',
  % Return the central part that is computed without the padded edges.
  rows = ms-1 + (1:mu-ms+1);
  cols = ns-1 + (1:nu-ns+1);
  c = c(rows,cols);
end
