/*
 * coda_circolare.c
 */
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    unsigned char max_len;
    unsigned char head, tail, size;
    int * data;
} t_queue;

void init_queue(t_queue * q, int max_len)
{
    q->max_len = max_len;
    q->head = q->tail = q->size = 0;
    q->data = (int *)malloc(max_len * sizeof(int));
}

int put(t_queue * q, int value)
{
    if (q->size == q->max_len)
        return 0;
    q->data[q->tail] = value;
    q->size++;
    q->tail = (q->tail + 1) % q->max_len;
    return 1;
}

int get(t_queue * q, int * value)
{
    if (q->size == 0)
        return 0;
    *value = q->data[q->head];
    q->size--;
    q->head = (q->head + 1) % q->max_len;
    return 1;
}

void delete_queue(t_queue * q)
{
    free(q->data);
    q->max_len = 0;
    q->head = q->tail = q->size = 0;
}


int main(int argc, char **argv)
{
    t_queue myqueue;
    int i, v;

    init_queue(&myqueue, 10);

    for (i = 0; i < 8;i++) {
        v = rand() % 30;
        if (put(&myqueue, v) == 1)
            printf("Put --> %d\n", v);
        else
            printf("Put --> queue full\n");
    }

    printf("-----------------------\n");

    for (i = 0; i < 4;i++) {
        if (get(&myqueue, &v) == 1)
            printf("Get --> %d\n", v);
    }

    printf("-----------------------\n");

    for (i = 0; i < 8;i++) {
        v = rand() % 30;
        if (put(&myqueue, v) == 1)
            printf("Put --> %d\n", v);
        else
            printf("Put --> queue full\n");
    }

    printf("-----------------------\n");

    while (get(&myqueue, &v) == 1) {
        printf("Get --> %d\n", v);
    }

    delete_queue(&myqueue);

    return 0;
}

