function visual( A, mag, normalize, cols, fignum )
% visual - display a set of image patches
%
% A          the basis, with patches as column vectors
% mag        magnification factor
% normalize  do we normalize each basis vector to fill scale?
% cols       number of columns (x-dimension of map)
% fignum     in which figure to plot it

% Normalize each column so min or max is -1 or +1 respectively
if normalize,
  A = A./(ones(size(A,1),1)*max(abs(A)));
end

% Get maximum absolute value (it represents white or black; zero is gray)
maxi = max(max(abs(A)));
mini = -maxi;

% This is the size of the window
dim = sqrt(size(A,1));

% Helpful quantities
dimm = dim-1;
dimp = dim+1;
if ~exist('cols'), cols=ceil(sqrt(size(A,2))); end
rows = ceil(size(A,2)/cols);

% Initialization of the image
I = maxi*ones(dim*rows+rows-1,dim*cols+cols-1); 

for i=0:rows-1
  for j=0:cols-1
    
    if i*cols+j+1>size(A,2)
      % This leaves it gray
      
    else
      % This sets the patch
      I(i*dimp+1:i*dimp+dim,j*dimp+1:j*dimp+dim) = ...
	  reshape(A(:,i*cols+j+1),[dim dim]);
    end
    
  end
end

I = imresize(I,mag);

if exist('fignum'), figure(fignum);
else figure;
end

colormap(gray(256));
iptsetpref('ImshowBorder','tight'); 
subplot('position',[0,0,1,1]);
imshow(I,[mini maxi]);
truesize;  

