/*
 * system_list.c
 *
 * Implementation of list manipulation functions
 * 
 */


#include <stdio.h>
#include <stdlib.h>
#include "system_list.h"


sys_list_t* sys_lst_new()
{
	sys_list_t *list;
	list = (sys_list_t*) malloc(sizeof(sys_list_t));
	list->first = NULL;
	list->last = NULL;
	return list;
}


void sys_lst_destroy(sys_list_t *list)
{
	if (list == NULL) {
		return;
	}
	
	sys_lst_iitem_t *el, *next;
	
	el = list->first;
	
	while (el != NULL) {
		next = el->next;
		
		if (el->type == TAKE) {
			if (el->system_response.take.size != 0) {
				free(el->system_response.take.cover);
			}
		}
		
		free(el);
		el = next;
	}
	
	free(list);
}


void sys_lst_insert(sys_list_t *list, sys_lst_iitem_t *item)
{
	if (list == NULL || item == NULL) {
		return;
	}

	item->next = NULL;

	if(list->first == NULL) {
    	list->first = item;
		list->last = item;
	} else {
		list->last->next = item;
		list->last = item;
   	}
}


void sys_lst_print(sys_list_t *list)
{
	int i = 1;
	sys_lst_iitem_t *el;
	
	el = list->first;
	
	while(el != NULL) {
		printf("%2d: type:%d.\n", i, el->type);
		el = el->next;
		++i;
	}
}


sys_lst_iitem_t* sys_lst_pop(sys_list_t *list)
{
	sys_lst_iitem_t *el;
	
	if(list->first == NULL) {
		return NULL;
	}
	
	el = list->first;
	list->first = el->next;

	return el;
}
