function img = img_layout ( rows , cols , cell , img , patch , bkg_col )

if (nargin < 6)
    bkg_col = 255;
end

pad_size = 4; % parameter, change it

if ( isempty (img) )
    % patch plus one row and one column padding
    tmp = uint8(bkg_col*ones(size(patch)+[pad_size,pad_size,0]));
    img = repmat(tmp,rows,cols);
end

if (any(size(repmat(patch,[rows,cols]))+[rows*pad_size,cols*pad_size,0] ~= size(img))) %if the size is not equal the first patch
    % retrieve first initial dimensions
    xh = size(img,1)/rows-pad_size;
    xw = size(img,2)/cols-pad_size;
    % resize it
    patch = imresize (patch,[xh,xw]);
end

[h,w,~] = size (patch);

% find the position of indexed cell
xrow = ceil(cell / cols);
xcol = mod(cell, cols);
if (xcol == 0) xcol=cols; end

% draw the image in the indexed position
xx = (xrow-1)*(h+pad_size)+1;
yy = (xcol-1)*(w+pad_size)+1;
img ( xx:xx+h-1 , yy:yy+w-1 , : ) = patch;