/** This is the heart of the event manager, which processes the events for a robot. */
  public void processEvents() {
    // Remove old events
    eventQueue.clear(getTime() - MAX_EVENT_STACK);

    // Process custom events
    for (Condition customEvent : customEvents) {
      boolean conditionSatisfied = callUserCode(customEvent);
      if (conditionSatisfied) {
        addImpl(new CustomEvent(customEvent));
      }
    }

    // Sort the events based on the time and priority of the events
    eventQueue.sort();

    // Process event queue here
    Event currentEvent;
    while ((currentEvent = (eventQueue.size() > 0) ? eventQueue.get(0) : null) != null
        && currentEvent.getPriority() >= currentTopEventPriority) {

      if (currentEvent.getPriority() == currentTopEventPriority) {
        if (currentTopEventPriority > Integer.MIN_VALUE
            && isInterruptible(currentTopEventPriority)) {
          setInterruptible(currentTopEventPriority, false); // we're going to restart it, so reset.

          // We are already in an event handler, took action, and a new event was generated.
          // So we want to break out of the old handler to process it here.
          throw new EventInterruptedException(currentEvent.getPriority());
        }
        break;
      }

      int oldTopEventPriority = currentTopEventPriority;

      currentTopEventPriority = currentEvent.getPriority();
      currentTopEvent = currentEvent;

      eventQueue.remove(currentEvent);
      try {
        dispatch(currentEvent);

        setInterruptible(currentTopEventPriority, false);

      } catch (EventInterruptedException e) {
        currentTopEvent = null;
      } catch (RuntimeException e) {
        currentTopEvent = null;
        throw e;
      } catch (Error e) {
        currentTopEvent = null;
        throw e;
      } finally {
        currentTopEventPriority = oldTopEventPriority;
      }
    }
  }
 /**
  * Removes all events from the event queue.
  *
  * @param includingSystemEvents {@code true} if system events must be removed as well; {@code
  *     false} if system events should stay on the event queue.
  */
 public void clearAllEvents(boolean includingSystemEvents) {
   eventQueue.clear(includingSystemEvents);
   // customEvents.clear(); // Custom event should not be cleared here
 }