/**
  * Fetch the items contained in the FetchProfile into the given set of Messages in as efficient
  * a manner as possible.
  *
  * @param messages
  * @param fp
  * @throws MessagingException
  */
 @Override
 public void fetch(
     List<Pop3Message> messages, FetchProfile fp, MessageRetrievalListener<Pop3Message> listener)
     throws MessagingException {
   if (messages == null || messages.isEmpty()) {
     return;
   }
   List<String> uids = new ArrayList<String>();
   for (Message message : messages) {
     uids.add(message.getUid());
   }
   try {
     indexUids(uids);
   } catch (IOException ioe) {
     throw new MessagingException("fetch", ioe);
   }
   try {
     if (fp.contains(FetchProfile.Item.ENVELOPE)) {
       /*
        * We pass the listener only if there are other things to do in the
        * FetchProfile. Since fetchEnvelop works in bulk and eveything else
        * works one at a time if we let fetchEnvelope send events the
        * event would get sent twice.
        */
       fetchEnvelope(messages, fp.size() == 1 ? listener : null);
     }
   } catch (IOException ioe) {
     throw new MessagingException("fetch", ioe);
   }
   for (int i = 0, count = messages.size(); i < count; i++) {
     Pop3Message pop3Message = messages.get(i);
     try {
       if (listener != null && !fp.contains(FetchProfile.Item.ENVELOPE)) {
         listener.messageStarted(pop3Message.getUid(), i, count);
       }
       if (fp.contains(FetchProfile.Item.BODY)) {
         fetchBody(pop3Message, -1);
       } else if (fp.contains(FetchProfile.Item.BODY_SANE)) {
         /*
          * To convert the suggested download size we take the size
          * divided by the maximum line size (76).
          */
         if (mStoreConfig.getMaximumAutoDownloadMessageSize() > 0) {
           fetchBody(pop3Message, (mStoreConfig.getMaximumAutoDownloadMessageSize() / 76));
         } else {
           fetchBody(pop3Message, -1);
         }
       } else if (fp.contains(FetchProfile.Item.STRUCTURE)) {
         /*
          * If the user is requesting STRUCTURE we are required to set the body
          * to null since we do not support the function.
          */
         pop3Message.setBody(null);
       }
       if (listener != null && !(fp.contains(FetchProfile.Item.ENVELOPE) && fp.size() == 1)) {
         listener.messageFinished(pop3Message, i, count);
       }
     } catch (IOException ioe) {
       throw new MessagingException("Unable to fetch message", ioe);
     }
   }
 }