function [sample_data, digit_img] = vis_digits(data, index, numrandom, showimg)
% assume data is m x m x K matrix, each m x m slice is an image
% pull and stitich a bigger collage from the designated indexes
% 
% EE4830, Spring 2008

[m1, m2, k] = size(data);
if nargin < 4, showimg = true; end
if nargin < 3, numrandom = 0; end
if ~isempty(index)
    n = length(index);
end
if nargin>2 && numrandom>0
    n = numrandom;
    index = randperm(k);
    index = sort(index(1:n));
end
assert(~isempty(index), 'data sample cannot be empty');

numcols = ceil(sqrt(n));
digit_img = zeros(m1*numcols, m2*numcols);
ij = 0;
for i = 1 : numcols
    idx = (i-1)*m1 + (1:m1);
    for j = 1 : numcols
        jdx = (j-1)*m2 + (1:m2);
        ij = ij + 1;
        if ij <= length(index)
            digit_img(idx, jdx) = data(:, :, index(ij)) ;
        end
    end
end
if showimg
    imshow(digit_img)
end
if nargout>0, 
    sample_data = double(data(:,:,index));
    sample_data = reshape(sample_data, m1*m2, length(index));
else
    sample_data = [];
end
