/* Standard C */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

/* Project */
#include "util.h"

typedef int T;

struct queue_item {
	struct queue_item *next;
	T                  data;
};

struct queue {
	struct queue_item *head, *tail;
};

void
queue_init(struct queue *queue)
{
	queue->head = NULL;
}

void
queue_put(struct queue *queue, T data)
{
	struct queue_item *new_item;

	if ( (new_item = malloc(sizeof(*new_item))) != NULL ) {
		struct queue_item *tmp = queue->tail;
		new_item->data         = data;
		new_item->next         = NULL;
		queue->tail            = new_item;
		if ( queue->head == NULL )
			queue->head = queue->tail;
		else
			tmp->next = queue->tail;
	}
	else
		ERROR("out of memory");
}

bool
queue_get(struct queue *queue, T *data)
{
	if ( queue->head != NULL ) {
		struct queue_item *next = queue->head->next;
		*data                   = queue->head->data;
		free(queue->head);
		queue->head = next;

		return true;
	}
	else
		return false;
}

bool
queue_empty(struct queue *queue)
{
	return queue->head == NULL;
}

void
queue_free(struct queue *queue)
{
	struct queue_item *item, *next;

	for ( item = queue->head; item; item = next ) {
		next = item->next;
		free(item);
	}
}

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

	queue_init(queue);

	for ( int i = 0; i != 10; ++i )
		queue_put(queue, i);

	while ( !queue_empty(queue) ) {
		int i;
		if ( queue_get(queue, &i) )
			printf("%d\n", i);
		else
			ERROR("this shouldn't happen!");
	}

	queue_free(queue);

	return EXIT_SUCCESS;
}
