#include "list.h"
#include <stdlib.h>
#ifndef __FreeBSD__
#include <malloc.h>
#endif
#include <string.h>


int	ListInit(ListItem *list)
{
	(*list)=NULL;
	return 1;
}

int	ListSize(ListItem *list)
{
	struct aItem *iterator = (*list);
	int count=0;
	for (;iterator;iterator=iterator->next, count++);
	return count;
}

int	ListInsert(ListItem *list,void *dta)
{
	struct aItem* l;
	if (!(*list)) {
		(*list)=(ListItem)(malloc(sizeof(struct aItem)));
		if  (!*list) return 0;
		(*list)->data=dta;
		(*list)->next=NULL;
		(*list)->prev=NULL;
		return 1;
	}

	l=(*list);
	while (l->next)
		l=l->next;

	l->next=(ListItem)(malloc(sizeof(struct aItem)));
	if (!l->next) return 0;
	l->next->prev=l;
	l->next->data=dta;
	l->next->next=NULL;
	return 1;
}
int 	ListAllocInsert(ListItem *list,void*dta,int size)
{
	void *ptr;
	ptr=(void*)malloc(size);
	if (!ptr) return 0;
	memcpy(ptr,dta,size);
	ListInsert(list,ptr);
	return 1;
}

int	ListRemove(ListItem l,ListItem *list)
{
	if (l->prev)
		l->prev->next=l->next;
	else
		*list=l->next;
	if (l->next)
		l->next->prev=l->prev;
	if (l->data) free(l->data);
	free(l);
        return 1;
}
int	ListFree(ListItem*l)
{
	ListItem p=*l;
	while (p) {
		ListRemove(p,l);
		p=*l;
	}
	return 1;
}
int 	ListGetFirstAndRemove(ListItem *l,void *dest,int size)
{
	if (!*l) return 0;
	memcpy(dest,(*l)->data,size);
	ListRemove(*l,l);
	return 1;
}



syntax highlighted by Code2HTML, v. 0.9.1