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

#include "util.h"

typedef int T;

struct stack {
	T *array;
	size_t sz, p;
};

void
stack_init(struct stack *stack)
{
	stack->array = NULL;
	stack->sz = 0;
	stack->p = 0;
}

bool
stack_push(struct stack *stack, T data)
{
	if ( stack->array == NULL ) {
		if ( (stack->array = malloc(10 * sizeof(*stack->array))) != NULL ) {
			stack->sz = 10;
			stack->p = 0;
		}
		else {
			ERROR("out of memory");
			return false;
		}
	}

	if ( stack->p == stack->sz ) {
		size_t new_sz;
		T *new_array;

	   	if ( (new_array = realloc(stack->array, (new_sz = (stack->sz * 3 / 2)) * sizeof(*stack->array))) != NULL ) {
			stack->array = new_array;
			stack->sz = new_sz;
		}
		else {
			ERROR("out of memory");
			return false;
		}
	}

	stack->array[stack->p++] = data;
	return true;
}

bool
stack_pop(struct stack *stack, T *data)
{
	if ( stack->p != 0 ) {
		*data = stack->array[--stack->p];
		return true;
	}
	else
		return false;
}

bool
stack_empty(struct stack *stack)
{
	return stack->p == 0;
}

void
stack_free(struct stack *stack)
{
	free(stack->array);
}

int
main()
{
	struct stack stack[1];

	stack_init(stack);

	for ( int i = 0; i != 20; ++i )
		stack_push(stack, i);

	while ( !stack_empty(stack) ) {
		int i;

		if ( stack_pop(stack, &i) )
			printf("%d\n", i);
		else
			ERROR("this shouldn't happen!");
	}

	stack_free(stack);

	return EXIT_SUCCESS;
}

