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

struct tnode {
	char *word;
	int count;
	struct tnode *left;
	struct tnode *right;
};


struct tnode *talloc(void);
//char *strdup(char *);


/* addtree: pの位置、またはその下にwのノードを加える */
struct tnode *addtree(struct tnode *p, char *w)
{
	/* 文字列の比較結果を格納する */
	int cond;
	
	printf("[DBG] addtree() start  tnode:%p w:%s\n", p, w);
	
	/* 新しい単語が来たら新規ノードを作る */
	if (p == NULL) {
		p = talloc();
		p->word = strdup(w);
		p->count = 1;
		p->left = p->right = NULL;
	}
	/* 繰り返された単語 */
	else if ((cond = strcmp(w, p->word)) == 0) {
		p->count++;
	}
	/* より小さい文字列なら、左側の分木へ */
	else if (cond < 0) {
		p->left = addtree(p->left, w);
	}
	/* より大きい文字列なら、右側の分木へ */
	else {
		p->right = addtree(p->right, w);
	}
	
	printf("[DBG] << addtree() return p:%p\n", p);
	
	return p;
}


/* treeprint: ノードの単語を再帰的にプリントする */
void treeprint(struct tnode *p)
{
	printf("[DBG] >> treeprint()  p:%p\n", p);
	if (p != NULL) {
		treeprint(p->left);
		printf("%4d : %s\n", p->count, p->word);
		treeprint(p->right);
	}
}


/* talloc: tnodeを作る */
struct tnode *talloc(void)
{
	printf("[DBG] tnode() called\n");
	return (struct tnode *)malloc(sizeof(struct tnode));
}


/* strdup: sをmallocで確保した領域にコピーする */
/*
char *strdup(char *s)
{
	char *p; 
	
	p = (char *)malloc(strlen(s) + 1);	 +1は最後のNULL文字を格納するため 
	if (p != NULL) {
		strcpy(p, s);
	}

	return p;
}*/