/*  stack.C   */
/*  Copyright 1990 Mountain Math Software  */
/*  All Rights Reserved                    */
#include "stack.h"
#include "debug.h"

Stack::Stack(int InitialSize)
{
	ArraySize = InitialSize ;
	Values = new int[ArraySize];
	StackSize = 0 ;
	ForceTrueFlag=0;
}

int Stack::Pop()
{
	ForceTrueFlag = 0 ;
	if (!ReadSize()) {
		DbgError("Stack::Pop","null stack");
		return 0;
	}
	return Values[--StackSize];
}

void Stack::Push(int Value)
{
	ForceTrueFlag = 0 ;
	if (ReadSize() + 2 > ArraySize) {
		int NewSize = ArraySize + (ArraySize >> 2) + 4 ;
		int * NewValues = new int[NewSize];
		for (int i = 0 ; i < StackSize; i++) NewValues[i] = Values[i];
		delete Values ;
		Values = NewValues ;
		ArraySize = NewSize ;
	}
	Values[StackSize++] = Value ;
}

int Stack::Read(int IndexFromTop) const
{
	if (IndexFromTop < 0 || IndexFromTop >= StackSize) {
		DbgError("Stack::Read","bad index");
		return 0 ;
	}
	return Values[StackSize-1-IndexFromTop];
}

int Stack::IfTop() const
{
	if (ForceTrueFlag) return 1 ;
	if (!StackSize) return 1;
	return Values[StackSize-1];
}

void Stack::Negate()
{
	ForceTrueFlag = 0 ;
	if (!StackSize) {
		DbgError("Stack::Error","null stack");
		return ;
	}
	Values[StackSize-1] = ! Values[StackSize-1] ;
}
