#include <stdio.h>

typedef struct	{ int key; } LEAF;

#include "tree.h"	/* LEAF must be defined before tree.h is #included */

/* ------------------------------------------------------------------------ */

prnt( stream, p )
FILE	*stream;
LEAF	*p;
{
	/*	Print routine needed by tprint().  Should always print
	 *	the same number of characters.  When p == 0 it should
	 *	print blanks.
	 */

	fprintf( stream, p ? "%2d" : "  ", p->key );
}

/* ------------------------------------------------------------------------ */

icmp( n1, n2 )				/* Comparison routine for	    */
LEAF	*n1, *n2;			/* insert() to use.		    */
{
	return( n1->key - n2->key );
}

dcmp( key, n2 )				/* Comparison routine for	    */
LEAF	*n2;				/* delete() to use.		    */
{
	return( key - n2->key );
}

/* ------------------------------------------------------------------------ */

docmd( cmd, n )
{
	static	TREE	*root = NULL;
	LEAF		*p, *p2;
	
	switch( cmd )
	{
	case 'd':
		if( !delete(&root, (LEAF *) n, dcmp ) )
			fprintf(stderr, "Node NOT in tree\n");
		break;

	case 'f':
		if( p = find(root, (LEAF *) n, dcmp) )
			fprintf(stderr, "Node %d found\n", p->key);
		else
			fprintf(stderr, "Node NOT found\n");
		break;

	case 'i':
		if( !(p = talloc(sizeof(LEAF))) )
			fprintf(stderr, "Out of memory.\n:");
		else
		{
			p->key = n;
			if( p2 = insert(&root, p, icmp) )
			{
				fprintf(stderr, "%d already in tree\n", p2->key);
				tfree( p );
			}
		}
		break;

	case 'a':
		freeall ( &root );
		break;

	case 'q':
		exit(0);
	}

	tprint( root, prnt, stdout );
	printf("\n");
}

/* ------------------------------------------------------------------------ */

main(argc, argv)
char **argv;
{
	/* Assemble a tree, first get commands from the command line
	 * until these are exhausted, then get commands from the
	 * keyboard.
	 */

	char	buf[128];

	for( ++argc; --argc > 0; ++argv )
		docmd( **argv, atoi(*argv + 1) );

	printf("commands are: iN -insert node N into tree\n");
	printf("              dN -delete node N\n");
	printf("              fN -find   node N\n");
	printf("              a  -delete the entire tree\n");
	printf("              q  -quit\n");
	
	for(; gets(buf); printf("i/d/f/a/q: ") )
		docmd( *buf, atoi(buf+1) );
}
