function [bbox, bboxcell] = imdetecthog(im, model)

feadim = 32;
maxcandidate = 3;
% get filters
filters{1} = reshape(model.w, model.height, model.width, feadim);

% compute hog features
tic;
for ii = 1:length(model.scale)
    ims = im2double(imresize(im, model.scale(ii)));
    feaarr = features(ims, model.grid);
    bbscore = fconv(feaarr, filters, 1, 1);
end

% assume single scale
bbscorematrix = bbscore{1};
minscore = min(bbscorematrix(:));
interval = max(bbscorematrix(:)) - min(bbscorematrix(:));
for ii = 1:maxcandidate
    bbox.maxscore = max(bbscorematrix(:));
    [top(ii,1), left(ii,1)] = find(bbscorematrix == bbox.maxscore);
    bbox.maxscore = (bbox.maxscore - minscore)/interval;

    % get bounding boxes
    bbox.top = model.grid*top(ii) - model.grid;
    bbox.left = model.grid*left(ii) - model.grid;
    bbox.bottom = bbox.top + model.height*model.grid + 2*model.grid - 1;
    bbox.right = bbox.left + model.width*model.grid + 2*model.grid - 1;
%    bbox.cheight = round((top(ii) + (model.height/2.0))*model.grid./model.scale);
%    bbox.cwidth = round((left(ii) + (model.width/2.0))*model.grid./model.scale);

    % make sure bounding boxes inside image
    bbox.bottom = min(bbox.bottom, size(im,1));
    bbox.top = max(bbox.top,1);
    bbox.right = min(bbox.right, size(im,2));
    bbox.left = max(bbox.left,1);
    bbox.cheight = round((bbox.top + (bbox.bottom - bbox.top)/2.0)./model.scale);
    bbox.cwidth = round((bbox.left + (bbox.right - bbox.left)/2.0)./model.scale);
    bboxcell{ii} = bbox;

    % non maximum suppression
    minheight = max(1, round(top(ii)+1 - model.height/2.0));
    maxheight = min(size(bbscorematrix,1), round(top(ii)-1 + model.width/2.0));
    minwidth = max(1, round(left(ii)+1 - model.width/2.0));
    maxwidth = min(size(bbscorematrix,2), round(left(ii)-1 + model.width/2.0));
    bbscorematrix(minheight:maxheight,minwidth:maxwidth) = min(bbscorematrix(:));    
end
bbox = bboxcell{1};
dettime = toc;
disp(['Detection time is ' num2str(dettime)]);

