function [clClust, clSco, clImgs, clDists, clC1Ind] = ...
  mapPatchesToPairClustersForRes( ...
    vlImgs, vlRelLoc, vlC1Ind, selPair, clustMembership, dists, cluster2, ...
    cl1Results, cl1ImgIds, numClust)

pImgs = vlImgs(selPair);
pRelLoc = vlRelLoc(selPair);
pC1Ind = vlC1Ind(selPair);
imgVts = cell(size(cl1ImgIds));
c1Ind = cell(size(cl1ImgIds));
probs = exp(-dists);
startInd = 1;

for i = 1 : length(pRelLoc)
  numPats = size(pRelLoc{i}, 1);
  endInd = startInd + numPats - 1;
  imid = find(pImgs{i}(1) == cl1ImgIds);
  if isempty(imgVts{imid})
    imgVts{imid} = zeros(numPats, numClust);
    c1Ind{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);
  c1Ind{imid}(indx(toReplace)) = pC1Ind{i}(toReplace);
  startInd = endInd + 1;
end

% construct the clusters
clClust = cell(1, numClust);
clC1Ind = cell(1, numClust);
clSco = cell(1, numClust);
clImgs = cell(1, numClust);
clDists = cell(1, numClust);
pBar = createProgressBar();
for i = 1 : length(cl1ImgIds)
  pBar(i, length(cl1ImgIds));
  if isempty(imgVts{i})
    continue;
  end
  rs = cl1Results(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)];
    clC1Ind{vts(j)} = [clC1Ind{vts(j)} c1Ind{i}(j, vts(j))];
    clSco{vts(j)} = [clSco{vts(j)} d2.decision(j)];
    clImgs{vts(j)} = [clImgs{vts(j)} cl1ImgIds(i)];
    clDists{vts(j)} = [clDists{vts(j)} vals(j)];
  end
end
end
