/*
 * Copyright 1990 by Baylor College of Medicine ALL RIGHTS RESERVED. 
 *
 * This program is subject to a license agreement between 
 * Baylor College of Medicine and MIT. Any use inconsistent with
 * said license and any use by persons other than the faculty, 
 * students and staff at MIT or any use on a computer not operated 
 * as part of the Athena Computing Environment (ACE) is expressly 
 * prohibited.
 */
/****************************************************************
 * File: callback.c
 * Date: 05/02/91
 *
 * Description:
 *   This file contains functions for managing callback lists.
 *
 * Revisions:
 ****************************************************************/
#include <stdio.h>
#include <malloc.h>
#include <string.h>

#include "VnsP.h"

/****************************************************************
 *              Private Functions
 ****************************************************************/

PRIVATE
VnsCallbackList *
find_callback_list(vns,name)
	VnsContext *vns;
	char *name;
{
	VnsCallbackList *list = vns->callbacks;

	while (list != NULL)
	{
		if (strcmp(list->name,name) == 0)
		{
			return list;
		}
		list = list->next;
	}

	return list;
}

/****************************************************************
 *              Public Functions
 ****************************************************************/

PUBLIC
void
VnsCreateCallbackList(vns,name)
	VnsContext *vns;
	char *name;
{
	VnsCallbackList *new, *list;

	/* check is list allready exists. if so, return */
	list = find_callback_list(vns,name);
	if (list != NULL) return;

	new = (VnsCallbackList *)malloc(sizeof(VnsCallbackList));

	new->name = strdup(name);
	new->list = NULL;            /* no callbacks yet */

	/* add new entry at the head of list */
	new->next = vns->callbacks;
	vns->callbacks = new;
}

PUBLIC
void
VnsAddCallback(vns,name,proc,data)
	VnsContext *vns;
	char *name;
	VnsCallbackProc proc;
	VnsPointer data;
{
	VnsCallbackList *cl;
	VnsCallbackRec *new;

	cl = find_callback_list(vns,name);
	if (cl == NULL)
	{
		fprintf(stderr,"Error: %s not found in callback list\n",name);
		return;
	}

	new = (VnsCallbackRec *)malloc(sizeof(VnsCallbackRec));

	new->proc = proc;
	new->data = data;

	/* add new callback to the head of the callback list */
	new->next = cl->list;
	cl->list = new;
}

PUBLIC
void
VnsCallCallbacks(vns,name,calldata)
	VnsContext *vns;
	char *name;
	VnsPointer calldata;
{
	VnsCallbackList *cl;
	VnsCallbackRec *list;

	cl = find_callback_list(vns,name);
	if (cl == NULL)
	{
		fprintf(stderr,"Error: %s not found in callback list\n",name);
		return;
	}

	/* call all of the callbacks registered for this list */
	list = cl->list;
	while (list != NULL)
	{
		list->proc(list->data,calldata);
		list = list->next;
	}
}
