
/*
 * xrt.cpp - cross-reference table implementation
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ln_seq.h"
#include "xrt.h"

struct treenode
    {
    char *word;
    ln_seq lines;
    treenode *left, *right;
    };

static treenode *addtree
        (treenode *t, char *w, unsigned n)
    {
    int cond;

    if (t == NULL)
        {
        t = new treenode;
        t->word
            = strcpy((char *)malloc(strlen(w) + 1), w);
        t->lines.add(n);
        t->left = t->right = NULL;
        }
    else if ((cond = strcmp(w, t->word)) == 0)
        t->lines.add(n);
    else if (cond < 0)
        t->left = addtree(t->left, w, n);
    else
        t->right = addtree(t->right, w, n);
    return t;
    }

static void printtree(treenode *t)
    {
    if (t != NULL)
        {
        printtree(t->left);
        printf("%12s: ", t->word);
        t->lines.print();
        printf("\n");
        printtree(t->right);
        }
    }

static treenode *root = NULL;

void xrt_add(char *w, unsigned n)
    {
    root = addtree(root, w, n);
    }

void xrt_print(void)
    {
    printtree(root);
    }

