#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "fibheap.h"

typedef struct {
	char payload[32];
	fbhn_t fbhn;
} entry_t;

entry_t *new_entry(fbh_t *fbh, int pri, char *payload)
{
	entry_t *e = malloc(sizeof(entry_t));
	strcpy(e->payload, payload);
	fbh_insert(fbh, e, pri);
	return e;
}

void print_subtree(fbh_t *fbh, fbhn_t *root, int ind)
{
	fbhn_t *n = root;

	if (n == NULL)
		return;

	do {
		int i;
		entry_t *e = fbh_n2o(fbh, n);
		for(i = 0; i < ind; i++) fputc(' ', stdout);
		printf("%ld %s (parent=%ld) %s\n", n->pri, e->payload, n->parent != NULL ? n->parent->pri : -1, fbh->min == n ? "*":"");
		print_subtree(fbh, n->child, ind+1);
		n = n->right;
	} while(n != root);
}

void print_tree(fbh_t *fbh, const char *title)
{
	printf("%s:\n", title);
	print_subtree(fbh, fbh->min, 1);
}

int main()
{
	int r, n;
	fbh_t fbh;
	entry_t *e;

/*	printf("size, offs: %d %d\n", sizeof(fbhn_t), offsetof(entry_t, fbhn)); */

	r = fbh_init(&fbh, offsetof(entry_t, fbhn));
	assert(r == 0);

	e = fbh_min(&fbh);
	assert(e == NULL);

	for(n = 0; n < 8; n++) {
		char tmp[32];
		int pri = rand() % 10;
		sprintf(tmp, "{%04d}", pri);
		printf("add: %d %s\n", pri, tmp);
		e = new_entry(&fbh, pri, tmp);
		assert(e != NULL);
	}

	print_tree(&fbh, "pre");

	e = fbh_min(&fbh);
	assert(e != NULL);
	printf("\nmin: %ld %s\n", e->fbhn.pri, e->payload);

	printf("\npop min:\n");
	while(fbh.num_nodes > 0) {
		e = fbh_pop_min(&fbh);
		assert(e != NULL);
		printf("-> %ld %s\n", e->fbhn.pri, e->payload);
	}

	return 0;
}
