class CombinedMaster implements AbstractMaster<D> {

  protected void search(List<? extends AbstractSearchResult<D>> results, final SearchCallback<D, M> callback) {
    final Set<D> nonUnique = new HashSet<D>();
    List<ListIterator<D>> iterators = Lists.newArrayList();
    Set<Integer> nextIteratorsToUse = Sets.newHashSet();
    for (AbstractSearchResult<D> searchResult : results) {
      final List<D> documents = (searchResult != null) ? getNonUnique(nonUnique, searchResult.getDocuments(), callback) : Collections.<D>emptyList();
      iterators.add(documents.listIterator());
      nextIteratorsToUse.add(iterators.size() - 1);
    }
    int remainingIterators = iterators.size();
    
    List<IndexedElement> elements = Lists.newArrayList();
    
    do {
      //refill elements
      remainingIterators = refillElements(elements, callback, iterators, nextIteratorsToUse, remainingIterators);
      //check we're not in a silly state here
      assert remainingIterators >= 0;
      
      if (remainingIterators < 0) {
        s_logger.error("Illegal state - number of remaining iterators is negative.");
        //allow to continue in the interest of providing a result...
      }
      if (remainingIterators <= 0) {
        break;
      }
      
      //sort the elements for iteration.
      //reverse ordering used so we're not popping from the start of the array list.
      Collections.sort(elements, Ordering.natural().reverse());
      
      ListIterator<IndexedElement> it = elements.listIterator(elements.size());
      List<IndexedElement> elementResults = Lists.newLinkedList();
      while (true) {
        IndexedElement indexedElement = it.previous();
        it.remove();
        elementResults.add(indexedElement);
        int index = indexedElement._index;
        nextIteratorsToUse.add(index);
        if (!it.hasPrevious()) {
          break;
        }
        D document = indexedElement._element;
        IndexedElement peekedElement = elements.get(elements.size() - 1);
        if (callback.compare(document, peekedElement._element) != 0) {
          break;
        }
      };
      
      if (elementResults.size() == 1) {
        //this document was unique
        IndexedElement indexedElement = elementResults.get(0);
        //booleans are trivially true since list is a singleton
        callback.accept(indexedElement._element, _masterList.get(indexedElement._index), true, true);
      } else {
        //multiple documents across master, so only unique across masters if records picked from a single iterator
        boolean uniqueAcrossMasters = nextIteratorsToUse.size() == 1;
        for (IndexedElement element : elementResults) {
          boolean uniqueWithinMaster = !nonUnique.contains(element._element);
          callback.accept(element._element, _masterList.get(element._index), uniqueWithinMaster, uniqueAcrossMasters);
        }
      }
      
    } while (true);
  }

  protected  CombinedMaster(List<M> masterList);

}