#include <stdio.h>
#include <stdlib.h>

struct IStack {
      int maxSize;
      int index;
      int* start;
  } IStack;

struct IStack* createIntStack(int size) {
        struct IStack* p;
        p = (struct IStack*) malloc(sizeof(struct IStack));
        if (p == NULL) {printf("error in malloc createStack\n");  }
        p->maxSize = size;
        p->start = (int*) malloc(size*sizeof(int));
        if (p->start == NULL) {printf("error in malloc createIntStack\n");   }
        int i;  // initialize all to zero
        for(i=0; i< p->maxSize; i++) {
            p->start[i]=0;
        }
        p->index = p->maxSize-1;
        return p;

   }
void push(struct IStack* p, int value){
    if (p->index >=0 ){ p->start[p->index] = value; p->index--;
    }
    else {printf("Stack full on push\n"); }

   }

int pop(struct IStack* p){
   if (p->index == p->maxSize-1){printf("pop with empty stack\n"); return;}  // empty case
   int r = p->start[p->index+1];
    p->start[p->index+1] = 0;  // re initialize to zero when element popped
   p->index++;
   return r;

   }



   void  freeIntStack (struct IStack* p){
       free(p->start);
       free(p);
      }
void printIntStack(struct IStack* p){
      int index ;
      printf("printing stack %p\n", p);
      for(index=0; index< p->maxSize; index++)
      printf("%d, ",  p->start[index]);
      printf("end %d\n", p);
      }

int main(int argc, char *argv[])
{
    struct IStack * s1;
    s1 = createIntStack(3);
    printIntStack(s1);
    push(s1, 1);
    printIntStack(s1);
    push(s1, 10);
    printIntStack(s1);



     s1->start[33] = 17;  // FORBIDDEN
    push(s1, 17);  // YES


    int r = pop(s1);  // return 10
    printf("result of pop is %d\n" , r);
    printIntStack(s1);
    push(s1, 12);
        printIntStack(s1);

    r = pop(s1); printf("result of pop is %d\n" , r);  // return 12
    printIntStack(s1);

    r = pop(s1); printf("result of pop is %d\n" , r);   // return 1
    printIntStack(s1);
    r = pop(s1);   // return error
    freeIntStack(s1);




  system("PAUSE");
  return 0;
}

