#include <stdlib.h>
#include <math.h>
#include "vector.h"             // 2D Vector stuff used for screen coordinates
#include "draw.h"               // 2D Raster Graphics Library used for drawing
#include "bullet.h"
#include "ship.h"               // Spaceship player class
#include "text.h"               // 2D Simple raster text output classes
#include "linklist.h"           // Used for enemy memory management


void LinkedList::Link::size(unsigned r){
	rock->size(r);
}

bool LinkedList::cleared(){
	return(head==NULL);
}

double LinkedList::Link::getsize(){
	return rock->getsize();
}

Vector LinkedList::Link::getcenter(){
	return rock->getcenter();
}

void LinkedList::Link::display(byte_t color, byte_t *where){
	draw(*rock,color,where);
}

Circle LinkedList::Link::me(){
	return (Circle(*rock));
}

void LinkedList::Link::fly(int ticks, const Vector &s){
	rock->fly(ticks,s);
}

void LinkedList::remove(){
	if (head!=NULL){
		Link *ptr=head;
		head=head->next;
		delete ptr;
	}
}

bool LinkedList::Link::on(Vector p){
	return (rock->on(p));
}

LinkedList::~LinkedList(){
	Link *ptr=head;
	Link *trail;
	while(ptr!=NULL){
		trail=ptr;
		ptr=ptr->next;
		delete trail;
	}	
}

void LinkedList::fly(int ticks, const Vector &s){
	Link *ptr, *trail;
	ptr=head;
	trail=ptr;
	while(ptr!=NULL){
		ptr->fly(ticks,s);
		trail=ptr;
		ptr=ptr->next;
	}
}

void draw(const LinkedList &list, byte_t color, byte_t *where){
	LinkedList::Link *ptr;
	ptr=list.head;
	while(ptr!=NULL){
		ptr->display(color,where);
		ptr=ptr->next;
	}
}

LinkedList::LinkedList(){
	head=NULL;
}

void LinkedList::add(Circle r){
	Link *ptr;
	ptr=new Link(r,head);
	if ((ptr!=0)&&(ptr->ok)) head=ptr;
	else exit(1);
}

void LinkedList::collide(Ship &ship){
	Link *ptr,*trail;
	ptr=head;
	trail=head;
	bool divides=false;
	Vector center;
	int size=0;
	while(ptr!=NULL){
		if(ship.collide(ptr->me())){
			ship.kill();
			if (ptr->getsize()>7){
				divides=true;
				size=((ptr->getsize()>12)?10:5);
				center=ptr->getcenter();
			}
			if (ptr==head)
				head=head->next;
			else
				trail->next=ptr->next;
			delete ptr;
			ptr=NULL;
		}
		else for(int i=0; i<ship.shots(); i++){
			if (ptr->on(pos(bullet(ship,i)))){
				if (ptr->getsize()>7){
					divides=true;
					size=((ptr->getsize()>12)?10:5);
					center=ptr->getcenter();
				}
				bullet(ship,i).kill();
				ship.score+=100;
				if(ptr==head)
					head=head->next;
				else
					trail->next=ptr->next;
				delete ptr;
				ptr=NULL;
				i=ship.shots();
			}
		}
		trail=ptr;
		if (ptr!=NULL) ptr=ptr->next;
	}
	if(divides){
		add(Circle(center,Vrand(),size));
		add(Circle(center,Vrand(),size));
	}
}

LinkedList::Link::Link(Circle r, Link * ptr){
	rock=new Circle(r);
	ok=(rock!=NULL);
	next=ptr;
}

LinkedList::Link::~Link(){
	if (rock!=NULL) delete rock;
}
