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

struct node {
    int key;
    struct node *left, *right;
};

static void insert(struct node **p, int key)
{
    while (*p)
        p = key < (*p)->key ? &(*p)->left : &(*p)->right;
    *p = malloc(sizeof(**p));
    if (!*p) {
        perror("malloc");
        exit(1);
    }
    (*p)->key = key;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

static void destroy(struct node *t)
{
    if (!t)
        return;
    destroy(t->left);
    destroy(t->right);
    free(t);
}

/* automaton: in-order walk, one key per step */
enum { max_depth = 64 };

struct walker {
    const struct node *stack[max_depth];
    int top;
};

static void push_left(struct walker *w, const struct node *t)
{
    for (; t && w->top < max_depth; t = t->left) {
        w->stack[w->top] = t;
        w->top++;
    }
}

static void walker_init(struct walker *w, const struct node *root)
{
    w->top = 0;
    push_left(w, root);
}

/* no side effects: only looks at the state */
static int walker_empty(const struct walker *w)
{
    return w->top == 0;
}

/* one step: returns the next key; call only if !walker_empty(w) */
static int walker_next(struct walker *w)
{
    const struct node *t;

    w->top--;
    t = w->stack[w->top];
    push_left(w, t->right);
    return t->key;
}

/* pretend a network client asks for a key */
static void serve_client(struct walker *w, const char *name)
{
    int key;

    if (walker_empty(w)) {
        printf("%s: no keys left\n", name);
        return;
    }
    key = walker_next(w);
    printf("%s gets key %d\n", name, key);
}

int main(void)
{
    int keys[] = { 50, 20, 70, 10, 30 };
    struct node *t = NULL;
    struct walker w;
    size_t i;

    for (i = 0; i < sizeof(keys) / sizeof(*keys); i++)
        insert(&t, keys[i]);
    walker_init(&w, t);
    serve_client(&w, "alice");
    printf("... other work, time passes ...\n");
    serve_client(&w, "bob");
    serve_client(&w, "carol");
    printf("... more work ...\n");
    for (i = 0; i < 3; i++)
        serve_client(&w, "dave");
    destroy(t);
    return 0;
}
