function z = tile(data);
% function z = tile(data);
% data should be 4-D, with dimensions a*b*c*d
% output is a 2d array with a*b images tiled in a c*d grid

s = size(data);
nd = length(s);

if nd<3 || nd>4
    disp('tile.m: data must be 3 or 4 dimensional');
    return;
end

if nd==4
    for k=1:size(data,4)
        zz = squeeze(data(:,:,1,k));
        for l=2:size(data,3)
            zz = cat(1,zz,squeeze(data(:,:,l,k)));
        end
        if k==1
            z = zz;
        else
            z = cat(2,z,zz);
        end
    end
else
    zr = 1:floor(sqrt(s(3)));
    r = max(find(rem(s(3),zr)==0));
    c = s(3)/r;
    for k=1:r
        roff = (k-1)*c;
        zz = squeeze(data(:,:,roff+1));
        for l=2:c
            zz = [zz squeeze(data(:,:,roff+l))];
        end
        if k==1
            z = zz;
        else
            z = [z; zz];
        end
    end

end