#include <stdlib.h>
#include "c_list.h"

LIST::LIST() {
  first = NULL;
  last  = NULL;
  count = 0;
}

void LIST::add( ENTITY *item ) {
 if (first == NULL) {
  first = new NODE;
  first->item = item;
  first->next = NULL;
  first->prev = NULL;
  last = first;
 } else {
  NODE *p = last;
  NODE *insert = new NODE;
  insert->item = item;
  insert->next = NULL;
  insert->prev = p;
  p->next = insert;
  last = p->next;
 }
 count++;
}

void LIST::remove( NODE *p ) {
 if (first == p) first = p->next;
 if (last  == p) last  = p->prev;
 if (p->prev) p->prev->next = p->next;
 if (p->next) p->next->prev = p->prev;
 delete(p);
 count--;
}

void LIST::remove_all() {
  NODE *p = first;
  NODE *x;
  while (p) {
    x = p->next;
    delete(p->item);
    remove(p);
    p = x;
  }
  count = 0;
}

void LIST::draw_all() {
  NODE *p = first;
  while (p) {
    p->item->draw();
    p = p->next;
  }
}

void LIST::move_all() {
  NODE *p = first;
  while (p) {
    p->item->move();
    p = p->next;
  }
}

void LIST::remove_dead_nodes() {
  NODE *p = first;
  NODE *x;
  while (p) {
    x = p->next;
    if (p->item->done()) {
      delete(p->item);
      remove(p);
    }
    p = x;
  }
}

void LIST::unlink_entity( ENTITY *item ) {
NODE *p = first;
  NODE *x;
  while (p) {
    x = p->next;
    if (p->item == item) remove(p);
    p = x;
  }
}

void LIST::check_collisions() {
  NODE *p = first;
  NODE *o;
  while (p) {
    o = first;
    while (o) {
      p->item->collide(o->item);
      o = o->next;
    }
    p = p->next;
  }
}

/* END */
