/* Routines to support a simple FIFO character queue */

#include <memory.h>

#define True 1
#define False 0
#define QLEN 400

static char *qptr;		/* Pointer to queue storage area */
static char *fill;		/* Fill pointer */
static char *empty;		/* Empty pointer */


/* Allocate storage for the queue */
q_init() 
{
  if (!(qptr = (char *) malloc(QLEN)))
    error("Not enough memory");
  q_clear();
}


/* Clear the queue */
q_clear() 
{
  empty = qptr;
  fill = qptr;
}


/* Put a string into the queue.  Return false if queue is full.  */
int q_put(string, len)
     char *string;
     int len;
{
  register int j;

  /* See if the queue has enough room */
  if (len > 255) return False;
  j = empty - fill;
  if (j <= 0) j += QLEN;
  if (len + 1 >= j) return False;
  
  /* Don't wrap around end of queue array */
  if (fill - qptr + len + 1 >= QLEN) 
    {
      if (empty > fill) return False;
      *fill = 0;
      fill = qptr;
      return q_put(string, len);
    }
  
  /* Store the string in the queue */
  *fill++ = len;
  memcpy(fill, string, len);
  fill += len;
  return True;
}


/* Retrieve a string from queue.  Return length of string or zero if empty.  */
int q_get(string)
     char **string;
{
  int len;
  if (empty == fill) return 0;
  if (!*empty) empty = qptr;
  if (empty == fill) return 0;
  len = (int) *empty++;
  *string = empty;
  empty += len;
  if (empty >= qptr + QLEN) empty = qptr;
  return len;
}


/* Return true if queue is empty */
int q_empty()
{
  return (empty == fill);
}
