function [clClust, clSco, clImgs, clDists] = mapPatchesToPairClusters( ...
  vlImgs, vlRelLoc, selPair, imgSet, clustMembership, dists, cluster2, ...
  detResDir, numClust)

pImgs = vlImgs(selPair);
pRelLoc = vlRelLoc(selPair);
imgVts = cell(size(imgSet));
probs = exp(-dists);
startInd = 1;

for i = 1 : length(pRelLoc)
  numPats = size(pRelLoc{i}, 1);
  endInd = startInd + numPats - 1;
  imid = find(pImgs{i}(1) == imgSet);
  if isempty(imgVts{imid})
    imgVts{imid} = zeros(numPats, numClust);
  end
  clMem = clustMembership(startInd:endInd);
  prb = probs(startInd : endInd);
  indx = sub2ind(size(imgVts{imid}), 1:numPats, clMem');
  curr = imgVts{imid}(indx)';
  toReplace = curr < prb;
  imgVts{imid}(indx(toReplace)) = prb(toReplace);
  startInd = endInd + 1;
end

% construct the clusters
res = PresenceDetectionResults(detResDir);
clClust = cell(1, numClust);
clSco = cell(1, numClust);
clImgs = cell(1, numClust);
clDists = cell(1, numClust);
pBar = createProgressBar();
for i = 1 : length(imgSet)
  pBar(i, length(imgSet));
  if isempty(imgVts{i})
    continue;
  end
  rs = res.getPosResult(imgSet(i));
  d2 = rs.firstLevel.detections(cluster2);
  [vals, vts] = max(imgVts{i}, [], 2);
  % Convert back to distance.
  vals = -log(vals);
  for j = 1 : length(vts)
    clClust{vts(j)} = [clClust{vts(j)} d2.metadata(j)];
    clSco{vts(j)} = [clSco{vts(j)} d2.decision(j)];
    clImgs{vts(j)} = [clImgs{vts(j)} imgSet(i)];
    clDists{vts(j)} = [clDists{vts(j)} vals(j)];
  end
end
end
