function a = col2im(b,block,mat,kind)
%COL2IM Rearrange column blocks to form image.
%	COL2IM undoes the effects of IM2COL and is used to reform
%	the image after column processing.  COL2IM handles two types
%	of blocks, 'distinct' and 'sliding'. 'sliding' is the default.
%	See the Image Processing Toolbox guide for the definition of
%	these two block types.
%
%	A = COL2IM(B,[M N],[MROWS NCOLS],'distinct') rearranges each
%	column of B into distinct M-by-N blocks to create the matrix
%	A of size MROWS-by-NCOLS.  If B = [A11(:) A21(:) A12(:) A22(:)]
%	where each column has length M*N, then A = [A11 A12;A21 A22].
%
%	A = COL2IM(B,[M N],[MROWS NCOLS],'sliding') rearranges the row
%	vector B into a matrix of size (MROWS-M+1)-by-(NCOLS-N+1).  
%	B must be vector of size 1-by-(MROWS-M+1)*(NCOLS-N+1).  B is 
%	usually created by processing the output of IM2COL(...,'sliding')
%	using a function that compresses each column to a scalar 
%	(examples are SUM and MAX).
%
%	COL2IM is used by the function COLFILT.
%
%	Example use: Distinct Blocks      | Example use: Sliding Blocks
%	 [m,n] = size(a);                 |  [m,n] = size(a);
%	 b = im2col(a,[3 3],'distinct');  |  b = im2col(a,[3 3],'sliding');
%	 c = (ones(9,1)/9)*sum(b);        |  c = sum(b)/9;
%	 d = col2im(c,[3 3],size(a),'d'); |  d = col2im(c,[3 3],size(a),'s');
%
%	See also: IM2COL, COLFILT.

%       Copyright (c) 1993 by The MathWorks, Inc.
%       $Revision: 1.4 $  $Date: 1993/10/21 12:59:32 $

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

if nargin<3, kind = 'sliding'; end

if ~isstr(kind), 
  error('The block type parameter must be either ''distinct'' or ''sliding''.');
end

kind = [lower(kind) ' ']; % Protect against short string

if kind(1)=='d', % Distinct
  % Check argument sizes
  [m,n] = size(b);
  if prod(block)~=m, error('The row size of B must be M*N.'); end
  
  % Find size of padded A.
  mpad = rem(mat(1),block(1)); if mpad>0, mpad = block(1)-mpad; end
  npad = rem(mat(2),block(2)); if npad>0, npad = block(2)-npad; end
  mpad = mat(1)+mpad; npad = mat(2)+npad;
  if mpad*npad/prod(block)~=n, 
    error('The column size of b not consistent with BLK2COL size.');
  end
  
  mblocks = mpad/block(1);
  nblocks = npad/block(2);
  aa = zeros(mpad,npad);
  x = zeros(block);
  rows = 1:block(1); cols = 1:block(2);
  for i=0:mblocks-1,
    for j=0:nblocks-1,
      x(:) = b(:,i+j*mblocks+1); 
      aa(i*block(1)+rows,j*block(2)+cols) = x;
    end
  end
  a = aa(1:mat(1),1:mat(2));
  
elseif kind(1)=='s', % sliding
  a = reshape(b,mat(1)-block(1)+1,mat(2)-block(2)+1);
else
  error([deblank(kind),' is a unknown block type']);

end

