function evalAssignDetsToGroundTruth(dets, gt)
if length(dets) ~= length(gt)
  error(['Incorrect data. Number of detection images doesnt match the number' ...
    'of ground truth images.']);
end

[BB, confidence, ids] = getDetectionData(dets);
[sc,si]=sort(-confidence);
ids=ids(si);
BB=BB(:,si);
nd = length(confidence);
for d=1:nd
    % display progress
    if toc>1
        fprintf('%s: pr: compute: %d/%d\n',cls,d,nd);
        drawnow;
        tic;
    end
    
    % find ground truth image
    i=strmatch(ids{d},gtids,'exact');
    if isempty(i)
        error('unrecognized image "%s"',ids{d});
    elseif length(i)>1
        error('multiple image "%s"',ids{d});
    end

    % assign detection to ground truth object if any
    bb=BB(:,d);
    ovmax=-inf;
    for j=1:size(gt(i).BB,2)
        bbgt=gt(i).BB(:,j);
        bi=[max(bb(1),bbgt(1)) ; max(bb(2),bbgt(2)) ; min(bb(3),bbgt(3)) ; min(bb(4),bbgt(4))];
        iw=bi(3)-bi(1)+1;
        ih=bi(4)-bi(2)+1;
        if iw>0 & ih>0                
            % compute overlap as area of intersection / area of union
            ua=(bb(3)-bb(1)+1)*(bb(4)-bb(2)+1)+...
               (bbgt(3)-bbgt(1)+1)*(bbgt(4)-bbgt(2)+1)-...
               iw*ih;
            ov=iw*ih/ua;
            if ov>ovmax
                ovmax=ov;
                jmax=j;
            end
        end
    end
    % assign detection as true positive/don't care/false positive
    if ovmax>=VOCopts.minoverlap
        if ~gt(i).diff(jmax)
            if ~gt(i).det(jmax)
                tp(d)=1;            % true positive
		gt(i).det(jmax)=true;
            else
                fp(d)=1;            % false positive (multiple detection)
            end
        end
    else
        fp(d)=1;                    % false positive
    end
end

end

function [BB, confidence, imageIds] = getDetectionData(dets)
imageIds = cell(size(dets));
confidence = cell(size(dets));
BB = cell(size(dets));
for i = 1 : length(dets)
  if ~isempty(dets{i})
    imageIds{i} = i * ones(size(dets{i}, 1), 1);
    confidence{i} = dets{i}(:, 5);
    BB{i} = dets{i}(:, 1:4);
  end
end
imageIds = cell2mat(imageIds);
confidence = cell2mat(confidence);
BB = cell2mat(BB);
end
