/*
Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include "util.h"

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

void dcop_stringlist_destroy( dcop_stringlist *list )
{
    dcop_list_item *it = list->root;
    while ( it )
    {	
	free( (char *)it->data );
	it = it->next;
    }
    dcop_list_destroy( list );
}

void dcop_stringlist_append( dcop_stringlist *list, const char *str )
{
    dcop_list_append( list, strdup( str ) );
}

dcop_list *dcop_list_new()
{
    dcop_list *res = (dcop_list *)malloc( sizeof( dcop_list ) );
    res->root = NULL;
    return res;
}

void dcop_list_destroy( dcop_list *list )
{
    dcop_list_item *it = list->root;
    while ( it )
    {
	dcop_list_item *tmp = it;
	it = it->next;
	free( tmp );
    }
    free( list );
}

dcop_list_item *dcop_list_item_new()
{
    dcop_list_item *res = malloc( sizeof( dcop_list ) );
    res->prev = res->next = NULL;
    return res;
}

dcop_list_item *dcop_list_append( dcop_list *list, void *data )
{
    dcop_list_item *it = list->root;
    dcop_list_item *res = dcop_list_item_new();

    if ( it == NULL )
	list->root = res;
    else
    {
	while ( it->next != NULL )
	    it = it->next;

	it->next = res;
	res->prev = it;
    }

    res->data = data;
    return res;
}

gboolean dcop_list_remove( dcop_list *list, void *data )
{
    dcop_list_item *it = list->root;

    if ( it == NULL )
	return False;

    if ( it->data == data )
    {
	list->root = it->next;
	if ( list->root )
	    list->root->prev = NULL;

	free( it );

	return True;
    }

    it = it->next;

    while ( it != NULL )
    {
	if ( it->data == data )
	{
	    it->prev->next = it->next;
	    if ( it->next )
		it->next->prev = it->prev;
	    free( it );
	    return True;
	}
	it = it->next;
    }

    return False;
}

unsigned int dcop_list_count( dcop_list *list )
{
    unsigned int res = 0;
    dcop_list_item *it = list->root;
    while ( it )
    {
	res++;
	it = it->next;
    }
    return res;
}
