#include "list.h"
#include "tmalloc.h"

void InitList(struct list *list)
{
    list->head = 0L;
    list->tail = 0L;
}

struct list *CreateList(void)
{
    struct list *list;

    list = tmalloc(sizeof(struct list), 21);
    InitList(list);
    return(list);
}

struct node *CreateNode(void *data)
{
    struct node *node;

    node = tmalloc(sizeof(struct node), 22);
    node->next = 0L;
    node->prev = 0L;
    node->data = data;
    return(node);
}

void DestroyNode(struct node *node)
{
    tfree(node);
}

void AddNode(struct list *list, struct node *node, struct node *where, int pa)
{
    if (where != 0L) {
	if (pa == PREPEND) {
	    node->next = where;
	    node->prev = where->prev;
	    if (node->prev) {
		node->prev->next = node;
	    } else {
		list->head = node;
	    }
	    where->prev = node;
	} else {
	    node->next = where->next;
	    where->next = node;
	    if (node->next) {
		node->next->prev = node;
	    } else {
		list->tail = node;
	    }
	    where->next = node;
	}
    } else {
	if (pa == PREPEND) {
	    node->next = list->head;
	    if (list->head) {
		list->head->prev = node;
	    } else {
		list->tail = node;
	    }
	    node->prev = 0L;
	    list->head = node;
	} else {
	    node->prev = list->tail;
	    if (list->tail) {
		list->tail->next = node;
	    } else {
		list->head = node;
	    }
	    node->next = 0L;
	    list->tail = node;
	}
    }
}

void DeleteNode(struct list *list, struct node *node)
{
    if (node->prev) {
	node->prev->next = node->next;
    } else {
	list->head = node->next;
	if (list->head) list->head->prev = 0;
    }
    if (node->next) {
	node->next->prev = node->prev;
    } else {
	list->tail = node->prev;
	if (list->tail) list->tail->next = 0;
    }
}
