/*
This is a modified version of the avl package from xrn,
Its been modified to be a class, so it can be used from ATK
*/

#ifndef lint
static char XRNrcsid[] = "$Header: /afs/net.mit.edu/dapps/project/andyplay/wdc/src/newms/RCS/avlkeyset.c,v 1.2 92/09/03 18:47:07 wdc Exp $";
#endif

/*
 * avl package
 *
 * Copyright (c) 1988, 1989, The Regents of the University of California.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted, provided
 * that the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of the University of California not
 * be used in advertising or publicity pertaining to distribution of 
 * the software without specific, written prior permission.  The University
 * of California makes no representations about the suitability of this
 * software for any purpose.  It is provided "as is" without express or
 * implied warranty.
 *
 * THE UNIVERSITY OF CALIFORNIA DISCLAIMS ALL WARRANTIES WITH REGARD TO 
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS, IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE FOR
 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <andrewos.h>
#include <class.h>

#include <newms.h>
#include <extlist.ih>
#include <avlkeyset.eh>

struct avlnode {
    void *key;
    void *value;
    int height;
    struct avlnode *left;
    struct avlnode *right;
    struct avlnode *parent;
};

#define ALLOC(type, number)  (type *) malloc((unsigned) sizeof(type) * number)
#define NIL(type)            (type *) 0
#define FREE(item)           (void) free(item)

#define MAX(a,b)             ((a) > (b) ? (a) : (b))

/* LINTLIBRARY */


/*#define MAX(a,b) ((a) > (b) ? (a) : (b))*/
#define HEIGHT(node) (node == NIL(struct avlnode) ? -1 : (node)->height)
#define BALANCE(node) (HEIGHT((node)->right) - HEIGHT((node)->left))

#define compute_height(node) {				\
    int x=HEIGHT(node->left), y=HEIGHT(node->right);	\
    (node)->height = MAX(x,y) + 1;			\
}

#define COMPARE(key, nodekey, compare)	 		\
    ((compare == NULL) ? 				\
	(int) key - (int) nodekey : 			\
	(*compare)(key, nodekey))


static struct avlnode *
new_node(key, value)
void *key;
void *value;
{
    register struct avlnode *new;

    new = ALLOC(struct avlnode, 1);
    new->key = key;
    new->value = value;
    new->height = 0;
    new->left = new->right = NIL(struct avlnode);
    new->parent = NIL(struct avlnode);
    return new;
}


static void rotate_left(node_p)
register struct avlnode **node_p;
{
    register struct avlnode *old_root = *node_p, *new_root, *new_right;
    struct avlnode *parent = old_root->parent;

    if (BALANCE(old_root->right) >= 0) {
	*node_p = new_root = old_root->right;
	old_root->right = new_root->left;
	if (old_root->right != NULL) {
	    old_root->right->parent = old_root;
	}
	new_root->left = old_root;
	if (new_root->left != NULL) {
	    new_root->left->parent = new_root;
	}
    } else {
	new_right = old_root->right;
	*node_p = new_root = new_right->left;
	old_root->right = new_root->left;
	if (old_root->right != NULL) {
	    old_root->right->parent = old_root;
	}
	new_right->left = new_root->right;
	if (new_right->left != NULL) {
	    new_right->left->parent = new_right;
	}
	new_root->right = new_right;
	if (new_root->right != NULL) {
	    new_root->right->parent = new_root;
	}
	new_root->left = old_root;
	if (new_root->left != NULL) {
	    new_root->left->parent = new_root;
	}
	compute_height(new_right);
    }
    new_root->parent = old_root->parent;
    compute_height(old_root);
    compute_height(new_root);
}


static void rotate_right(node_p)
struct avlnode **node_p;
{
    register struct avlnode *old_root = *node_p, *new_root, *new_left;
    struct avlnode *parent = old_root->parent;

    if (BALANCE(old_root->left) <= 0) {
	*node_p = new_root = old_root->left;

	old_root->left = new_root->right;
	if (old_root->left != NULL) {
	    old_root->left->parent = old_root;
	}
	new_root->right = old_root;
	if (new_root->right != NULL) {
	    new_root->right->parent = new_root;
	}
    } else {
	new_left = old_root->left;
	*node_p = new_root = new_left->right;

	old_root->left = new_root->right;
	if (old_root->left != NULL) {
	    old_root->left->parent = old_root;
	}
	new_left->right = new_root->left;
	if (new_left->right != NULL) {
	    new_left->right->parent = new_left;
	}
	new_root->left = new_left;
	if (new_root->left != NULL) {
	    new_root->left->parent = new_root;
	}
	new_root->right = old_root;
	if (new_root->right != NULL) {
	    new_root->right->parent = new_root;
	}
	compute_height(new_left);
    }
    new_root->parent = old_root->parent;
    compute_height(old_root);
    compute_height(new_root);
}

static void do_rebalance(tree, node)
register struct avlkeyset *tree;
struct avlnode *node;
{
    register struct avlnode **node_p, *node;
    register int hl, hr;
    int height;
    struct avlnode *parent;

    /* work our way back up, re-balancing the tree */
    while (node != NULL) {
	parent = node->parent;
	if (parent == NULL) {
	    node_p = &tree->root;
	}
	else if (node == parent->left) {
	    node_p = &parent->left;
	}
	else {
	    node_p = &parent->right;
	}
	    
	hl = HEIGHT(node->left);		/* watch for NIL */
	hr = HEIGHT(node->right);		/* watch for NIL */
	if ((hr - hl) < -1) {
	    rotate_right(node_p);
	} else if ((hr - hl) > 1) {
	    rotate_left(node_p);
	} else {
	    height = MAX(hl, hr) + 1;
	    if (height == node->height) break;
	    node->height = height;
	}
    }
}

static struct avlnode *find_rightmost(tree, node_p, parent)
struct avlkeyset *tree;
register struct avlnode **node_p;
struct avlnode *parent;
{
    register struct avlnode *node;

    node = *node_p;
    while (node->right != NIL(struct avlnode)) {
	parent = node;
	node_p = &node->right;
	node = *node_p;
    }
    *node_p = node->left;
    if (node->left != NULL) {
	node->left->parent = parent;
    }

    do_rebalance(tree, parent);
    return node;
}

static struct avlnode *avl_walk(node, stopfunc, rock)
struct avlnode *node;
boolerror (*stopfunc)();
void *rock;
{
    if (node != NIL(struct avlnode)) {
	avl_walk(node->left, stopfunc, rock);
	if ((*stopfunc)(node->key, node->value, rock)) {
	    return node;
	}
	avl_walk(node->right, stopfunc, rock);
    }
    return NULL;
}

static void
free_entry(node, key_free, value_free)
struct avlnode *node;
void (*key_free)();
void (*value_free)();
{
    if (node != NIL(struct avlnode)) {
	free_entry(node->left, key_free, value_free);
	free_entry(node->right, key_free, value_free);
	if (key_free != 0) {
	    (*key_free)(node->key);
	}
	if (value_free != 0) {
	    (*value_free)(node->value);
	}
	FREE(node);
    }
}
    

boolean avlkeyset__InitializeObject(classid, self)
struct classheader *classid;
struct avlkeyset *self;
{
    self->root = NIL(struct avlnode);
    return TRUE;
}

void avlkeyset__FinalizeObject(classid, self)
struct classheader *classid;
struct avlkeyset *self;
{
    free_entry(self->root, avlkeyset_GetKeyFreeFunction(self), avlkeyset_GetValueFreeFunction(self));
}

boolean avlkeyset__Lookup(self, key, value)
struct avlkeyset *self;
register void *key;
void **value;
{
    register struct avlnode *node;
    register int (*compare)() = avlkeyset_GetCompareFunction(self);
    int diff;

    node = self->root;
    while (node != NIL(struct avlnode)) {
	diff = COMPARE(key, node->key, compare);
	if (diff == 0) {
	    /* got a match, give the user a 'value' only if non-null */
	    if (value != NULL) {
		*value = node->value;
	    }
	    return TRUE;
	}
	node = (diff < 0) ? node->left : node->right;
    }
    return FALSE;
}

static struct avlnode **GetPointerToNode(self, key, parent)
struct avlkeyset *self;
void *key;
struct avlnode **parent;
{
    register int (*compare)() = avlkeyset_GetCompareFunction(self);
    struct avlnode **node_p = &self->root;
    struct avlnode *node;
    int diff;

    node_p = &self->root;

    /* walk down the tree (saving the path); stop at insertion point */

    while ((node = *node_p) != NIL(struct avlnode)) {
	diff = COMPARE(key, node->key, compare);
	if (diff == 0)  {
	    break;
	}
	*parent = node;
	node_p = (diff < 0) ? &node->left : &node->right;
    }
    return node_p;
}

void avlkeyset__Insert(self, key, value)
struct avlkeyset *self;
void *key;
void *value;
{
    register struct avlnode **node_p, *node;
    struct avlnode *parent = NIL(struct avlnode);

    node_p = GetPointerToNode(self, key, &parent);

    if ((node = *node_p) != NULL) {
	if (avlkeyset_GetValueFreeFunction(self)) {
	    (*avlkeyset_GetValueFreeFunction(self))(node->value);
	}
	node->value = value;
    }
    else {
	/* insert the item and re-balance the tree */
	if (avlkeyset_GetKeyCopyFunction(self) != NULL) {
	    key = (*avlkeyset_GetKeyCopyFunction(self))(key);
	}
	if (avlkeyset_GetValueCopyFunction(self) != NULL) {
	    value = (*avlkeyset_GetValueCopyFunction(self))(value);
	}
	*node_p = new_node(key, value);
	(*node_p)->parent = parent;
	do_rebalance(self, parent);
	avlkeyset_IncrementNumberOfElements(self);
    }
}

static void RemoveNode(self, node_p, parent, key_p, value_p)
struct avlkeyset *self;
struct avlnode **node_p;
struct avlnode *parent;
void **key_p;
void **value_p;
{
    struct avlnode *node = *node_p;

    /* prepare to delete node and replace it with rightmost of left tree */

    if (avlkeyset_GetKeyFreeFunction(self) != NULL) {
	(*avlkeyset_GetKeyFreeFunction(self))(node->key);
	node->key = NULL;
    }
    if (key_p != NULL) {
	*key_p = node->key;
    }

    if (avlkeyset_GetValueFreeFunction(self) != NULL) {
	(*avlkeyset_GetValueFreeFunction(self))(node->value);
	node->value = NULL;
    }
    if (value_p != NULL) {
	*value_p = node->value;
    }

    if (node->left == NIL(struct avlnode)) {
	*node_p = node->right;
	if (node->right != NULL) {
	    node->right->parent = parent;
	}
    } else {
	struct avlnode *rightmost = find_rightmost(self, &node->left, node);

	rightmost->left = node->left;
	if (rightmost->left != NULL) {
	    rightmost->left->parent = rightmost;
	}
	rightmost->right = node->right;
	if (rightmost->right != NULL) {
	    rightmost->right->parent = rightmost;
	}
	rightmost->height = -2; 	/* mark bogus height for do_rebal */
	parent = rightmost;
    }
    FREE(node);

    /* work our way back up, re-balancing the tree */
    do_rebalance(self, parent);
    avlkeyset_DecrementNumberOfElements(self);
}
    

boolean avlkeyset__Remove(self, key_p, value_p)
struct avlkeyset *self;
void **key_p;
void **value_p;
{
    register struct avlnode **node_p;
    char *key = (char *)*key_p;
    struct avlnode *parent = NIL(struct avlnode);
    
    node_p = GetPointerToNode(self, *key, &parent);

    if (*node_p != NULL) {
	RemoveNode(self, node_p, parent, key_p, value_p);
    }

    return TRUE;
}

static void avl_record_gen(node, include, rock, nodelist)
struct avlnode *node;
boolean (*include)();
void *rock;
struct extendedlist *nodelist;
{
    if (node != NIL(struct avlnode)) {
	avl_record_gen(node->left, include, rock, nodelist);
	if (include == NULL || (*include)(node->key, node->value, rock)) {
	    extendedlist_AddElement(nodelist, node->value);
	}
	avl_record_gen(node->right, include, rock, nodelist);
    }
}


struct extendedlist *avlkeyset__GetList(self, include, rock)
struct avlkeyset *self;
boolean (*include)();
void *rock;
{
    struct extendedlist *nodelist = extendedlist_New();

    avl_record_gen(self->root, include, rock, nodelist);

    return nodelist;
}

void *avlkeyset__ForEach(tree, stopfunc, rock)
struct avlkeyset *tree;
boolerror (*stopfunc)();
void *rock;
{
    struct avlnode *node;

    node = avl_walk(tree->root, stopfunc, rock);

    if (node != NULL) {
	return node->key;
    }
    else {
	return NULL;
    }
}

static struct avlnode *First(node)
struct avlnode *node;
{
    while (node->left != NULL) {
	node = node->left;
    }
    return node;
}

static struct avlnode *Next(node)
struct avlnode *node;
{
    if (node->right != NULL) {
	return First(node->right);
    }
    else {
	return node->parent;
    }
}

void avlkeyset__Prune(tree, func, rock)
struct avlkeyset *tree;
boolean (*func)();
void *rock;
{
    struct avlnode *p;
    struct avlnode *nextp;
    struct avlnode **node_p;
    struct avlnode *parent;

    if (tree->root == NULL) {
	return;
    }

    for (p = First(tree->root); p != NULL; p = nextp) {
	nextp = Next(p);
	if ((*func)(p, rock)) {
	    /* Delete the node Here */

	    if ((parent = p->parent) == NULL) {
		node_p = &tree->root;
	    }
	    else if (p == parent->left) {
		node_p = &parent->left;
	    }
	    else {
		node_p = &parent->right;
	    }
	    RemoveNode(tree, node_p, p->parent, NULL, NULL);
	}
    }
}
	
void avlkeyset__Clear(self)
struct avlkeyset *self;
{
    free_entry(self->root, avlkeyset_GetKeyFreeFunction(self), avlkeyset_GetValueFreeFunction(self));
    self->root = NULL;
    super_Clear(self);
}

static int do_check_tree(node, compare, error)
struct avlnode *node;
int (*compare)();
int *error;
{
    int l_height, r_height, comp_height, bal;
    
    if (node == NIL(struct avlnode)) {
	return -1;
    }

    r_height = do_check_tree(node->right, compare, error);
    l_height = do_check_tree(node->left, compare, error);

    comp_height = MAX(l_height, r_height) + 1;
    bal = r_height - l_height;
    
    if (comp_height != node->height) {
	(void) printf("Bad height for 0x%08x: computed=%d stored=%d\n",
	    node, comp_height, node->height);
	++*error;
    }

    if (bal > 1 || bal < -1) {
	(void) printf("Out of balance at node 0x%08x, balance = %d\n", 
	    node, bal);
	++*error;
    }

    if (node->left != NIL(struct avlnode) && 
		    (*compare)(node->left->key, node->key) > 0) {
	(void) printf("Bad ordering between 0x%08x and 0x%08x", 
	    node, node->left);
	++*error;
    }
    
    if (node->right != NIL(struct avlnode) && 
		    (*compare)(node->key, node->right->key) > 0) {
	(void) printf("Bad ordering between 0x%08x and 0x%08x", 
	    node, node->right);
	++*error;
    }

    return comp_height;
}

long avlkeyset__CheckTree(tree)
struct avlkeyset *tree;
{
    int error = 0;
    (void) do_check_tree(tree->root, avlkeyset_GetCompareFunction(tree), &error);
    return error;
}
