// evlist.cc: the EventList class.

#include <iostream.h>
#include "event.h"
#include "evlist.h"

void EventList::insert (Event *e) {
   // Create the item to go on the event list.
   ListItem *item = new ListItem();
   item->data = e;
   
   // Find the appropriate place for the item in the event list,
   // and put it there.
   const double time = e->getTime();
   if (firstEvent == 0 || time < firstEvent->data->getTime()) {
      item->next = firstEvent;
      firstEvent = item;
   }
   else {
      ListItem *behind = firstEvent;
      ListItem *ahead = firstEvent->next;
      while (ahead != 0 && ahead->data->getTime() <= time) {
         behind = ahead;
         ahead = ahead->next;
      }
      behind->next = item;
      item->next = ahead;
   }      
}

Event *EventList::takeNextEvent () {
   // precondition: firstEvent != null
   if (firstEvent == 0) {
      cout << "Error! ran out of events\n";
      return 0;
   }
   
   Event *eventToReturn = firstEvent->data;

   ListItem *restOfList = firstEvent->next;
   delete firstEvent;
   firstEvent = restOfList;

   return eventToReturn;    
}

