function [pts,idx] = select_sample_by_votepts_in_grid( sketchimg,gridsize,votepts,scores )
% [pts,idx] = select_sample_by_votepts_in_grid( sketchimg,gridsize,votepts,scores )
% select sample points based on vote points and a grid
% gridsize = [m,n], number of divisions along x and y
% votepts = vote points
% scores = fit score of each vote points

% the grid is within the sketch's AABB
[xs ys] = find(sketchimg);
[boxlens,mincorner] = util_make_aabb_from_pts([xs(:) ys(:)]');

% for each cell, find the highest-scored vote point, use it as sample
% calculate votepts's new coordinate in the grid
dx = boxlens(1)/gridsize(1);
dy = boxlens(2)/gridsize(2);

xs = ceil((votepts(1,:)-mincorner(1))/dx);
xs = min(xs,gridsize(1)); %truncate xs
xs = max(xs,1);

ys = ceil((votepts(2,:)-mincorner(2))/dy);
ys = min(ys,gridsize(2)); %truncate ys
ys = max(ys,1);

idxsel = [];
for i=1:gridsize(1)
    for j=1:gridsize(2)
        mask = xs==i & ys==j;
        idx = find(mask);
        
        if isempty(idx)
            continue;
        end
        
        [~,idxmax] = max(scores(idx));
        idxsel(end+1) = idx(idxmax);
    end
end

idx = idxsel;
pts = votepts(:,idx);

end

