#include "mutextree"
#include "config/config"

MutexNode *MutexTree::nodelock(void *o, MutexNode *start) {

    // No tree start yet? Create one.
    if (!start) {
#	ifdef DEBUG
	debugmsg("Mutex nodelock: new node for " << o <<", locking now\n");
#	endif	
        start = new MutexNode(o);
	start->lock();
#	ifdef DEBUG
	debugmsg("Mutex nodelock: new node for " << o <<" locked\n");
#	endif	
	return start;
    }

    // At object? Dive into the Mutexnode.
    if (start->obj() == o) {
#	ifdef DEBUG
	debugmsg("Mutex nodelock: existing node for " << o <<
		 ", locking now\n");
#	endif	
	start->lock();
#	ifdef DEBUG
	debugmsg("Mutex nodelock: existing node for " << o << " locked\n");
#	endif	
	return start;
    }

    // Decide whether to recurse left or right.
    if (start->obj() < o) {
#	ifdef DEBUG
	debugmsg("Mutex nodelock: going left for " << o << '\n');
#	endif	
        start->left(nodelock(o, start->left()));
    } else {
#	ifdef DEBUG
	debugmsg("Mutex nodelock: going right for " << o << '\n');
#	endif	
	start->right(nodelock(o, start->right()));
    }	
    return start;
}
