/* File "queue.c".
 * The queue will hold pointers to lists of ApptNodes
 */

#include <stdio.h>
#include "queue.h"
#include "bool.h"



/* InitQueue
 *----------------------------------------------------------------
 */
void
InitQueue(Queue *Q)
{
    Q->head = 0;
    Q->tail = MAX_LENGTH - 1;
    Q->size = 0;
}


/* enqueue
 *----------------------------------------------------------------
 */
boolean
enqueue(Queue *Q, elementType newElement)
{
    /* If the array is full, we can't add the new element.*/
    if(Q->size == MAX_LENGTH) {
	return FALSE;
    } else {
	/* Increase the tail position, but wrap around if necessary.*/
	Q->tail++;
	if(Q->tail > MAX_LENGTH - 1) 
	    Q->tail = 0;
	
	/* Insert the new element at the tail of the queue, and update
	   the queue's size. */
	Q->elements[Q->tail] = newElement;
	Q->size++;
	return TRUE;
    }
}


/* dequeue
 *----------------------------------------------------------------
 */
elementType
dequeue(Queue *Q)
{

    /* Extract the element at the head of the queue, to be returned.*/
    elementType res;
    res = Q->elements[Q->head];

    /* Increase the head position by 1 and wrap around if necessary.*/
    Q->head++;
    if(Q->head > MAX_LENGTH - 1)
	Q->head = 0;

    /* Update the queue's size and return the extracted element.*/
    Q->size--;
    return res;
    
}


/* isQueueEmpty
 *----------------------------------------------------------------
 */
boolean
isQueueEmpty(Queue *Q)
{
    return (Q->size == 0);
}


/* isQueueFull
 *----------------------------------------------------------------
 */
boolean
isQueueFull(Queue *Q)
{
    return (Q->size == MAX_LENGTH - 1);
}



/* printQueue
 *----------------------------------------------------------------
 * Print all elements of the queue, each on a separate line.
 *     This subprogram is specific to the element type, because
 * it must know how to print an element.  The current subprogram
 * only works for an integer element type.  It was used to test
 * the queue module;
 */

void
printQueue(Queue Q)
{
    /* Only if the queue is not empty do we have some printing to do. */
       
    if(Q.size != 0) {
	
        /* Start at the head of the queue.*/
	int i = Q.head;

	while(i != Q.tail) {    
	    /* Print the next element.*/
            printf("%d\n", Q.elements[i]);
	    
	    /* Advance to the next queue element, wrapping
	       around if necessary.*/
	    i++;
	    if( i >= MAX_LENGTH) 
                    i = 0;
	}
	/* Print the tail element. */
	printf("%d\n", Q.elements[Q.tail]);
    }
}
