/* Program to illustrate stacking numbers, using an array */

#include <stdio.h>


#define SIZE 10

/* function prototypes */


int getInteger(void);
void printHelpText(void);

/**********  MAIN FUNCTION **********/

int main (void)

{

  int stack[SIZE]; /* variable to hold a stack */
  int top = -1; /* represents top of stack; -1 signifies empty stack */
  

  int num; /* variable to hold an integer read in from user */
  char answer; /* variable to hold a character read in from user */
  char dummy; /* used for dummy read to get rid of newline */

  while (1) /* program ends via exit() called from getCommand(); */

    {
      printf("\n");
      printf("Enter command (h for help)> ");

      answer = getchar();
      dummy = getchar(); /* read the newline character */

      printf("\n");

      /* process that command */

      switch (answer)
	{
	case 'p':  /* pop a number from the stack */
	  if (top < 0)
	    printf("stack empty\n");
	  else
	    {
	      printf("popped %d \n",stack[top]);
	      top--;
	    }
	  break;
	  
	case 'a': /* add (push) a number onto the stack */
	  if (top == SIZE - 1)
	    printf("stack full\n");
	  else
	    {
	      num = getInteger();
	      top++;
	      stack[top]=num;
	    }
	  break;

	case 'l': /*  list the stack */
	  {
	    int i;
	    printf("Contents of stack: \n");
	    for (i = top; i>=0; i--)
	      {
		printf(" +--------+\n");
		printf(" |%8d|\n",stack[i]);
	      }
	    printf(" +========+\n");
	    printf("  (bottom) \n");
	    break;
	  }
	  
	case 't': /* peek at the top of the stack */
	  if (top<0)
	    printf("stack is empty\n");
	  else
	    printf("top is %d\n",stack[top]);
	  break;
	  
	case 's': /* ask the size of the stack */
	  printf("stack contains %d elements\n", top + 1);
	  break;

	case 'h':
	  printHelpText();
	  break;

	case 'q':
	  printf("Goodbye\n");
	  exit(0);
	  break;

	default:

	  printf("command <%c> not understood \n",answer);
	  printf("\n");

	} /* end switch */
      
    } /* end while */
 
} /* end main */


  /* getInteger()     prompt for an integer and then return it */




int getInteger(void)
{
  int result;
  char dummy;

  printf("Enter an integer>");
  scanf("%d", &result);
  dummy = getchar();

  return (result);

}


/* printHelpText()    print help message listing all program options */

void printHelpText(void)
{
  printf("a to add something to the stack\n");
  printf("p to pop something from the stack\n");
  printf("t to show what is on the top of the stack\n");
  printf("l to list entire contents of stack\n");
  printf("s to show how many elements are currently on the stack\n");
  printf("h to show this help message\n");
  printf("q to quit \n");
  printf("\n");
  return;
}

