function writeOutDetectedPatches(data, outDir, canonicalSize, clustIds)
parfor i = 1 : length(data)
  dets = data{i}.detections;
  prefix = sprintf('%d_', i);
  for j = 1 : length(dets)
    clId = clustIds(j);
    if isempty(dets(j).metadata)
      continue;
    end
    clustDir = [outDir sprintf('/%d/', clId)];
    clusterFile = [outDir sprintf('/%d.jpg', clId)];
    if ~exist(clustDir, 'dir')
      mkdir(clustDir);
      fclose(fopen(clusterFile, 'w'));
    end
    writeOutPatches(dets(j).metadata, clustDir, canonicalSize, prefix);
  end
end
end
