function [WPS WPNS WNPS WNPNS] = makeSelectionPair(allImages, ...
  primaryCat, secondCat, doFanning)
% From all the images picks images that contain the primary category and
% then splits this selection into two. One with the secondary category and
% one without the secondary category.
% In addition, if doFanning is true and if a primary or secondary object
% occurs multiple times in an image then creates a separate entry for each
% instance.
%
% Assuming there will be atleast one image with and without

wpsInd = 1;
wpnsInd = 1;
wnpsInd = 1;
wnpnsInd = 1;

for i = 1 : length(allImages)
    if ismember(primaryCat, {allImages(i).annotation.object.name})
      fanPrim = allImages(i);
      if doFanning
        fanPrim = fanOut(primaryCat, allImages(i));
      end
      for j = 1 : length(fanPrim)
        if ismember(secondCat, {fanPrim(j).annotation.object.name})
          fanSec = fanPrim(j);
          if doFanning
            fanSec = fanOut(secondCat, fanPrim(j));
          end
          for k = 1 : length(fanSec)
            WPS(wpsInd) = fanSec(k);
            wpsInd = wpsInd + 1;
          end
        else
          WPNS(wpnsInd) = fanPrim(j);
          wpnsInd = wpnsInd + 1;
        end
      end
    else
      if ismember(secondCat, {allImages(i).annotation.object.name})
        fanSec = allImages(i);
        if doFanning
          fanSec = fanOut(secondCat, allImages(i));
        end
        for k = 1 : length(fanSec)
          WNPS(wnpsInd) = fanSec(k);
          wnpsInd = wnpsInd + 1;
        end
      else
        WNPNS(wnpnsInd) = allImages(i);
        wnpnsInd = wnpnsInd + 1;
      end
    end
end

% WPNS = [];
% WNPS = [];
% WNPNS = [];
% return;
if isempty(WPS) || isempty(WPNS)
    error('Only one example found');
end

fprintf('WPS(%s, %s) %d\n', primaryCat, secondCat, length(WPS));
fprintf('WPnS(%s, %s) %d\n', primaryCat, secondCat, length(WPNS));
fprintf('WnPS(%s, %s) %d\n', primaryCat, secondCat, length(WNPS));
fprintf('WnPnS(%s, %s) %d\n', primaryCat, secondCat, length(WNPNS));
% testOneInstancePerEntry(primaryCat, WPS);
% testOneInstancePerEntry(primaryCat, WPNS);
% testOneInstancePerEntry(secondCat, WPS);
% testOneInstancePerEntry(secondCat, WNPS);
end

function all = fanOut(category, imgData)
% Given a single image data with multiple entries of an object, creates one
% copy for each object instance.
[memb, unused] = ismember({imgData.annotation.object.name}, {category});
inds = find(memb>0);
objs = imgData.annotation.object(inds);
imgData.annotation.object(inds) = [];
all(1:length(inds)) = imgData;
for i = 1 : length(all)
  all(i).annotation.object(end + 1) = objs(i);
end
end


function testOneInstancePerEntry(category, data)
for i = 1 : length(data)
  [mem, unused] = ismember({data(i).annotation.object.name}, {category});
  if sum(mem) > 1
    error('Entry %d has multiple entries', i);
  end
end
end
