/* main2.c   by Michael Thorpe   2000-06-07 */

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

#define BUF_SIZE 4096

char **ss;

int dumpit(const char *s,int depth,int value) {
   char **tt;
   int i;

   tt=(char **)realloc(ss,(depth+1)*sizeof(char *));
   if(!tt)
      return(1);
   ss=tt;
   ss[depth]=strdup(s);
   if(!ss[depth])
      return(1);
   if(value) {
      for(i=0;i<=depth;i++)
         fputs(ss[i],stdout);
      fputs("\n",stdout);
   }

   return(0);
}

int dumpitlit(const char *s,int depth,int value) {
   int i;

   for(i=0;i<depth;i++)
      putchar('\t');
   printf("%s (value=%d)\n",s,value);

   return(0);
}

int main(void) {
   int i;
   tree *tree;
   FILE *f;
   char buf[BUF_SIZE];

   tree=tree_create();
   if(!tree) {
      printf("Couldn't create tree!\n");
      return(1);
   }
   f=fopen("urls","r");
   if(!f) {
      f=stdin;
      printf("Enter strings to add:\n");
   }
   while(fgets(buf,BUF_SIZE,f)) {
      i=strlen(buf);
      while(i && buf[i-1]=='\n')
         buf[--i]='\0';
      if(!i) {
         if(tree_dump(tree,dumpitlit))
            printf("Couldn't dump tree!\n");
      } else if(tree_add(tree,buf,i))
         printf("Couldn't add \"%s\"!\n",buf);
   }
   printf("Tree size is %lu bytes, for %d nodes\n",(unsigned long)tree_getsize(tree),tree_getnodes(tree));
   printf("Enter strings to match:\n");
   while(fgets(buf,BUF_SIZE,stdin)) {
      i=strlen(buf);
      while(i && buf[--i]=='\n')
         buf[i]='\0';
      if(!i) {
         if(tree_dump(tree,dumpitlit))
            printf("Couldn't dump tree!\n");
      } else
         printf("Returned %d\n",tree_match(tree,buf));
   }
   printf("Enter strings to delete:\n");
   while(fgets(buf,BUF_SIZE,stdin)) {
      i=strlen(buf);
      while(i && buf[--i]=='\n')
         buf[i]='\0';
      if(!i) {
         if(tree_dump(tree,dumpitlit))
            printf("Couldn't dump tree!\n");
      } else if(!tree_del(tree,buf))
         printf("Couldn't delete \"%s\"!\n",buf);
   }
   ss=0;
   if(tree_dump(tree,dumpitlit))
      printf("Couldn't dump tree!\n");
   free(ss);
   if((i=tree_destroy(tree)))
      printf("Couldn't destroy tree (return value=%d)!\n",i);

   return(0);
}
