function mData = genMosaic(mData,TileSize,dval)
% Dette er en hjælpefunktion til Mosaic programmet.
% Den skal modtage 3 input argumenter og leverer et retur:
%   mData = data fra handles.mData
%   TileSize = antallet af fliser horisontalt. De vertikale udregnes så det
%              passer med den horisontale flise størrelse
%   DitherValue = værdi, som indikerer hvor tæt ens fliser må ligge
% Output:
%   mData - skal gemmes i handles.mData

num_files = length(mData.thumbs);
ref_img = imresize(mData.im,TileSize*ceil(mData.imsize/TileSize));
progress = waitbar(0, 'Creating Photomosiac...');
num_tiles = [size(ref_img,1) size(ref_img,2)]/TileSize;
pic_map = zeros(num_tiles);
tiles_done = 0;
for row_tile = 1:num_tiles(1)
    for col_tile = 1:num_tiles(2)
        shortest_dist = Inf;
        %get mean vals for the image tiles
        cur_tile = ref_img(TileSize*(row_tile-1)+1:TileSize*(row_tile), ...
        TileSize*(col_tile-1)+1:TileSize*(col_tile),:);
        %disp(sprintf('R=%i,C=%i',row_tile,col_tile));
        cur_RGB = mean(reshape(cur_tile, [], 3), 1);
        %find the closest thumb to each tile
        for thumb_tile = 1:num_files
            dist = sum((mData.RGB_val{thumb_tile} - cur_RGB) .^2);
            %if new pt is closer
            if dist < shortest_dist
                %implement dithering to limit use of tile in an area
                if isempty(find( ...
                        pic_map(max(row_tile-dval,1): ...
                        min(row_tile+dval,num_tiles(1)),... 
                        max(col_tile-dval,1): ...
                        min(col_tile+dval,num_tiles(2))) ... 
                        == thumb_tile, 1))
                    shortest_dist = dist;
                    pic_map(row_tile, col_tile) = thumb_tile;
                end
            end
        end
        tiles_done = tiles_done + 1;
        waitbar(tiles_done/(num_tiles(1)*num_tiles(2)), progress);
    end
end
close(progress);

% Take mapping of thumbnails and create photomosaic
progress = waitbar(0, 'Assembling Photomosaic...');
for row_tile = 1:num_tiles(1)
    cur_row = mData.thumbs{pic_map(row_tile, 1)};
    for col_tile = 2:num_tiles(2)
        cur_row = horzcat(cur_row, mData.thumbs{pic_map(row_tile, col_tile)});
    end
    if row_tile == 1
        mosaic = cur_row;
    else
        mosaic = vertcat(mosaic, cur_row);
        clear cur_row;
    end
    waitbar(row_tile/num_tiles(1), progress);
end
close(progress);
mData.mosaic = mosaic;
