#include "memmgr.h"
#include "list.h"

void List::add(Object& object) {
    Node* node = new Node;
    if (node != 0) {
        node->value = &object;
        node->next = 0;
        node->prev = bottom;
        if (bottom == 0) {
            top = node;
        } else {
            bottom->next = node;
        }
        bottom = node;
    }
}

void List::insert(uint32 i, Object& object) {
    Node* node = getNode(i);
    if (node == 0) {
        add(object);
    } else {
        Node* new_node = new Node;
        if (new_node != 0) {
            new_node->value = &object;
            if (node->prev != 0) {
                node->prev->next = new_node;
                new_node->prev = node->prev;
            } else {
                new_node->prev = 0;
                top = new_node;
            }
            new_node->next  = node;
            node->prev      = new_node;
        }
    }
}

void List::remove(Object& object) {
    Node* node = getNode(object);
    if (node != 0) {
        if (node->prev == 0) {
            top = node->next;
        } else {
            node->prev->next = node->next;
        }
        if (node->next == 0) {
            bottom = node->prev;
        } else {
            node->next->prev = node->prev;
        }
        delete node;
    }
}

Object* List::get(uint32 i) {
    Node* node = getNode(i);
    return (node != 0) ? node->value : 0;
}

List::Node* List::getNode(Object& object) {
    Node* node = 0;
    for (node = top; node != 0; node = node->next) {
        if (&object == node->value) break; 
    }
    return (node != 0) ? node : 0;
}

List::Node* List::getNode(uint32 i) {
    Node* node = top;
    for (uint32 j = 0; j < i; j++) {
        if (node == 0) break;
        node = node->next;
    }
    return node;
}

