function ccvisual( X, B, cols, fignum, mag )
% ccvisual - display complex-cell activity patterns
%
% X          the activity patterns
% B          contains the icons for the complex cells
% cols       number of columns in display
% fignum     in which figure to plot it
% mag        magnification factor (default is 1)

if ~exist('mag'), mag=1; end

% The icons are binary and sparse so this will speed up computations
% quite a bit!
B = sparse(B);

% If we have negative values, we show everything on a scale where
% negative values are dark, zero is gray, and positive bright. Otherwise,
% zero is black and positive values are bright.
if min(min(X))<0, zeroisgray=1; else zeroisgray=0; end

% This is the patch size of the display
winsize = sqrt(size(B,1));

% This will hold the results
A = zeros(winsize^2,size(X,2));

fprintf('ccvisual: ');

% Step through each data point
for i=1:size(X,2)

  % Show progress
  fprintf('.');
  
  % Multiply each column j of B by coefficient X(j,i)
  Bm = B*sparse(1:size(X,1),1:size(X,1),X(:,i)');
    
  % Take MAX
  pospart = abs(max(Bm')');
  negpart = abs(min(Bm')');
  A(:,i) = (pospart>negpart).*pospart - (negpart>pospart).*negpart;
end

fprintf('\n');

% Show the result
if zeroisgray==0,
  A = A-min(min(A));
  A = A/max(max(A));
  A = (A-0.5)*2;
end

if exist('fignum'), visual( A, mag, 1, cols, fignum );
else visual( A, mag, 1, cols );
end

drawnow;

return

