/*
**	avl_bench.c - simple index benchmark for avltree
*/

#include <stdio.h>
#include <stdlib.h>
#include "avltree.h"


/*
**	key generation
*/

static char	*key = NULL;
static int	keylen = 0, seeded = 0;

char *
keygen(int n, int seed)
{
	int	i, len;

	if (seed) {
		srandom((unsigned)seed);
		seeded++;
	}
	if (!seeded) {
		srandom(1);
		seeded++;
	}

	if (n > keylen) {
		if (keylen)
			free(key);
		keylen = n;
		key = malloc(keylen+1);
	}
	len = random() % n;
	while (len == 0)
		len = random() % n;

	for (i=0; i<len; i++)
		key[i] = 'a' + (random() % 26);

	key[i] = '\0';
	return(key);
}

void
keyreset()
{
	seeded = 0;
}

usage(char *str)
{
	fprintf(stderr, "usage: %s [nkeys [max_key_len]]\n", str);
	exit(1);
}

main(int argc, char *argv[])
{
        AVL_IX_DESC     ix;
        AVL_IX_REC      *pe;
        int             i, ret, nkeys, maxlen;

	switch (argc) {
	    case 1:
		nkeys = 100000;
		maxlen = 20;
		break;
	    case 2:
		nkeys = atoi(argv[1]);
		maxlen = 20;
		break;
	    case 3:
		nkeys = atoi(argv[1]);
		maxlen = atoi(argv[2]);
		break;
	    default:
		usage(argv[0]);
	}
	if (nkeys < 1  ||  maxlen < 1)
		usage(argv[0]);

	printf("nkeys %d  maxkeylen %d\n", nkeys, maxlen);

        pe = (AVL_IX_REC *) malloc(sizeof(AVL_IX_REC) + maxlen);

	/* create index & populate it */

        avl_create_index(&ix, AVL_COUNT_DUPS, 0);
	for (i=0; i<nkeys; i++) {
        	strcpy(pe->key, keygen(20, 0));
                if (avl_add_key(pe, &ix) != AVL_IX_OK) {
                        fprintf(stderr, "avl_add_key(%s)\n", pe->key);
                        exit(1);
                }
        }

	/* look up all keys */

	keyreset();
	for (i=0; i<nkeys; i++) {
        	strcpy(pe->key, keygen(20, 0));
                if (avl_find_key(pe, &ix) != AVL_IX_OK) {
                        fprintf(stderr, "avl_add_key(%s)\n", pe->key);
                        exit(1);
                }
	}
        exit(0);
}

