
#include <stdlib.h>
#include <string.h>

struct mnode
  {
    struct mnode *prev, *next;
    unsigned long timestamp;
    char *message;
  };

struct mnode mqueue;

void
init_message_q (void)
{
  mqueue.prev = mqueue.next = &mqueue;
}

void
put_message (char *message, unsigned long timestamp)
{
  struct mnode *newnode, *current;

  newnode = (struct mnode *) malloc (sizeof (struct mnode));
  newnode->message = strdup (message);
  newnode->timestamp = timestamp;

  current = mqueue.next;

  while ((current != &mqueue) && (newnode->timestamp > current->timestamp))
    current = current->next;

  newnode->prev = current->prev;
  newnode->next = current;
  (current->prev)->next = newnode;
  current->prev = newnode;
}

void
get_message (char *message, unsigned long timestamp)
{
  struct mnode *current = mqueue.next;

  if (current == &mqueue)
    message[0] = '\0';
  else
    {
      if (current->timestamp <= timestamp)
	{
	  strcpy (message, current->message);
	  free (current->message);
	  (current->prev)->next = current->next;
	  (current->next)->prev = current->prev;
	  free (current);
	}
      else
	message[0] = '\0';
    }
}
