function recon = reconstructInput(rbm, data, width, height, binary_vis, numgibbs)
%given a trained RBM, reconstruct the given data with gibbs sampling and
%plot the data and reconstructions
% rbm = {weights, hidden biases, visible biases};
% data = [input dimension, number of samples];
% width,height = default width is floor(sqrt(size(data,1)))
% binaryvis = whether or not the visible units should be sampled or if
%   their activation probabilities should be treated as grayscale values.
%   (dafault true)
% numgibbs = the number of reconstructions to compute and plot (dafault 4).

if nargin<2; fprintf('Usage: reconstructInput(rbm, data)\n'); return; end
[dim,nsample]=size(data); w=rbm{1}; hb=rbm{2}; vb=rbm{3}; recon=data; 
if nargin<4; width= floor(sqrt(dim)); height=size(data,1)/width; end
if nargin<5; binary_vis=true; end;    if nargin<6; numgibbs = 4; end
figure; set(gcf,'Position',get(0,'screensize')); %maximize figure window

for i=0:numgibbs
  for j=1:nsample/2
    subplot(numgibbs+1, nsample/2, i*nsample/2 + j);
    imagesc( reshape(recon(:,j),[width height]) );
    colormap gray; axis off; axis image;
  end
  drawnow;
  h = w * recon + repmat(hb,[1 nsample]);
  hs = h > rand(size(h));
  recon = w'*hs + repmat(vb,[1 nsample]);
  if binary_vis; recon = +(recon > rand(dim,nsample)); end
end