function [P,R] = PrecisionRecallOfDetectionArrays(DA1, DA2);
%function [P,R] = PrecisionRecallOfDetectionArrays(DA1, DA2);
%
%DA2 is the true samples in the same form as DA1 (all strengths are 1 here)
%DA1 is an array where each column is a detection
%d = DA(:,1)
%d(1) is CAidx, d(2) is confidence, d(3) is x coord, d(4) is y coord, d(5) is radius of detection field

nTestSamples = size(DA1,2);
MatchVec = zeros(1,nTestSamples);
for i = 1:nTestSamples
   MatchVec(i) = DoesMatch(DA1(:,i),DA2);
end
m = min(DA1(2,:));
M = max(DA1(2,:));
n = 1;
for t = (m-(((M-m)/1000))):((M-m)/1000):M
  bMatchVec = MatchVec;
  bMatchVec(find(DA1(2,:) < t)) = 0;
  if(length(find(DA1(2,:) > t))) == 0;
    %P(n) = 0;
  else
    x = (length(unique(bMatchVec)) - 1) / size(DA2,2);
    if(x > 0);
      R(n) = x;
      P(n) = length(find((DA1(2,:) > t) & (MatchVec>0))) / length(find(DA1(2,:) > t));
      n = n+1;
    end
  end
end



function  b = DoesMatch(d,DA2);
%function  b = DoesMatch(d,DA2);
%a sample has a match in the list of true locations iff
% is has the same CAidx and
% the scales do not differ by more than a factor of 2 and
% the squares with 2x the radius edges centered over the point xy
% overlap by more than 50% of the area of the smaller square.

ThresholdArea = .5;

b = 0;
fSameCAIdx = find(DA2(1,:) == d(1));
if(isempty(fSameCAIdx))
  return;
end
DA2s = DA2(:,fSameCAIdx); %smaller set, check for within scale radius
SS = DA2s(5,:);
minS = d(5) / 2;
maxS = d(5) * 2;
fSameScale = find( ( (SS >= minS) & (SS <= maxS)));
if(isempty(fSameScale))
  return;
end
DA2ss = DA2s(:,fSameScale);
areaPercentOverlap = zeros(2,size(DA2ss,2));
bboxd = [d(3)-d(5),d(4)-d(5),d(3)+d(5),d(4)+d(5)];
a1 = 4 * d(5) * d(5);
for i = 1:size(DA2ss,2)
  d2 = DA2ss(:,i);
  a2 = 4 * d2(5) * d2(5);
  bboxd2 = [d2(3)-d2(5),d2(4)-d2(5),d2(3)+d2(5),d2(4)+d2(5)];
  isectbox = BBoxIntersect(bboxd, bboxd2);
  a3 = isectbox(3) * isectbox(4);
  areaPercentOverlap(1,i) = a3 / a1;
  areaPercentOverlap(1,i) = a3 / a2;
end
fOverlapEnough = find(max(areaPercentOverlap,[],1) > ThresholdArea);
if(isempty(fOverlapEnough))
  return;
end
b = fSameCAIdx(fSameScale(fOverlapEnough));
b = b(1);
  

