function writeTopNDetsPerCluster(allPos, allNeg, selectedClusters, ...
  outDir, orderWeights, canonicalSize, overlap)
% orderWeights are typically mmht weights.

if exist('orderWeights', 'var')
  [unused, orderInds] = sort(orderWeights, 'descend');
else
  orderInds = 1 : length(selectedClusters);
end

all = [allPos allNeg];
maxToShow = 20;
for i = 1 : length(orderInds)
  [scores, imgIds, meta] = getAllClusterScores(all, orderInds(i), overlap);
  [vals, inds] = sort(scores, 'descend');
  toSelect = min(length(scores), maxToShow);
  selected = inds(1:toSelect);
  selectedMeta = meta(selected);
  
  namePrefix = sprintf('%d_%d_', i, selectedClusters(orderInds(i)));
  writeOutPatches(selectedMeta, outDir, canonicalSize, namePrefix, ...
    scores(selected))
end
end

function [scores, imgIds, meta] = getAllClusterScores(detRes, clusti, ...
  overlap)
scores = [];
imgIds = [];
meta = [];
for j = 1 : length(detRes)
  thisScores = detRes{j}.firstLevel.detections(clusti).decision;
  if isempty(thisScores)
    continue;
  end
  imgMeta = detRes{j}.firstLevel.detections(clusti).metadata;
  % Do NMS for image.
  picks = doNmsForImg(imgMeta, thisScores, overlap);
  
  thisScores = thisScores(picks);
  scores = [scores thisScores];
  imgIds = [imgIds ones(1, length(thisScores)) * j];
  meta = [meta imgMeta(picks)];
end
end
