/*
 * This is an example of how to use the STAILQ features of queue.h
 * from FreeBSD.
 *
 * Steve Shah (sshah@planetoid.org)
 * July 9, 2000
 *
 */


#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>

STAILQ_HEAD(entry_head, entry) queue;

struct entry {
    int y;
    int x;
    STAILQ_ENTRY(entry) entries;
} *data[5], *tmp, *tmp2;


int main ()
{
    int i;

    printf ("Initializing queue...\n");
    STAILQ_INIT(&queue);

    printf ("Creating entries to work with...\n");
    for (i=0;i < 5; i++) {
	data[i] = malloc(sizeof(struct entry));
	data[i]->x = i * 2;
	data[i]->y = i;
    }


    printf ("Inserting entries into the queue...\n");
    for (i=0;i < 5; i++) {
	STAILQ_INSERT_TAIL (&queue, data[i], entries);
    }

    /* Print them out in FIFO order */
    printf ("Printing out queue in FIFO order...\n");
    for (tmp = STAILQ_FIRST(&queue); 
	 tmp != NULL; 
	 tmp = STAILQ_NEXT(tmp, entries)) {
	printf ("\t%d. ", tmp->y);
	printf ("Value = %d\n", tmp->x);
    }
    

    /* Pop the head off the top */
    tmp = STAILQ_FIRST(&queue);
    STAILQ_REMOVE_HEAD(&queue, entries);
    printf ("Popped number %d having value %d off the head.\n",
	    tmp->y, tmp->x);
    free (tmp);


    /* Now go through and print all of them out, in natural order */
    printf ("Printing out queue in natural order...\n");
    STAILQ_FOREACH(tmp, &queue, entries) {
	printf ("\t%d. ", tmp->y);
	printf ("Value = %d\n", tmp->x);
    }

    printf ("Removing all elements from the queue...\n");
    /* Now torch the entire queue */
    tmp = STAILQ_FIRST(&queue);
    while (tmp != NULL) {
	tmp2 = STAILQ_NEXT(tmp, entries);
	free(tmp);
	tmp = tmp2;
    }

    printf ("Reinitializing queue...\n");
    STAILQ_INIT(&queue);

    printf ("The value that is returned when looking at the head is now: ");
    tmp = STAILQ_FIRST(&queue);
    printf ("%08x\n", (int)tmp);

    printf ("Recreating entries to work with...\n");
    for (i=0;i < 5; i++) {
	data[i] = malloc(sizeof(struct entry));
	data[i]->x = i * 2;
	data[i]->y = i;
    }

    printf ("Reinserting values into queue...\n");
    for (i=0;i < 5; i++) {
	STAILQ_INSERT_TAIL (&queue, data[i], entries);
    }

    printf ("Now popping one off at a time...\n");
    while ((tmp = STAILQ_FIRST(&queue)) != NULL) {
	printf ("\tPopped index %d with value %d\n", tmp->y, tmp->x);
	STAILQ_REMOVE_HEAD(&queue, entries);
	free (tmp);
    }
    printf ("\tNothing left to POP!\n");

    printf ("Done.\n");

    return 0;
}

	






