/**************************************************************

imglist.c (C-Munipack project)
Copyright (C) 2003 David Motl, dmotl@volny.cz

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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

**************************************************************/

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>

#include "cmpack_common.h"
#include "list.h"

/* Free the list (do not free items) */
void list_free(CmpackList *list)
{
	while (list) {
		CmpackList *next = list->next;
		cmpack_free(list);
		list = next;
	}
}

/* Free the list (call freefn for each item) */
void list_free_with_items(CmpackList *list, void (*freefn)(void *))
{
	while (list) {
		CmpackList *next = list->next;
		if (freefn)
			freefn(list->ptr);
		cmpack_free(list);
		list = next;
	}
}

int list_count(CmpackList *list)
{
	int count=0;
	while (list) {
		count++;
		list = list->next;
	}
	return count;
}

CmpackList *list_append(CmpackList *list, void *item)
{
	CmpackList *ptr = list;
	if (ptr) {
		/* Find last item */
		while (ptr->next!=NULL)
			ptr = ptr->next;
		ptr->next = (CmpackList*)cmpack_malloc(sizeof(CmpackList));
		ptr->next->ptr = item;
		ptr->next->next = NULL;
		return list;
	} else {
		/* First item */
		ptr = (CmpackList*)cmpack_malloc(sizeof(CmpackList));
		ptr->ptr = item;
		ptr->next = NULL;
		return ptr;
	}
}

CmpackList *list_prepend(CmpackList *list, void *item)
{
	CmpackList *ptr = (CmpackList*)cmpack_malloc(sizeof(CmpackList));
	ptr->ptr = item;
	ptr->next = list;
	return ptr;
}

/* Reverse order of items */
CmpackList *list_reverse(CmpackList *list)
{
	CmpackList *ptr, *res, *next;
	
	res = NULL;
	for (ptr=list; ptr!=NULL; ptr=next) {
		next = ptr->next;
		ptr->next = res;
		res = ptr;
	}
	return res;
}
