nsresult sbRequestThreadQueue::PopBatch(Batch & aBatch)
{
  TRACE_FUNCTION("");
  NS_ENSURE_STATE(mLock);

  nsAutoLock lock(mLock);

  aBatch.clear();

  // If nothing was found then just return with an empty batch
  if (mRequestQueue.empty()) {
    LOG("No requests found\n");
    return NS_OK;
  }

  // If we're in the middle of a batch just return an empty batch
  if (mBatchDepth > 0) {
    LOG("Waiting on batch to complete\n");
    return NS_OK;
  }
  RequestQueue::iterator queueIter = mRequestQueue.begin();
  // request queue holds on to the object
  sbRequestItem * request = *queueIter;

  // If this isn't countable just return it by itself
  if (!request->GetIsCountable()) {
    LOG("Single non-batch request found\n");
    aBatch.push_back(request);
    mRequestQueue.erase(queueIter);
    // Release our reference to the request, aBatch is holding a reference to it
    NS_RELEASE(request);
    return NS_OK;
  }

  const PRUint32 requestBatchId = request->GetBatchId();

  // find the end of the batch and keep track of the matching batch entries
  const RequestQueue::const_iterator queueEnd = mRequestQueue.end();
  while (queueIter != queueEnd &&
         requestBatchId == (*queueIter)->GetBatchId()) {
    request = *queueIter++;
    aBatch.push_back(request);
    // Release our reference to the request, aBatch is holding a reference to it
    NS_RELEASE(request);
  }

  // Remove all the items we pushed onto the batch
  mRequestQueue.erase(mRequestQueue.begin(), queueIter);

  return NS_OK;
}