/***********************************************************************
 * Equeue.m
 *
 * Interface file for a simple Equeue class. Actual logic works the
 * same way as in the C++ version, we simple switch from using method
 * calls to passing messages as needed.
 *
 * Written by Paul Bonamy - 9 August 2010
 ***********************************************************************/

#import "Equeue.h"


@implementation Equeue

-(id) init {
	if (self = [super init]) {
		head = nil;
		tail = nil;
	}
	return self;
}

/*
 * When deallocating, clean up your own mess, and then hand off to
 * your parent class so it can to its own cleanup.
 */
-(void)dealloc {
	[self empty];
	[super dealloc];
}


// Note that an Obj-C bool has values YES and NO rather than TRUE and FALSE
-(bool)enqueueValue:(int)value {
	EqueueNode * newbie = [[EqueueNode alloc] init];
	if(!newbie) {
		return NO;
	}
	[newbie setValue:value];
	[newbie setNext:head];
	head = newbie;
	
	if(!tail) {
		tail = newbie;
	}
	else {
		[[head next] setPrev:head];
	}
	
	return YES;
}

-(bool)dequeueInto:(int *)value {
	EqueueNode *temp;
	
	if(!tail) {
		return NO;
	}
	
	temp = tail;
	*value = [temp value];
	
	if(tail == head) {
		head = nil;
	}
	else {
		[[tail prev] setNext:nil];
	}
	
	tail = [tail prev];
	
	[temp release];
	
	return YES;
}

-(void) empty {
	EqueueNode *curr = head;
	head = nil;
	EqueueNode *next;
	
	while(curr) {
		next = [curr next];
		[curr release];
		curr = next;
	}
	
	tail = nil;
}

@end
