/*
	Copyright (C) 1994 Sean Luke

	COWSStack.m
	Version 1.0
	Sean Luke
	
*/




#import "COWSStack.h"
#import "COWSNode.h"
#import "COWSStateNode.h"
#import "COWSSymbolNode.h"
#import <stdio.h>


@implementation COWSStack

- init
	{
	id returnval= [super init];
	current=NULL;
	return returnval;
	}
	
- push:this
	{
	[this setNext:current];
	[this setPrev:NULL];
	if (current!=NULL) [current setPrev:this];
	current=this;
	return current;
	}
	
- pop
	{
	id temp=current;
	if (temp!=NULL) 
		{
		if ([temp next]!=NULL) [[temp next] setPrev:NULL];
		current=[current next];
		[temp setNext:NULL];
		}
	return temp;
	}
	
- top
	{
	return current;
	}
	
- _symbolHelper:pos		// private helper function for topSymbol
	{
	if (pos==NULL)	return NULL;
	if (![pos isKindOf:[COWSNode class]]) 
		{
		printf ("ERROR!  Something wrong with Stack!\n");
		return NULL;
		}
	if ([pos isMemberOf:[COWSStateNode class]]) return NULL;
	if ([pos isMemberOf:[COWSSymbolNode class]]) return pos;
	return [self _symbolHelper:[pos next]];
	}

- topSymbol
	{
	return [self _symbolHelper:current];
	}
	
- _stateHelper:pos		// private helper function for topState
	{
	if (pos==NULL)	return NULL;
	if (![pos isKindOf:[COWSNode class]]) 
		{
		printf ("ERROR!  Something wrong with Stack!\n");
		return NULL;
		}
	if ([pos isMemberOf:[COWSStateNode class]]) return pos;
	return [self _stateHelper:[pos next]];
	}

- topState
	{
	return [self _stateHelper:current];
	}
	
- clear
	{
	while (current!=NULL)
		{
		[[self pop] free];
		}
	return self;
	}	
	
- (int) number
	{
	int x=0;
	id temp=current;
	while (temp!=NULL)
		{
		x++;
		temp=[temp next];
		}
	return x;
	}


	
- free
	{
	[self clear];
	return [super free];
	}


- printContents
	{
	id temp=current;
	while (temp!=NULL)
		{
		[temp printContents];
		temp=[temp next];
		}
	return self;
	}
	
	
@end