/**
   * Handles events occurring during the flight from the event queue. Each event that has occurred
   * before or at the current simulation time is processed. Suitable events are also added to the
   * flight data.
   */
  private boolean handleEvents() throws SimulationException {
    boolean ret = true;
    FlightEvent event;

    log.trace("HandleEvents: current branch = " + currentStatus.getFlightData().getBranchName());
    log.trace("EventQueue = " + currentStatus.getEventQueue().toString());
    for (event = nextEvent(); event != null; event = nextEvent()) {

      // Ignore events for components that are no longer attached to the rocket
      if (event.getSource() != null
          && event.getSource().getParent() != null
          && !currentStatus.getConfiguration().isComponentActive(event.getSource())) {
        continue;
      }

      // Call simulation listeners, allow aborting event handling
      if (!SimulationListenerHelper.fireHandleFlightEvent(currentStatus, event)) {
        continue;
      }

      if (event.getType() == FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT) {
        RecoveryDevice device = (RecoveryDevice) event.getSource();
        if (!SimulationListenerHelper.fireRecoveryDeviceDeployment(currentStatus, device)) {
          continue;
        }
      }

      // Check for motor ignition events, add ignition events to queue
      for (MotorClusterState state : currentStatus.getActiveMotors()) {
        if (state.testForIgnition(event)) {
          final double simulationTime = currentStatus.getSimulationTime();
          MotorClusterState sourceState = (MotorClusterState) event.getData();
          double ignitionDelay = 0;
          if ((event.getType() == FlightEvent.Type.BURNOUT)
              || (event.getType() == FlightEvent.Type.EJECTION_CHARGE)) {
            ignitionDelay = sourceState.getEjectionDelay();
          }
          final double ignitionTime = currentStatus.getSimulationTime() + ignitionDelay;
          final RocketComponent mount = (RocketComponent) state.getMount();

          // TODO:  this event seems to get enqueue'd multiple times ...
          log.info("Queueing Ignition Event for: " + state.toDescription() + " @: " + ignitionTime);
          // log.info("     Because of "+event.getType().name()+" @"+event.getTime()+" from:
          // "+event.getSource().getName());

          addEvent(new FlightEvent(FlightEvent.Type.IGNITION, ignitionTime, mount, state));
        }
      }

      // Check for stage separation event
      for (AxialStage stage : currentStatus.getConfiguration().getActiveStages()) {
        int stageNo = stage.getStageNumber();
        if (stageNo == 0) continue;

        StageSeparationConfiguration separationConfig =
            stage.getSeparationConfigurations().get(this.fcid);
        if (separationConfig.getSeparationEvent().isSeparationEvent(event, stage)) {
          addEvent(
              new FlightEvent(
                  FlightEvent.Type.STAGE_SEPARATION,
                  event.getTime() + separationConfig.getSeparationDelay(),
                  stage));
        }
      }

      // Check for recovery device deployment, add events to queue
      for (RocketComponent c : currentStatus.getConfiguration().getActiveComponents()) {
        if (!(c instanceof RecoveryDevice)) continue;
        DeploymentConfiguration deployConfig =
            ((RecoveryDevice) c).getDeploymentConfigurations().get(this.fcid);
        if (deployConfig.isActivationEvent(event, c)) {
          // Delay event by at least 1ms to allow stage separation to occur first
          addEvent(
              new FlightEvent(
                  FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT,
                  event.getTime() + Math.max(0.001, deployConfig.getDeployDelay()),
                  c));
        }
      }

      // Handle event
      switch (event.getType()) {
        case LAUNCH:
          {
            currentStatus.getFlightData().addEvent(event);
            break;
          }

        case IGNITION:
          {
            MotorClusterState motorState = (MotorClusterState) event.getData();

            log.info(
                "  Igniting motor: "
                    + motorState.toDescription()
                    + " @"
                    + currentStatus.getSimulationTime());
            motorState.ignite(event.getTime());

            // Ignite the motor
            currentStatus.setMotorIgnited(true);
            currentStatus.getFlightData().addEvent(event);

            // ... ignite ...uhh, again?
            // TBH, I'm not sure what this call is for. It seems to be mostly a bunch of event
            // distribution.
            MotorConfigurationId motorId = motorState.getID();
            MotorMount mount = (MotorMount) event.getSource();
            if (!SimulationListenerHelper.fireMotorIgnition(
                currentStatus, motorId, mount, motorState)) {
              continue;
            }

            // and queue up the burnout for this motor, as well.
            double duration = motorState.getMotor().getBurnTimeEstimate();
            double burnout = currentStatus.getSimulationTime() + duration;
            addEvent(
                new FlightEvent(FlightEvent.Type.BURNOUT, burnout, event.getSource(), motorState));
            break;
          }

        case LIFTOFF:
          {
            // Mark lift-off as occurred
            currentStatus.setLiftoff(true);
            currentStatus.getFlightData().addEvent(event);
            break;
          }

        case LAUNCHROD:
          {
            // Mark launch rod as cleared
            currentStatus.setLaunchRodCleared(true);
            currentStatus.getFlightData().addEvent(event);
            break;
          }

        case BURNOUT:
          {
            // If motor burnout occurs without lift-off, abort
            if (!currentStatus.isLiftoff()) {
              throw new SimulationLaunchException(
                  trans.get("BasicEventSimulationEngine.error.earlyMotorBurnout"));
            }

            // Add ejection charge event
            MotorClusterState motorState = (MotorClusterState) event.getData();
            motorState.burnOut(event.getTime());

            AxialStage stage = motorState.getMount().getStage();
            log.debug(
                " adding EJECTION_CHARGE event for stage "
                    + stage.getStageNumber()
                    + ": "
                    + stage.getName());
            log.debug(
                "                         .... for motor "
                    + motorState.getMotor().getDesignation());

            double delay = motorState.getEjectionDelay();
            if (motorState.hasEjectionCharge()) {
              addEvent(
                  new FlightEvent(
                      FlightEvent.Type.EJECTION_CHARGE,
                      currentStatus.getSimulationTime() + delay,
                      stage,
                      event.getData()));
            }
            currentStatus.getFlightData().addEvent(event);
            break;
          }

        case EJECTION_CHARGE:
          {
            MotorClusterState motorState = (MotorClusterState) event.getData();
            motorState.expend(event.getTime());
            currentStatus.getFlightData().addEvent(event);
            break;
          }

        case STAGE_SEPARATION:
          {
            // Record the event.
            currentStatus.getFlightData().addEvent(event);

            RocketComponent boosterStage = event.getSource();
            final int stageNumber = boosterStage.getStageNumber();

            // Mark the status as having dropped the booster
            currentStatus.getConfiguration().clearStage(stageNumber);

            // Prepare the simulation branch
            SimulationStatus boosterStatus = new SimulationStatus(currentStatus);
            boosterStatus.setFlightData(
                new FlightDataBranch(boosterStage.getName(), FlightDataType.TYPE_TIME));
            // Mark the booster status as only having the booster.
            boosterStatus.getConfiguration().setOnlyStage(stageNumber);
            toSimulate.add(boosterStatus);
            log.info(
                String.format(
                    "==>> @ %g; from Branch: %s ---- Branching: %s ---- \n",
                    currentStatus.getSimulationTime(),
                    currentStatus.getFlightData().getBranchName(),
                    boosterStatus.getFlightData().getBranchName()));

            break;
          }

        case APOGEE:
          // Mark apogee as reached
          currentStatus.setApogeeReached(true);
          currentStatus.getFlightData().addEvent(event);
          // This apogee event might be the optimum if recovery has not already happened.
          if (currentStatus.getSimulationConditions().isCalculateExtras()
              && currentStatus.getDeployedRecoveryDevices().size() == 0) {
            currentStatus.getFlightData().setOptimumAltitude(currentStatus.getMaxAlt());
            currentStatus.getFlightData().setTimeToOptimumAltitude(currentStatus.getMaxAltTime());
          }
          break;

        case RECOVERY_DEVICE_DEPLOYMENT:
          RocketComponent c = event.getSource();
          int n = c.getStageNumber();
          // Ignore event if stage not active
          if (currentStatus.getConfiguration().isStageActive(n)) {
            // TODO: HIGH: Check stage activeness for other events as well?

            // Check whether any motor in the active stages is active anymore
            for (MotorClusterState state : currentStatus.getActiveMotors()) {
              if (state.isSpent()) {
                continue;
              }
              currentStatus.getWarnings().add(Warning.RECOVERY_DEPLOYMENT_WHILE_BURNING);
            }

            // Check for launch rod
            if (!currentStatus.isLaunchRodCleared()) {
              currentStatus.getWarnings().add(Warning.RECOVERY_LAUNCH_ROD);
            }

            // Check current velocity
            if (currentStatus.getRocketVelocity().length() > 20) {
              currentStatus
                  .getWarnings()
                  .add(new Warning.HighSpeedDeployment(currentStatus.getRocketVelocity().length()));
            }

            currentStatus.setLiftoff(true);
            currentStatus.getDeployedRecoveryDevices().add((RecoveryDevice) c);

            // If we haven't already reached apogee, then we need to compute the actual coast time
            // to determine the optimum altitude.
            if (currentStatus.getSimulationConditions().isCalculateExtras()
                && !currentStatus.isApogeeReached()) {
              FlightData coastStatus = computeCoastTime();

              currentStatus.getFlightData().setOptimumAltitude(coastStatus.getMaxAltitude());
              currentStatus.getFlightData().setTimeToOptimumAltitude(coastStatus.getTimeToApogee());
            }

            this.currentStepper = this.landingStepper;
            this.currentStatus = currentStepper.initialize(currentStatus);

            currentStatus.getFlightData().addEvent(event);
          }
          break;

        case GROUND_HIT:
          currentStatus.getFlightData().addEvent(event);
          break;

        case SIMULATION_END:
          ret = false;
          currentStatus.getFlightData().addEvent(event);
          break;

        case ALTITUDE:
          log.trace("BasicEventSimulationEngine:  Handling event " + event);
          break;

        case TUMBLE:
          this.currentStepper = this.tumbleStepper;
          this.currentStatus = currentStepper.initialize(currentStatus);
          currentStatus.getFlightData().addEvent(event);
          break;
      }
    }

    if (1200 < currentStatus.getSimulationTime()) {
      ret = false;
      log.error("Simulation hit max time (1200s): aborting.");
      currentStatus
          .getFlightData()
          .addEvent(
              new FlightEvent(FlightEvent.Type.SIMULATION_END, currentStatus.getSimulationTime()));
    }

    // If no motor has ignited, abort
    if (!currentStatus.isMotorIgnited()) {
      throw new MotorIgnitionException(trans.get("BasicEventSimulationEngine.error.noIgnition"));
    }

    return ret;
  }
  /**
   * Handles events occurring during the flight from the event queue. Each event that has occurred
   * before or at the current simulation time is processed. Suitable events are also added to the
   * flight data.
   */
  private boolean handleEvents() throws SimulationException {
    boolean ret = true;
    FlightEvent event;

    for (event = nextEvent(); event != null; event = nextEvent()) {

      // Ignore events for components that are no longer attached to the rocket
      if (event.getSource() != null
          && event.getSource().getParent() != null
          && !status.getConfiguration().isStageActive(event.getSource().getStageNumber())) {
        continue;
      }

      // Call simulation listeners, allow aborting event handling
      if (!SimulationListenerHelper.fireHandleFlightEvent(status, event)) {
        continue;
      }

      if (event.getType() != FlightEvent.Type.ALTITUDE) {
        log.verbose("BasicEventSimulationEngine:  Handling event " + event);
      }

      if (event.getType() == FlightEvent.Type.IGNITION) {
        MotorMount mount = (MotorMount) event.getSource();
        MotorId motorId = (MotorId) event.getData();
        MotorInstance instance = status.getMotorConfiguration().getMotorInstance(motorId);
        if (!SimulationListenerHelper.fireMotorIgnition(status, motorId, mount, instance)) {
          continue;
        }
      }

      if (event.getType() == FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT) {
        RecoveryDevice device = (RecoveryDevice) event.getSource();
        if (!SimulationListenerHelper.fireRecoveryDeviceDeployment(status, device)) {
          continue;
        }
      }

      // Check for motor ignition events, add ignition events to queue
      for (MotorId id : status.getMotorConfiguration().getMotorIDs()) {
        MotorMount mount = status.getMotorConfiguration().getMotorMount(id);
        RocketComponent component = (RocketComponent) mount;

        if (mount.getIgnitionEvent().isActivationEvent(event, component)) {
          addEvent(
              new FlightEvent(
                  FlightEvent.Type.IGNITION,
                  status.getSimulationTime() + mount.getIgnitionDelay(),
                  component,
                  id));
        }
      }

      // Check for stage separation event
      for (int stageNo : status.getConfiguration().getActiveStages()) {
        if (stageNo == 0) continue;

        Stage stage = (Stage) status.getConfiguration().getRocket().getChild(stageNo);
        if (stage.getSeparationEvent().isSeparationEvent(event, stage)) {
          addEvent(
              new FlightEvent(
                  FlightEvent.Type.STAGE_SEPARATION,
                  event.getTime() + stage.getSeparationDelay(),
                  stage));
        }
      }

      // Check for recovery device deployment, add events to queue
      Iterator<RocketComponent> rci = status.getConfiguration().iterator();
      while (rci.hasNext()) {
        RocketComponent c = rci.next();
        if (!(c instanceof RecoveryDevice)) continue;
        if (((RecoveryDevice) c).getDeployEvent().isActivationEvent(event, c)) {
          // Delay event by at least 1ms to allow stage separation to occur first
          addEvent(
              new FlightEvent(
                  FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT,
                  event.getTime() + Math.max(0.001, ((RecoveryDevice) c).getDeployDelay()),
                  c));
        }
      }

      // Handle event
      switch (event.getType()) {
        case LAUNCH:
          {
            status.getFlightData().addEvent(event);
            break;
          }

        case IGNITION:
          {
            // Ignite the motor
            MotorMount mount = (MotorMount) event.getSource();
            RocketComponent component = (RocketComponent) mount;
            MotorId motorId = (MotorId) event.getData();
            MotorInstanceConfiguration config = status.getMotorConfiguration();
            config.setMotorIgnitionTime(motorId, event.getTime());
            status.setMotorIgnited(true);
            status.getFlightData().addEvent(event);

            break;
          }

        case LIFTOFF:
          {
            // Mark lift-off as occurred
            status.setLiftoff(true);
            status.getFlightData().addEvent(event);
            break;
          }

        case LAUNCHROD:
          {
            // Mark launch rod as cleared
            status.setLaunchRodCleared(true);
            status.getFlightData().addEvent(event);
            break;
          }

        case BURNOUT:
          {
            // If motor burnout occurs without lift-off, abort
            if (!status.isLiftoff()) {
              throw new SimulationLaunchException("Motor burnout without liftoff.");
            }
            // Add ejection charge event
            String id = status.getConfiguration().getMotorConfigurationID();
            MotorMount mount = (MotorMount) event.getSource();
            double delay = mount.getMotorDelay(id);
            if (delay != Motor.PLUGGED) {
              addEvent(
                  new FlightEvent(
                      FlightEvent.Type.EJECTION_CHARGE,
                      status.getSimulationTime() + delay,
                      event.getSource(),
                      event.getData()));
            }
            status.getFlightData().addEvent(event);
            break;
          }

        case EJECTION_CHARGE:
          {
            status.getFlightData().addEvent(event);
            break;
          }

        case STAGE_SEPARATION:
          {
            // TODO: HIGH: Store lower stages to be simulated later
            RocketComponent stage = event.getSource();
            int n = stage.getStageNumber();
            status.getConfiguration().setToStage(n - 1);
            status.getFlightData().addEvent(event);
            break;
          }

        case APOGEE:
          // Mark apogee as reached
          status.setApogeeReached(true);
          status.getFlightData().addEvent(event);
          break;

        case RECOVERY_DEVICE_DEPLOYMENT:
          RocketComponent c = event.getSource();
          int n = c.getStageNumber();
          // Ignore event if stage not active
          if (status.getConfiguration().isStageActive(n)) {
            // TODO: HIGH: Check stage activeness for other events as well?

            // Check whether any motor in the active stages is active anymore
            for (MotorId motorId : status.getMotorConfiguration().getMotorIDs()) {
              int stage =
                  ((RocketComponent) status.getMotorConfiguration().getMotorMount(motorId))
                      .getStageNumber();
              if (!status.getConfiguration().isStageActive(stage)) continue;
              if (!status.getMotorConfiguration().getMotorInstance(motorId).isActive()) continue;
              status.getWarnings().add(Warning.RECOVERY_DEPLOYMENT_WHILE_BURNING);
            }

            // Check for launch rod
            if (!status.isLaunchRodCleared()) {
              status
                  .getWarnings()
                  .add(
                      Warning.fromString(
                          "Recovery device device deployed while on " + "the launch guide."));
            }

            // Check current velocity
            if (status.getRocketVelocity().length() > 20) {
              // TODO: LOW: Custom warning.
              status
                  .getWarnings()
                  .add(
                      Warning.fromString(
                          "Recovery device deployment at high "
                              + "speed ("
                              + UnitGroup.UNITS_VELOCITY.toStringUnit(
                                  status.getRocketVelocity().length())
                              + ")."));
            }

            status.setLiftoff(true);
            status.getDeployedRecoveryDevices().add((RecoveryDevice) c);

            this.currentStepper = this.landingStepper;
            this.status = currentStepper.initialize(status);

            status.getFlightData().addEvent(event);
          }
          break;

        case GROUND_HIT:
          status.getFlightData().addEvent(event);
          break;

        case SIMULATION_END:
          ret = false;
          status.getFlightData().addEvent(event);
          break;

        case ALTITUDE:
          break;
      }
    }

    // If no motor has ignited, abort
    if (!status.isMotorIgnited()) {
      throw new MotorIgnitionException("No motors ignited.");
    }

    return ret;
  }