// evlist.cc: the event-list class for the CSC 270 simulation example
// -- J. Clarke, March-June 1996

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

// Remember that events are not entities in the same sense as cars and
// pumps are, and the event queue does not have the same reality as the
// car queue. The event queue is a data structure without a real-world
// equivalent, while the car queue is real and you can see it. Events are
// not quite so imaginary, but they are certainly less "real" than cars.

eventListClass::eventListClass (void)
{
	firstEvent = NULL;
}

void eventListClass::insert (eventClass * event)
{
	eventListItem * e = new eventListItem;
	e -> data = event;

	const double T = event -> whatTime();
	if (firstEvent == NULL || T < firstEvent -> data -> whatTime()) {
		e -> next = firstEvent;
		firstEvent = e;
	}
	else {
		eventListItem * behind = firstEvent;
		eventListItem * ahead = firstEvent -> next;
		while (ahead != NULL && ahead -> data -> whatTime() <= T) {
			behind = ahead;
			ahead = ahead -> next;
		}
		behind -> next = e;
		e -> next = ahead;
	}
}

eventClass * eventListClass::getNext (void)
{
	// pre firstEvent not= NULL

	if (firstEvent == NULL) {
		cout << "Error! ran out of events\n";
		return NULL;
	}

	eventClass * eventToReturn = firstEvent -> data;

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

	return eventToReturn;
}
