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

struct word_pair
{
	int pair_number;
	char *wordA, *wordB;
};
int main()
{
	struct word_pair **word_pair_list, *current_pair;
	int total_word_pairs;
	FILE *file_pointer;
	char filename[] = "example.txt";
	char buffer[100];
	char *current_character;
//	int error_check_int, *error_check_pointer;
//	int finished = 0;

	printf("\nCommand line vocabulary flash cards v5\n\n");
	file_pointer = fopen(filename, "r");
	if (NULL == file_pointer)
	{
	//	finished = 1;
		printf("Could not open file %s\n", filename);
		return(1);
	}

	int loop_count=0;

	total_word_pairs = 0;
	word_pair_list = NULL;
	while((current_character = fgets(buffer, 100, file_pointer)))
	{
		loop_count++;
		printf("Reading line %d\n", loop_count);
		fflush(stdout);
		if ('#' != buffer[0])
		{
			if ((current_character = strchr(buffer, '\r')))
			{
				*current_character = '\0';
			}
			if ((current_character = strchr(buffer, '\n')))
			{
				*current_character = '\0';
			}
			if ((current_character = strchr(buffer, '|')))
			{
				struct word_pair **temp;
				int i;

				*current_character = '\0';
				current_character++;
				total_word_pairs++;
				temp = realloc(word_pair_list, total_word_pairs*sizeof(struct word_pair **));
				current_pair = malloc(sizeof(struct word_pair));
				if ((NULL == temp) || (NULL == current_pair))
				{
					printf("Could not allocate more memory for pair %d", total_word_pairs);
					total_word_pairs--;
				}
				else
				{
					word_pair_list = temp;
					word_pair_list[total_word_pairs - 1] = current_pair;
					current_pair->pair_number = total_word_pairs;
					if (0 == (strlen(buffer)))
					{
						i = printf("Word %dA is blank\n", total_word_pairs);
						current_pair->wordA = malloc(i*sizeof(char));
						sprintf(current_pair->wordA, "Word %dA is blank", total_word_pairs);
					}
					else
					{
						current_pair->wordA = strdup(buffer);
					}
					if (0 == (strlen(current_character)))
					{
						i = printf("Word %dB is blank\n", total_word_pairs);
						current_pair->wordA = malloc(i*sizeof(char));
						sprintf(current_pair->wordB, "Word %dB is blank", total_word_pairs);
					}
					else
					{
						current_pair->wordB = strdup(current_character);
					}
				}
			}
		}
	}
	printf("Reached End Of File\n");
	fflush(stdout);
	fclose(file_pointer);

	printf("Cleaning up\n");

	int i;
	
	for(i=0; i<total_word_pairs; i++)
	{
		printf("No. %-4d A: %-17s B: %s\n",
				word_pair_list[i]->pair_number, word_pair_list[i]->wordA, word_pair_list[i]->wordB);
		free(word_pair_list[i]->wordA);
		free(word_pair_list[i]->wordB);
		free(word_pair_list[i]);
		fflush(stdout);
	}
	free(word_pair_list);
	printf("Exiting\n");
	return(0);
}
