// sattool - visual satellite tracking and prediction tool.
// Copyright 2000 Tom Rothamel <tom-idbg@onegeek.org>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  

#include "sattool.h"
#include <stdlib.h>
#include <malloc.h>

List::List() {
	first = NULL;
	last = NULL;
	cur = NULL;

	count = 0;
}

List::~List() {
	ListElement *oldnext;
	
	cur = first;
  	while (cur) {
		oldnext = cur->next;
		unlock(cur->data);
  		delete cur;
		cur = oldnext;
	}
}


void List::add(Thing *t) {
	ListElement *le;

	lock(t);
	
	le = new ListElement;
	le->next = NULL;
	le->prev = NULL;
	le->data = t;

	count++;
	
	if (!first) {
		first = le;
		last = le;

		return;
	}

	le->prev = last;
	last->next = le;
	last = le;
}

void List::reset() {
	cur = NULL;
}

Thing *List::next() {
	if (cur == NULL) {
		cur = first;
	} else {
		cur = cur->next;
	}

	if (!cur) return NULL;
	
	return cur->data;
}

Thing *List::prev() {
	if (cur == NULL) {
		cur = last;
	} else {
		cur = cur->prev;
	}

	if (!cur) return NULL;
	
	return cur->data;
}


// This sorts a list, and creates a new list.
List *SortList(List *l, int (*func)(Thing **, Thing **)) {
	List *nl;
	Thing **things;
	Thing *t;
	int i;

	nl = new List();
	if (!l->count) return nl;
	
	things = (Thing **) calloc(sizeof(Thing *), l->count);

	i = 0;
	while (t = l->next()) things[i++] = t;

	qsort(things, l->count, sizeof(Thing *),
	      (int (*)(const void *, const void *)) func);

	for (i = 0; i < l->count; i++) {
		nl->add(things[i]);
	}
		
	free(things);
	return nl;
}
		
