#include <iostream.h>
#include <stdlib.h>

#include "os.h"

#undef VERBOSE

extern unsigned int _stklen = 24576;

int
compare_ints(const void *a, const void *b)
{
    return *(int *) a - *(int *) b;
}

const int NumInts = 1000;
const int NumReps = 1000;

int
main(int argc, char *argv[])
{
    int i;
    int *arr = new int[NumInts];
    int seed;
    OSTree<int> *tree;

    for (int j = 0; j < NumReps; j++) {
	tree = new OSTree<int>;
	cout << "Repetition " << j << '\n';
	switch (argc) {
	    case 1:
		if (NumReps == 1)
		    randomize();
		else
		    srand(seed = j);
		break;
	   case 2:
		srand(atoi(argv[1]));
		break;
	   case 3:
		cerr << "Usage: " << argv[0] << " [seed]\n";
		exit(1);
	}

	for (i = 0; i < NumInts; i++) {
	    arr[i] = rand();
	    tree->Insert(arr[i]);
	    tree->CheckNodes();
#ifdef VERBOSE
	    tree->PrintNodes();
	    cout << '\n';
#endif
	}
#ifdef VERBOSE
	cout << '\n';
#endif

	qsort(arr, NumInts, sizeof(int), compare_ints);

	for (i = 0; i < NumInts; i++) {
	    int inx;
	    int j, k;
	    for (j = 0; j < NumInts - i; j++)
		if (*tree->Select(j) != arr[j]) {
		    cout << "Problems, seed = " << seed << '\n';
		}
		inx = rand() % (NumInts - i);
		tree->DeleteItem(arr[inx]);
		tree->CheckNodes();
#ifdef VERBOSE
		tree->PrintNodes();
#endif
		for (j = inx; j < NumInts - 1; j++)
		    arr[j] = arr[j+1];
#ifdef VERBOSE
		cout << *tree->Select(i) << ' ';
		cout << '\n';
#endif
	    }
#ifdef VERBOSE
	cout << '\n';
#endif
	delete tree;
    }

    return 0;
}

