function [relLoc, c1Sc, imgs, relInd] = ...
  computeCanonicalRelativeLocationsPair(cl1, cl2s, imgSet, c1NmsThresh, ...
  detResDir1, detResDir2)
% Computes the location of cl2s relative to cl1. This is for the
% computation of the relative locations in teh next iterations.

results1 = PresenceDetectionResults(detResDir1);
results2 = PresenceDetectionResults(detResDir2);
relLoc = cell(size(cl2s));
c1Sc = cell(size(cl2s));
imgs = cell(size(cl2s));
relInd = cell(size(cl2s));
for i = 1 : length(cl2s)
  [relLoc{i} c1Sc{i} imgs{i} relInd{i}] = computePairRelation(cl1, ...
    cl2s(i), results1, results2, imgSet, c1NmsThresh);
end
end

function [relLoc, c1Sc, imgs, relInd] = computePairRelation(cl1, cl2, ...
  results1, results2, imgSet, c1NmsThresh)
pairRelation = cell(2 * length(imgSet), 1);
pairC1Scores = cell(2 * length(imgSet), 1);
pairImgs = cell(2 * length(imgSet), 1);
pairRelInds = cell(2 * length(imgSet), 1);
pairInd = 0;
pBar = createProgressBar();
for i = 1 : length(imgSet)
  pBar(i, length(imgSet));
  rs1 = results1.getPosResult(imgSet(i));
  d1 = rs1.firstLevel.detections(cl1);
  d1 = doNmsForCl1(d1, c1NmsThresh);
  rs2 = results2.getPosResult(imgSet(i));
  d2 = rs2.firstLevel.detections(cl2);
  if ~isempty(d1.metadata) && ~isempty(d2.metadata)
    b1 = getBoxesForPedro(d1.metadata);
    b2 = getBoxesForPedro(d2.metadata);
    sc1 = b1(:, 3) - b1(:, 1);
    sc2 = b2(:, 3) - b2(:, 1);
    for j = 1 : size(b1, 1)
      b1t = repmat(b1(j, :), size(b2, 1), 1);
      sc1t = ones(size(b2, 1), 1) * sc1(j);
      [b1trfor, b2trfor] = transformWithBox1AsCano(b1t, b2);
      metrfor = [mean(b2trfor(:, [1 3]), 2) mean(b2trfor(:, [2 4]), 2)];
      fe = [metrfor sc2 ./ sc1t];
      pairInd = pairInd + 1;
      pairC1Scores{pairInd} = ones(size(fe, 1), 1) * d1.decision(j);
      pairImgs{pairInd} = ones(size(fe, 1), 1) * imgSet(i);
      pairRelation{pairInd} = fe;
%       ones(size(b1, 1), 1).* j
%       (1:size(b2, 1))'
      pairRelInds{pairInd} = [ones(size(b2, 1), 1).* j (1:size(b2, 1))'];
    end
%     keyboard;
  end
end

relLoc = pairRelation(1 : pairInd);
c1Sc = pairC1Scores(1 : pairInd);
imgs = pairImgs(1 : pairInd);
relInd = pairRelInds(1 : pairInd);
end


function nmsD = doNmsForCl1(d, thresh)
nmsD = d;
picks = doNmsForImg(d.metadata, d.decision, thresh);
nmsD.metadata = d.metadata(picks);
nmsD.decision = d.decision(picks);
end
