/* Author: Ben Miller
 * Title: Hashing
 *
 * This is the modified version of my first hashing function program.  I modified it to decrease its
 * size by 20%.  This program reads three files from the command line to create adn edit a table.
 * There are four functions that are used to initialize, add, find, and remove entries from a table.
 * I have created my own library for the functions being used.
 * This is for CS38, my second course in programming.
*/

#include <stdio.h>
#include "hash2_lib.h"

#define NAME_LENGTH 20

int main (int argc, char *argv[])
{
	FILE *infile1, *infile2, *infile3;
	char add_file[NAME_LENGTH], remove_file[NAME_LENGTH], display_file[NAME_LENGTH];
	Array Table;
	Entry node, *temp;
	int location, remove_key, display_key;

	/* check command line for correct number of files */
	if (argc != 4) {
		printf("Error: Enter the 3 correct files: \n");
		printf("(add, remove, & display) ");
		scanf("%s %s %s", add_file, remove_file, display_file);
	}
	
	strcpy (add_file, argv[1]);
	strcpy (remove_file, argv[2]);
	strcpy (display_file, argv[3]);
	
	/* initializes the table to be empty */
	initialize_table(Table);
	
	/* open add file */
	if ((infile1 = fopen(add_file, "r")) == NULL) {
		printf("Error opening file: %s.\n", add_file);
		exit(1);
	}
	
	/* read in entries from file and store in table */
	while (fscanf(infile1, "%d %d", &node.key, &node.info) != EOF)
		insert(node, Table);

	/* open remove file */
	if ((infile2 = fopen(remove_file, "r")) == NULL) {
		printf("Error opening file: %s.\n", remove_file);
		exit(1);
	}
	
	while (fscanf(infile2, "%d", &remove_key) != EOF) {
		location = find(remove_key, Table);
		if (location > (-1))
			delete(location, remove_key, Table);
		else
			printf("%d was not found for removal.\n", remove_key);
	}	
	
	/*open display file */
	if ((infile3 = fopen(display_file, "r")) == NULL) {
		printf("Error opening file: %s.\n", display_file);
		exit(1);
	}

	while (fscanf(infile3, "%d", &display_key) != EOF) {
		location = find(display_key, Table);
		if (location > (-1))
			if (Table[location].key == display_key)
				printf("%d %d\n", Table[location].key, Table[location].info);
			else {
				temp = Table[location].next;
				while (temp->key != display_key)
					temp = temp->next;
				printf("%d %d\n", temp->key, temp->info);
			}
		else
			printf("%d was not found for display.\n", display_key);
	}
	
	/* close the three open files */
	fclose(infile1);
	fclose(infile2);
	fclose(infile3);
	
	exit(1);
}

