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

#define NAMESIZE 40
#define TESTNAMES 6

typedef struct list_item_ {
	char name[NAMESIZE];
	struct list_item_ *next;
} LIST_ITEM;


void lisaa_listaan(LIST_ITEM **list, LIST_ITEM *item)
{
	if(*list == NULL) {
		item->next = NULL;
	}
	else {
		item->next = *list;
	}
	*list = item;
}


void tulosta(LIST_ITEM *list)
{
	while(list != NULL) {
		printf("Nimi: %s\n", list->name);
		list = list->next;
	}
}


LIST_ITEM *poista(LIST_ITEM **list, char *remove)
{
	LIST_ITEM *removed = NULL;
	LIST_ITEM *link = NULL;

	if(*list == NULL) return NULL; // empty list

	if(strcmp((*list)->name, remove)==0) { // check top item
		removed = *list;
		*list = removed->next; // remove top item
		return removed;
	}

	link = *list;
	while(link->next != NULL) { // check following items
		removed = link->next;
		if(strcmp(removed->name, remove)==0) {
			link->next = removed->next;
			return removed;
		}
		else {
			link = link->next;
		}
	}

	return NULL;
}


int poista_kaikki(LIST_ITEM **list, char *remove)
{
	LIST_ITEM *removed = NULL;
	LIST_ITEM *link = NULL;
	int count = 0;

	while(*list != NULL) { // check if we need to remove first item
		if(strcmp((*list)->name, remove)==0) {
			removed = *list;
			*list = (*list)->next; // first item removed - change list head
			free(removed);
			count++;
		}
	}

	if(*list == NULL) return count; // list is empty

	link = *list;
	while(link->next != NULL) {
		if(strcmp(link->next->name, remove)==0) {
			removed = link->next;
			link->next = link->next->next;  // same as removed->next;
			free(removed);
			count++;
		}
		else {
			link = link->next;
		}
	}

	return count;
}



int main(int argc, char **argv)
{
	int i;
	LIST_ITEM *list = NULL; // start with empty list
	LIST_ITEM *item;

	for(i = 1; i <= TESTNAMES; i++) {
		item = (LIST_ITEM *) malloc(sizeof(LIST_ITEM));
		if(item != NULL)  {
			sprintf(item->name, "Pekka%d Puupaa", i/2);
			lisaa_listaan(&list, item);
		}
	}
	tulosta(list);


	do {
		char name[NAMESIZE];
		printf("Anna poistettava nimi: ");
		gets(name);
		item = poista(&list, name);
		if(item != NULL) {
			printf("Pois: %s\n", item->name);
			free(item);
		}
		else {
			printf("Ei löydy: %s\n", name);
		}
		printf("Listaan jäi: \n");
		tulosta(list);

	}while(list != NULL);


	for(i = 1; i <= TESTNAMES; i++) {
		char name[NAMESIZE];
		sprintf(name, "Pekka%d Puupaa", i);
		item = poista(&list, name);
		if(item != NULL) {
			printf("Pois: %s\n", item->name);
			free(item);
		}
		tulosta(list);
	}


	return 0;
}