// File:  ADTStack\ArrayStack.java

/**
 * Realization of a Stack ADT
 * 
 * @author Bary W Pollack
 * @version Jan. 2, 2001 - 19:00 PST
 */

// Represents an array implementation of a stack of ints
public class ArrayStack extends Stack {

    // Default constructor
    ArrayStack() { }

    // Creates a fresh array-implemented stack of a given length
    public void create(int length) {
        stack = new NItem[length];
        this.length = 0;
    }

    // True if the stack cannot contain any more Items
    public boolean isFull() throws StackException {
        checkNullStack();
        return (length >= stack.length);
    }

    // Returns the number of items in the stack
    public int size() throws StackException {
        checkNullStack();
        return length;
    }
    
    // Adds an Item at the top of the stack
    public void push(NItem nItem) throws StackException {
        checkNullStack();
        if (length >= stack.length)
            throw new StackException("stack full (" + length + ")");
        stack[length] = nItem;
        ++length;
///System.out.println("push(" + nItem + ")  new length=" + length); //FOO 
    }

    // Removes and returns the Item at the top of the stack
    public Item pop() throws StackException {
        checkNullStack();
        if (length <= 0)
            throw new StackException("attempt to pop an empty stack");
///System.out.println("pop.  length=" + length); //FOO
        --length;
        return stack[length];
    }

    // Empties the stack
    public void popAll() {
        create(stack.length); 
    }

    // Returns the Item at the top of the stack
    public Item peek() throws StackException {
        checkNullStack();
        return stack[length-1];
    }

    // Displays the stack on System.out
    public void display() throws StackException {
        checkNullStack();
        System.out.println(toString());
    }

    // Returns the String version of the data in the stack
    // Assumes that Item has a toString method
    public String toString() {
        String s = "";
        try {
            for (int i = length-1; i >= 0; i--) {
                if (i < length-1)
                    s += ", ";
                s += stack[i];
            }
        } catch (StackException e) {
            s = "<null>";
        }
        return s;
    }

    // Checks to ensure that 'stack' is not null
    protected void checkNullStack() throws StackException {
        if (stack == null)
            throw new StackException("stack is <null>");
    }

    protected NItem[] stack;
    protected int length;
}
