#include <stdio.h>
#include "search_lib.c"

int main (int argc, char* argv[] )
{
	FILE *infile1, *infile2;
	char datafile[25], searchfile[25];
	int id_number, data_number, counter = 0, found_items = 0;
	int a , b;
	RecordList Array;
	Record entry;

	/* check if files were entered in the command line */
	if (argc != 3) {
		printf("Error with command line.\n");
		printf("Enter data file name: ");
		scanf("%s", datafile);
		printf("Enter search file name: ");
		scanf("%s", searchfile);
	} else {
		strcpy(datafile, argv[1]);
		strcpy(searchfile, argv[2]);
	}

	/* open datafile */
	if ((infile1 = fopen(datafile, "r")) == NULL) {
		printf("Error opening file %s.\n", datafile);
		exit(1);
	}

	/* set the list to null */
	initialize_list(Array);

	/* read in file and store into an array of structs */
	while (fscanf(infile1, "%d %d", &id_number, &data_number) != EOF) {
		entry.id = id_number;
		entry.data = data_number;
		counter++;
		a = add_record(Array, entry, counter);

		if (a != 1) {
			printf("Error with function add_record: \n");
			exit(1);
		}
	}

	/* open searchfile */
	if ((infile2 = fopen(searchfile, "r")) == NULL) {
		printf("Error opening file %s.\n", datafile);
		exit(1);
        }

	/* read in search file and search for id in array */
	while (fscanf(infile2, "%d", &id_number) != EOF) {
		a = search_binary(Array, id_number, counter);
		if (a != 1)
			printf("%.3d was not found.\n", id_number);
		b = search_sequential(Array, id_number, counter);
		if (b == 1)
			found_items++;
	}
	
	/* display results */
	printf("Found %d item(s) from %s in %s.\n", found_items, searchfile, datafile);
	printf("Binary search performed %d comparison(s).\n", binary_com);
	printf("Sequential search performed %d comparison(s).\n", sequential_com);
	
	/* close files */
	fclose(infile1);
	fclose(infile2);

	exit(1);
}
