function h = montage(a,siz)
%MONTAGE Display image deck as a rectangular montage.
%	MONTAGE(D,[M N P]) displays the images in the M-by-N-by-P
%	deck D as a roughly square montage.
%
%	H = MONTAGE(D,[M N P]) returns a handle to an image object.
%
%	See also IMMOVIE, IMSLICE.

%	Clay M. Thompson 5-13-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.7 $  $Date: 1993/09/10 01:08:00 $

nn = sqrt(prod(siz))/siz(2);
mm = siz(3)/nn;
if (ceil(nn)-nn) < (ceil(mm)-mm),
  nn = ceil(nn); mm = ceil(siz(3)/nn);
else
  mm = ceil(mm); nn = ceil(siz(3)/mm);
end

b = ones(mm*siz(1),nn*siz(2));

rows = 1:siz(1); cols = 1:siz(2);
for i=0:mm-1,
  for j=0:nn-1,
    k = j+i*nn+1;
    if k<=siz(3),
      b(rows+i*siz(1),cols+j*siz(2)) = a(imslice(siz,k));
    end
  end
end

cm = colormap;
if isind(a(imslice(siz,1))),
  hh = imshow(b);
elseif isgray(a(imslice(siz,1))),
  idx = round(b*(size(cm,1)-1))+1;
  hh = imshow(idx);
  set(hh,'UserData',[0 1])
else
  hh = imshow(b);
end
colormap(cm)

if nargout > 0
	h = hh;
end

