/* $Id: tree.cc,v 1.3 2003/08/21 17:49:46 rene0 Exp $ */

#include "tree.h"
#include <stdio.h>

Tree::Tree(Token* token) {
	mytoken = token;
	myprev = 0;
	mynext = 0;
	myparent = 0;
	mychild = 0;
}

Tree::~Tree() {
	delete mytoken; // also deletes Token object itself !
	mytoken = 0;
	if (myprev != 0) {
		myprev->mynext = mynext;
	}	
	if (mynext != 0) {
		mynext->myprev = myprev;
	}	
	if (myparent != 0) {
		if (myparent->mychild == this) {
			if (myprev != 0) {
				myparent->mychild = myprev;
			} else if (mynext != 0) {
				myparent->mychild = mynext;
			}
		}
	}
	// remove children
	if (mychild != 0) {
		delList(mychild);
		mychild = 0;
	}
}

Token* Tree::getToken() {
	return mytoken;
}

void Tree::setToken(Token *token) {
	mytoken = token;
}

bool Tree::hasPrev() {
	return (myprev != 0);
}

bool Tree::hasNext() {
	return (mynext != 0);
}

bool Tree::hasChild() {
	return (mychild != 0);
}

bool Tree::hasParent() {
	return (myparent != 0);
}

Tree* Tree::prev() {
	return myprev;
}

Tree* Tree::next() {
	return mynext;
}

Tree* Tree::child() {
	return mychild;
}

Tree* Tree::parent() {
	return myparent;
}

void Tree::prepend(Token* token) {
	// insert new element before current
	Tree* elem = new Tree(token);

	elem->myprev = myprev;
	elem->mynext = this;
	elem->mychild = 0;
	elem->myparent = myparent;
	if (myprev != 0) {
		myprev->mynext = elem;
	} else if (myparent != 0) {
		myparent->mychild = elem; // 2004-01-25,2004-04-21
	}
	myprev = elem;
}

void Tree::append(Token* token) {
	// insert new element after current
	Tree* elem = new Tree(token);

	elem->myprev = this;
	elem->mynext = mynext;
	elem->mychild = 0;
	elem->myparent = myparent;
	if (mynext != 0) {
		mynext->myprev = elem;
	}
	mynext = elem;
}

void Tree::insertChild(Token* token) {
	// insert new child node and link to parent
	Tree* elem = new Tree(token);

	elem->myparent = this;
	mychild = elem;
}

void Tree::delList(Tree *t) {
	// delete a chain of nodes
	while (t->mynext != 0) {
		t = t->mynext;
	}
	while (t != 0) {
		Tree *temp = t;
		t = t->myprev;
		delete temp;
	}
}

void Tree::removeChild() {
	mychild = 0;
}
