#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include "queue.h"

struct node {
  int i;
  struct node *next;
};

struct queue {
  struct node *head, *last;
};

queue* queue_create(void) {
  queue *q = malloc(sizeof(queue));
  q->head = NULL;
  q->last = NULL;
  return q;
}

void queue_free(queue *q) {
  // You may assume that the queue is no longer in use, eg, no one is locking
  // the mutex or waiting on the condition variable.
  struct node *p = q->head, *r;
  while (p != NULL) {
    r = p->next;
    free(p);
    p = r;
  }
  free(q);
}

void queue_add(queue *q, int i) {
  struct node *new = malloc(sizeof(struct node));
  new->i = i;
  new->next = NULL;
  if (q->last == NULL) {
    if (q->head != NULL) {
      fprintf(stderr, "Inconsistency detected!\n");
      exit(1);
    }
    q->head = q->last = new;
  } else {
    q->last->next = new;
    q->last = new;
  }
}

int queue_take(queue *q) {
  while (q->head == NULL) {
  }
  struct node *p = q->head;
  q->head = q->head->next;
  if (q->head == NULL) {
    q->last = NULL;
  }
  int i = p->i;
  free(p);
  return i;
}
