function M = getClusterPatchMosaic(patches, canonicalSize, selected)
if nargin < 3
  selected = zeros(size(patches));
end
toShow = length(patches);
rows = ceil(sqrt(toShow));
cols = ceil(toShow / rows);

maxPatches = rows * cols;
% Mosaic patches
MP = cell(1, maxPatches);
numPats = 0;
paddingSize = [4 4 0];
for i = 1 : length(patches)
  if i > maxPatches
    break;
  end
  D = patches(i);
  I = im2double(imread(D.im));
  if D.flip
    I(:,:,1) = fliplr(I(:,:,1));
    I(:,:,2) = fliplr(I(:,:,2));
    I(:,:,3) = fliplr(I(:,:,3));
  end

  I = getSubImg(I, D);
  MP{i} = imresize_old(I, canonicalSize, 'bilinear');
  MP{i} = doPadding(MP{i}, paddingSize, selected(i));
  numPats = numPats + 1;
end

while numPats < maxPatches
  numPats = numPats + 1;
  MP{numPats} = zeros([canonicalSize 3]);
  MP{numPats} = doPadding(MP{numPats}, paddingSize, selected(i));
end
M = cell2mat(reshape(MP, cols, rows)');
end

function s = getSubImg(I, D)
if D.x1 < 1
  D.x1 = 1;
end
if D.x2 > D.size.ncols
  D.x2 = D.size.ncols;
end
if D.y1 < 1
  D.y1 = 1;
end
if D.y2 > D.size.nrows
  D.y2 = D.size.nrows;
end
s = I(D.y1:D.y2, D.x1:D.x2, :);
end


function newPat = doPadding(pat, padSize, selected)
[row, col, z] = size(pat);
newPat = ones([row col z] + 2 .* padSize);
if selected > 0
  cmap = colormap('Lines');
  ind = rem(selected, size(cmap, 1));
  newPat(:, :, 1) = cmap(ind, 1);
  newPat(:, :, 2) = cmap(ind, 2);
  newPat(:, :, 3) = cmap(ind, 3);
end
newPat(padSize(1) + 1 : padSize(1) + row, ...
  padSize(2) + 1 : padSize(2) + col, ...
  padSize(3) + 1 : padSize(3) + z) = pat;
end
