#include "hash2_types.h"

/* sets key and into to -1 and next to null */
void initialize_table (Array Table)
{
	int a;
	
	for(a=0; a<LENGTH; a++) {
		Table[a].key = EMPTYKEY;
		Table[a].info = EMPTYKEY;
		Table[a].next = NULL;
	}
	return;
}

/* inserts a new entry using the hashing function and if the location
 * is already occupied then it link it on to the one already there
*/
void insert(Entry node, Array Table)
{
	int location;
	Entry *new_entry, *temp;
	
	/* hash function */
	location = node.key % LENGTH;
		
	if (Table[location].key == -1) {
		Table[location].key = node.key;
		Table[location].info = node.info;	
	} else {
		/* create more memory to add a link onto array location */
		if ((new_entry = (Entry *)malloc(sizeof(Entry))) == NULL) {
			printf("Error: malloc failed\n");
			exit(1);
		}
		
		/* occupy new node */
		new_entry->key = node.key;
		new_entry->info = node.info;
		new_entry->next = NULL;
		
		/* attach it onto the struct in the array location */
		if (Table[location].next == NULL)
			Table[location].next = new_entry;
		else {
			temp = Table[location].next;
			while (temp->next != NULL)
				temp = temp->next;
			temp->next = new_entry;
		}
	}
	return;
}

/* returns the array location of where the key is located or -1 for
 * not found
*/
int find(int key, Array Table)
{
	int location, not_found = -1;
	Entry *temp;

	/* hash function */
	location = key % LENGTH;

	if (Table[location].key == key)
		return (location);
		
	if (Table[location].next == NULL)
		return (not_found);
	else {
		temp = Table[location].next;
		while (temp->next != NULL) {
			if (temp->key == key)
				return(location);
			temp = temp->next;
		}
	}
	return(not_found);
}

/* deletes items in the table */
void delete(int location, int key, Array Table)
{
	Entry *temp, *previous, *current;
	
	if (Table[location].key == key && Table[location].next == NULL) {
		Table[location].key = -1;
		Table[location].info = -1;
		return;
	}
	
	if (Table[location].key == key && Table[location].next != NULL) {
			temp = Table[location].next;
			Table[location].key = temp->key;
			Table[location].info = temp->info;
			Table[location].next = temp->next;
	} else {
		current = Table[location].next;
		if (current->key == key) {
			Table[location].next = current->next;
			free(current);
			return;
		} else {
			previous = Table[location].next;
			current = current->next;
			while (current->next != NULL) {
				if (current->key == key)
					break;
				previous = previous->next;
				current = current->next;
			}
			previous->next = current->next;
			free(current);
			return;	
		}
	}
}

