/*	stack.c
 *
 * Licensed under the GPL. <www.gnu.org>
 *
 *  $Log$
 */

#include "stack.h"

STACK	*new_stack	( void ) {
	return calloc(1,sizeof(STACK));
}

void	 del_stack	(STACK *stack, void (*fn)(void*), unsigned int levels ) {
	unsigned int ix=0;
	for ( ; ix<stack->ix ; ix++ )
		if ( levels )
			del_stack(stack,fn,levels-1);
		else
			if ( fn )
				fn( stack->vector[ix] );
			else
				free(stack->vector[ix]);
	free(stack->vector);
	free(stack);
}

void	 stack_push	(STACK *stack, void *value) {
	stack->vector=realloc(stack->vector,sizeof(void*)*(stack->ix+1));
	stack->vector[stack->ix++]=value;
	stack->vector[stack->ix]=NULL;
}

void	*stack_pop	(STACK *stack) {
	void *value;
	if ( !stack->ix ) return NULL;
	value=stack->vector[--stack->ix];
	stack->vector[stack->ix]=NULL;
	/* stack->vector=realloc(stack->vector,sizeof(void*)*(stack->ix+1)); */
	return value;
}

void	*stack_peek	(STACK *stack, unsigned int index) {
	if ( index>=stack->ix ) return NULL;
	return stack->vector[stack->ix-index-1];
}

void	*stack_index(STACK *stack, unsigned int index) {
	if ( index>=stack->ix ) return NULL;
	return stack->vector[index];
}

int		 stack_depth(STACK *stack) {
	return stack->ix;		/* ix=0 for empty list */
}


