#include "tree_binary_types.h"

/* check command line for correct number of files */
void check_command_line (int argc, char *argv[], char file1[], char file2[])
{
	if (argc != 3) {
		printf("Error: number of arguments in command line.\n");
		printf("Enter add file: ");
		scanf("%s", file1);
		printf("Enter remove file: ");
		scanf("%s", file2);
	} else {
		strcpy (file1, argv[1]);
		strcpy (file2, argv[2]);
	}
}

/* creates the root node */
TreeNode *initialize_tree (void)
{
	TreeNode *root;

	if ((root = (TreeNode *)malloc(sizeof(TreeNode))) == NULL) {
		printf("Error: malloc failed\n");
 		exit(1);
	}

	root->data = -1;
	root->Llink = NULL;
	root->Rlink = NULL;
	
	return(root);
}

/* traverses through the tree until location of new node is found */
void add_node (int number, TreeNode *temp)
{
	TreeNode *new_node;
	
	if ((new_node = (TreeNode *)malloc(sizeof(TreeNode))) == NULL) {
		printf("Error: malloc failed\n");
		exit(1);
	}

	new_node->data = number;
	new_node->Llink = NULL;
	new_node->Rlink = NULL;

	while (1) {
		if (number < temp->data) {
			if (temp->Llink == NULL) {
				temp->Llink = new_node;
				return;
			} else
				temp = temp->Llink;
		} else {
			if (temp->Rlink == NULL) {
				temp->Rlink = new_node;
				return;
			} else
				temp = temp->Rlink;
		}
	}
}

/* displays the tree in preorder */
void preorder_display (TreeNode *temp)
{
	printf("%d\n", temp->data);
	
	if (temp->Llink != NULL)
		preorder_display(temp->Llink);

	if (temp->Rlink != NULL)
		preorder_display(temp->Rlink);
}

/* displays the tree inorder */
void inorder_display (TreeNode *temp)
{
	if (temp->Llink != NULL)
		inorder_display(temp->Llink);

	printf("%d\n", temp->data);

	if (temp->Rlink != NULL)
		inorder_display(temp->Rlink);
}

/* displays the tree in postorder */
void postorder_display (TreeNode *temp)
{
	if (temp->Llink != NULL)
		postorder_display(temp->Llink);

	if (temp->Rlink != NULL)
		postorder_display(temp->Rlink);

	printf("%d\n", temp->data);
}

/****************************************************************/
/* runs through file and finds the best root for the tree 
int find_pivot (FILE *file)
{
	int number, total = 0, average, num_in_file = 0, pivot = 0;
	int difference, new_difference;
	
	while (fscanf(file, "%d", &number) != EOF) {
		total = total + number;
		num_in_file++;
	}

	average = total / num_in_file;
	
	new_difference = average;
	while (fscanf(file, "%d", &number) != EOF) {
		if (number > average) {
			difference = number - average;
			printf("Difference:  %d\n", difference);
		} else
			difference = average - number;
		if (difference < new_difference) {
			number = pivot;
			new_difference = difference;
		}
	}

	return (pivot);
}*/
