/*queue.c - Routines for working with queues.
  Copyright (c) 1995 Matthew Belmonte

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  If you find this program useful, please send mail to Matthew Belmonte.
  <mkb4@Cornell.edu>.  If you base a publication on data processed by this
  program, please notify Matthew Belmonte and include the following citation
  in your publication:

	Matthew Belmonte, `A Software System for Analysis of
	Steady-State Evoked Potentials', Association for Computing
	Machinery SIGBIO Newsletter 17:1:9-14 (April 1997).
*/

#include <sys/types.h>
#include <malloc.h>
#include "fastshft.h" /*just for the definition of MAX_QLEN*/
#include "median.h" /*just for the definition of QVAL*/
#include "queue.h"

/*Allocate a queue large enough to hold 'size' items.*/
QUEUE *create_queue(size)
int size;
  {
  QUEUE *q;
  q = (QUEUE *)malloc(sizeof(QUEUE));
  q->ptr = -1;
  q->len = size;
  q->queue = (QVAL *)calloc(1+size, sizeof(QVAL));
  return(q);
  }

/*Deallocate the given queue.*/
void destroy_queue(q)
QUEUE *q;
  {
  free(q->queue);
  free(q);
  }

/*Insert a value into a queue.*/
void queue_insert(x, q)
QVAL x;
QUEUE *q;
  {
  q->ptr = (1+(q->ptr))%(q->len);
  q->queue[q->ptr] = x;
  }

/*Extract a value from a queue.*/
QVAL queue_extract(q)
QUEUE *q;
  {
  return(q->queue[(1+(q->ptr))%(q->len)]);
  }

/*Peek at the value that is 'n' places from the head of queue 'q'.*/
QVAL queue_peek(q, n)
QUEUE *q;
int n;
  {
  return(q->queue[(1+(q->len)-n+(q->ptr))%(q->len)]);
  }
