        #include "stackar.h"
        #include "fatal.h"
        #include <stdlib.h>

        #define EmptyTOS ( -1 )
        #define MinStackSize ( 1 )

        struct StackRecord
        {
            int Capacity;
            int TopOfStack;
            ElementTypeS *Array;
        };

        int
        IsEmpty( Stack S )
        {
            return S->TopOfStack == EmptyTOS;
        }

        int
        IsFull( Stack S )
        {
            return S->TopOfStack == S->Capacity - 1;
        }

        Stack
        CreateStack( int MaxElements )
        {
            Stack S;

/* 1*/      if( MaxElements < MinStackSize )
/* 2*/          Error( "Stack size is too small" );

/* 3*/      S = (Stack)malloc( sizeof( struct StackRecord ) );
/* 4*/      if( S == NULL )
/* 5*/          FatalError( "Out of space!!!" );

/* 6*/      S->Array = (ElementTypeS*)malloc( sizeof( ElementTypeS ) * MaxElements );
/* 7*/      if( S->Array == NULL )
/* 8*/          FatalError( "Out of space!!!" );
/* 9*/      S->Capacity = MaxElements;
/*10*/      MakeEmptyS( S );
	    
/*11*/      return S;
        }

        void
        MakeEmptyS( Stack S )
        {
            S->TopOfStack = EmptyTOS;
        }

        void
        DisposeStack( Stack S )
        {
            if( S != NULL )
            {
                free( S->Array );
                free( S );
            }
        }

        void
        Push( ElementTypeS X, Stack S )
        {
            if( IsFull( S ) )
                Error( "Full stack" );
            else
                S->Array[ ++S->TopOfStack ] = X;
        }


        ElementTypeS
        Top( Stack S )
        {
            if( !IsEmpty( S ) )
                return S->Array[ S->TopOfStack ];
            Error( "Empty stack" );
            ElementTypeS *empty = new ElementTypeS;
            empty->u = 0;
            empty->v = 0;
            return *empty;  /* Return value used to avoid warning */
        }

        void
        Pop( Stack S )
        {
            if( IsEmpty( S ) )
                Error( "Empty stack" );
            else
                S->TopOfStack--;
        }

        ElementTypeS
        TopAndPop( Stack S )
        {
            if( !IsEmpty( S ) )
                return S->Array[ S->TopOfStack-- ];
            Error( "Empty stack" );
            ElementTypeS *empty = new ElementTypeS;
            empty->u = 0;
            empty->v = 0;
            return *empty;  /* Return value used to avoid warning */
        }

	void showStack(Stack S) {
		int i;
		ElementTypeS e;
		for(i=0;i<=S->TopOfStack;i++) {
			e = S->Array[i];
			printf("%d %d\n",e.v,e.u);
		}
		printf("end showing stack\n");
	}
