Index: libabac/Makefile.am
===================================================================
--- libabac/Makefile.am	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/Makefile.am	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,27 @@
+lib_LTLIBRARIES = libabac.la
+
+libabac_la_SOURCES = \
+    abac.c \
+    abac.h \
+    abac_list.c \
+    abac_list.h \
+    abac_graph.c \
+    abac_graph.h \
+    abac_role.c \
+    abac_set.c \
+    abac_set.h \
+    abac_util.c \
+    abac_util.h \
+    abac_verifier.c \
+    abac_verifier.h \
+    uthash.h \
+    utlist.h
+
+libabac_la_LDFLAGS = -version-info 1:0:1
+
+libabac_la_LIBADD = $(top_builddir)/src/libstrongswan/libstrongswan.la
+verifier.o :	$(top_builddir)/config.status
+
+INCLUDES = -I$(top_srcdir)/src/libstrongswan
+AM_CFLAGS = \
+	-DPLUGINS=\""${libstrongswan_plugins}\""
Index: libabac/abac.c
===================================================================
--- libabac/abac.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,207 @@
+#include <assert.h>
+#include <err.h>
+#include <glob.h>
+
+#include <chunk.h>
+
+#include "abac.h"
+#include "abac_graph.h"
+#include "abac_util.h"
+#include "abac_verifier.h"
+
+struct _abac_context_t {
+    abac_graph_t *graph;
+};
+
+/**
+ * Init the library.
+ */
+void libabac_init(void) {
+    abac_verifier_init();
+}
+
+/**
+ * Deinit the library.
+ */
+void libabac_deinit(void) {
+    abac_verifier_deinit();
+}
+
+/**
+ * Create a new abac context.
+ */
+abac_context_t *abac_context_new(void) {
+    abac_context_t *ctx = abac_xmalloc(sizeof(abac_context_t));
+    ctx->graph = abac_graph_new();
+    return ctx;
+}
+
+/**
+ * Deep copy an abac context.
+ */
+abac_context_t *abac_context_dup(abac_context_t *ctx) {
+    assert(ctx != NULL);
+
+    abac_context_t *dup = abac_xmalloc(sizeof(abac_context_t));
+    dup->graph = abac_graph_dup(ctx->graph);
+
+    return dup;
+}
+
+/**
+ * Free an abac context.
+ */
+void abac_context_free(abac_context_t *ctx) {
+    assert(ctx != NULL);
+
+    abac_graph_free(ctx->graph);
+    free(ctx);
+}
+
+/**
+ * Load an ID cert from a file.
+ */
+int abac_context_load_id_file(abac_context_t *ctx, char *filename) {
+    assert(ctx != NULL); assert(filename != NULL);
+    return abac_verifier_load_id_file(filename);
+}
+
+/**
+ * Load an ID cert from a chunk.
+ */
+int abac_context_load_id_chunk(abac_context_t *ctx, abac_chunk_t cert) {
+    assert(ctx != NULL);
+    chunk_t cert_chunk = { cert.ptr, cert.len };
+    return abac_verifier_load_id_chunk(cert_chunk);
+}
+
+/**
+ * Load an attribute cert from a file.
+ */
+int abac_context_load_attribute_file(abac_context_t *ctx, char *filename) {
+    int ret = 0;
+
+    assert(ctx != NULL); assert(filename != NULL);
+
+    abac_credential_t *cred = abac_verifier_load_attribute_cert_file(filename);
+    if (cred != NULL) {
+        ret = abac_graph_add_credential(ctx->graph, cred);
+        abac_credential_free(cred);
+    }
+
+    return ret;
+}
+
+/**
+ * Load an attribute cert from a chunk.
+ */
+int abac_context_load_attribute_chunk(abac_context_t *ctx, abac_chunk_t cert) {
+    assert(ctx != NULL);
+
+    chunk_t cert_chunk = { cert.ptr, cert.len };
+    abac_credential_t *cred = abac_verifier_load_attribute_cert_chunk(cert_chunk);
+    if (cred != NULL)
+        return abac_graph_add_credential(ctx->graph, cred);
+    else
+        return 0;
+}
+
+#define ID_PAT "/*_ID.der"
+#define ATTR_PAT "/*_attr.der"
+
+/**
+ * Load a directory full of certs.
+ */
+void abac_context_load_directory(abac_context_t *ctx, char *path) {
+    char *glob_pat;
+    glob_t glob_buf;
+    int i, ret;
+
+    assert(ctx != NULL); assert(path != NULL);
+
+    int dirlen = strlen(path);
+    glob_pat = abac_xmalloc(dirlen + sizeof(ATTR_PAT));
+    memcpy(glob_pat, path, dirlen);
+
+    // first load ID certs
+    memcpy(glob_pat + dirlen, ID_PAT, sizeof(ID_PAT));
+    glob(glob_pat, 0, NULL, &glob_buf); // TODO check for error
+    for (i = 0; i < glob_buf.gl_pathc; ++i) {
+        char *cert_file = glob_buf.gl_pathv[i];
+
+        ret = abac_context_load_id_file(ctx, cert_file);
+        if (!ret)
+            warnx("Couldn't load ID cert %s\n", cert_file);
+    }
+    globfree(&glob_buf);
+
+    // then load attr certs
+    memcpy(glob_pat + dirlen, ATTR_PAT, sizeof(ATTR_PAT));
+    glob(glob_pat, 0, NULL, &glob_buf); // TODO check for error
+    for (i = 0; i < glob_buf.gl_pathc; ++i) {
+        char *cert_file = glob_buf.gl_pathv[i];
+
+        ret = abac_context_load_attribute_file(ctx, cert_file);
+        if (!ret)
+            warnx("Couldn't load attribute cert %s\n", cert_file);
+    }
+    globfree(&glob_buf);
+
+    free(glob_pat);
+}
+
+/**
+ * Run a query on the data in an abac context. Returns a NULL-terminated array
+ * of abac_credential_t.
+ */
+abac_credential_t **abac_context_query(abac_context_t *ctx, char *role, char *principal, int *success) {
+    abac_credential_t **credentials = NULL, *cur;
+    int i = 0;
+
+    assert(ctx != NULL); assert(role != NULL); assert(principal != NULL); assert(success != NULL);
+
+    abac_graph_t *result_graph = abac_graph_query(ctx->graph, role, principal);
+    abac_list_t *result = abac_graph_credentials(result_graph);
+
+    abac_graph_free(result_graph);
+
+    int size = abac_list_size(result);
+    if (size > 0)
+        *success = 1;
+
+    // if there is no actual path, return everything that can reach the role
+    else {
+        *success = 0;
+        abac_list_free(result);
+
+        result = abac_graph_postorder_credentials(ctx->graph, role);
+        size = abac_list_size(result);
+    }
+
+    if (size > 0) {
+        // make the array (leave space to NULL terminate it)
+        credentials = abac_xmalloc(sizeof(abac_credential_t *) * (size + 1));
+        abac_list_foreach(result, cur,
+            credentials[i++] = cur;
+        );
+        credentials[i] = NULL;
+    }
+
+    abac_list_free(result);
+
+    return credentials;
+}
+
+/**
+ * Frees the result of an abac query.
+ */
+void abac_context_query_free(abac_credential_t **credentials) {
+    int i;
+
+    if (credentials == NULL)
+        return;
+
+    for (i = 0; credentials[i] != NULL; ++i)
+        abac_credential_free(credentials[i]);
+    free(credentials);
+}
Index: libabac/abac.h
===================================================================
--- libabac/abac.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,73 @@
+#ifndef __ABAC_H__
+#define __ABAC_H__
+
+typedef struct _abac_context_t abac_context_t;
+typedef struct _abac_credential_t abac_credential_t;
+typedef struct _abac_role_t abac_role_t;
+
+typedef struct _abac_chunk_t {
+    unsigned char *ptr;
+    int len;
+} abac_chunk_t;
+
+/*
+ * Init/deinit the library.
+ */
+void libabac_init(void);
+void libabac_deinit(void);
+
+/*
+ * ABAC functions, operating on an ABAC context.
+ */
+abac_context_t *abac_context_new(void);
+abac_context_t *abac_context_dup(abac_context_t *ctx);
+void abac_context_free(abac_context_t *ctx);
+
+/* each of these returns a bool */
+int abac_context_load_id_file(abac_context_t *ctx, char *filename);
+int abac_context_load_id_chunk(abac_context_t *ctx, abac_chunk_t cert);
+int abac_context_load_attribute_file(abac_context_t *ctx, char *filename);
+int abac_context_load_attribute_chunk(abac_context_t *ctx, abac_chunk_t cert);
+
+/* load an entire directory full of certs */
+void abac_context_load_directory(abac_context_t *ctx, char *path);
+
+/* abac query, returns a NULL-terminated array of credentials on success, NULL on fail */
+abac_credential_t **abac_context_query(abac_context_t *ctx, char *role, char *principal, int *success);
+void abac_context_query_free(abac_credential_t **credentials);
+
+/*
+ * Operations on credentials
+ */
+abac_role_t *abac_credential_head(abac_credential_t *cred);
+abac_role_t *abac_credential_tail(abac_credential_t *cred);
+abac_chunk_t abac_credential_attribute_cert(abac_credential_t *cred);
+abac_chunk_t abac_credential_issuer_cert(abac_credential_t *cred);
+
+abac_credential_t *abac_credential_dup(abac_credential_t *cred);
+void abac_credential_free(abac_credential_t *cred);
+
+/*
+ * Operations on roles.
+ */
+abac_role_t *abac_role_principal_new(char *principal);
+abac_role_t *abac_role_role_new(char *principal, char *abac_role_name);
+abac_role_t *abac_role_linking_new(char *principal, char *linked_role, char *abac_role_name);
+
+void abac_role_free(abac_role_t *role);
+
+abac_role_t *abac_role_from_string(char *string);
+abac_role_t *abac_role_dup(abac_role_t *role);
+
+int abac_role_is_principal(abac_role_t *role);
+int abac_role_is_role(abac_role_t *role);
+int abac_role_is_linking(abac_role_t *role);
+
+char *abac_role_string(abac_role_t *role);
+char *abac_role_linked_role(abac_role_t *role);
+char *abac_role_role_name(abac_role_t *role);
+char *abac_role_principal(abac_role_t *role);
+
+char *abac_role_attr_key(abac_role_t *head_role, abac_role_t *tail_role);
+
+#endif /* __ABAC_H__ */
Index: libabac/abac.hh
===================================================================
--- libabac/abac.hh	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac.hh	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,102 @@
+#ifndef __ABAC_HH__
+#define __ABAC_HH__
+
+#include <string>
+#include <vector>
+
+namespace ABAC {
+    extern "C" {
+        #include "abac.h"
+    }
+
+    class Role {
+        public:
+            Role() : m_role(NULL) { } // do not use: here for swig
+            Role(abac_role_t *role) { m_role = abac_role_dup(role); }
+            Role(char *role_name) { m_role = abac_role_from_string(role_name); }
+            Role(const Role &role) { m_role = abac_role_dup(role.m_role); }
+            ~Role() { abac_role_free(m_role); }
+
+            bool is_principal() const { return abac_role_is_principal(m_role); }
+            bool is_role() const { return abac_role_is_role(m_role); }
+            bool is_linking() const { return abac_role_is_linking(m_role); }
+
+            char *string() const { return abac_role_string(m_role); }
+            char *linked_role() const { return abac_role_linked_role(m_role); }
+            char *role_name() const { return abac_role_role_name(m_role); }
+            char *principal() const { return abac_role_principal(m_role); }
+
+        private:
+            abac_role_t *m_role;
+    };
+
+    class Credential {
+        public:
+            Credential() : m_cred(NULL) { } // do not use: here for swig
+            Credential(abac_credential_t *cred) :
+                m_head(abac_credential_head(cred)),
+                m_tail(abac_credential_tail(cred)),
+                m_cred(abac_credential_dup(cred))
+                    { }
+            Credential(const Credential &cred) :
+                m_head(cred.m_head),
+                m_tail(cred.m_tail),
+                m_cred(abac_credential_dup(cred.m_cred))
+                    { }
+            ~Credential() { abac_credential_free(m_cred); }
+
+            const Role &head() { return m_head; }
+            const Role &tail() { return m_tail; }
+            abac_chunk_t attribute_cert() { return abac_credential_attribute_cert(m_cred); }
+            abac_chunk_t issuer_cert() { return abac_credential_issuer_cert(m_cred); }
+        
+        private:
+            abac_credential_t *m_cred;
+            Role m_head, m_tail;
+    };
+
+    class Context {
+        public:
+            Context() { m_ctx = abac_context_new(); }
+            Context(const Context &context) { m_ctx = abac_context_dup(context.m_ctx); }
+            ~Context() { abac_context_free(m_ctx); }
+
+            /* each of these returns a bool */
+            int load_id_file(char *filename) { return abac_context_load_id_file(m_ctx, filename); }
+            int load_id_chunk(abac_chunk_t cert) { return abac_context_load_id_chunk(m_ctx, cert); }
+            int load_attribute_file(char *filename) { return abac_context_load_attribute_file(m_ctx, filename); }
+            int load_attribute_chunk(abac_chunk_t cert) { return abac_context_load_attribute_chunk(m_ctx, cert); }
+
+            /* load an entire directory full of certs */
+            void load_directory(char *path) { abac_context_load_directory(m_ctx, path); }
+
+            /* abac query, returns a vector of credentials on success, NULL on fail */
+            std::vector<Credential> query(char *role, char *principal, bool &success) {
+                abac_credential_t **query, **start, **end;
+                int i, success_int;
+
+                query = abac_context_query(m_ctx, role, principal, &success_int);
+                success = success_int;
+
+                if (query == NULL)
+                    return std::vector<Credential>();
+
+                for (i = 0; query[i] != NULL; ++i)
+                    ;
+
+                start = query;
+                end = &query[i];
+
+                std::vector<Credential> credentials = std::vector<Credential>(start, end);
+
+                abac_context_query_free(start);
+
+                return credentials;
+            }
+
+        private:
+            abac_context_t *m_ctx;
+    };
+}
+
+#endif /* __ABAC_HH__ */
Index: libabac/abac_graph.c
===================================================================
--- libabac/abac_graph.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_graph.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,408 @@
+#include <assert.h>
+#include <stdlib.h>
+
+#include "abac_graph.h"
+
+#include "abac_set.h"
+#include "abac_util.h"
+
+#include "uthash.h"
+
+// vertex
+struct _abac_vertex_t {
+    abac_role_t *role;
+    char *name;
+
+    abac_list_t *edges;
+
+    UT_hash_handle hh;
+};
+
+// edge
+typedef struct _abac_edge_t {
+    abac_vertex_t *vertex;
+    abac_credential_t *credential;
+} abac_edge_t;
+
+// derived edge
+typedef struct _abac_derived_key_t {
+    abac_vertex_t *head;
+    abac_edge_t *tail;
+} abac_derived_key_t;
+
+typedef struct _abac_derived_t {
+    abac_derived_key_t key;
+    UT_hash_handle hh;
+} abac_derived_t;
+
+// graph
+struct _abac_graph_t {
+    abac_vertex_t *vertices;
+    abac_derived_t *derived;
+    int dirty;
+};
+
+/**
+ * Create a new graph.
+ */
+abac_graph_t *abac_graph_new(void) {
+    abac_graph_t *graph = abac_xmalloc(sizeof(abac_graph_t));
+
+    graph->vertices = NULL;
+    graph->derived = NULL;
+    graph->dirty = 0;
+
+    return graph;
+}
+
+/**
+ * Deep copy a graph.
+ */
+abac_graph_t *abac_graph_dup(abac_graph_t *graph) {
+    abac_vertex_t *vertex;
+    abac_edge_t *edge;
+
+    abac_graph_t *clone = abac_graph_new();
+
+    // copy the vertices edge by edge
+    for (vertex = graph->vertices; vertex != NULL; vertex = vertex->hh.next)
+        abac_list_foreach(vertex->edges, edge,
+            // only copy non-derived edges
+            if (edge->credential != NULL)
+                abac_graph_add_credential(clone, edge->credential);
+        );
+
+    return clone;
+}
+
+/**
+ * Add a vertex to the graph. Should only be called by abac_graph_add_credential.
+ */
+static abac_vertex_t *_get_vertex(abac_graph_t *graph, abac_role_t *role) {
+    abac_vertex_t *vertex;
+    char *string;
+    
+    string = abac_role_string(role);
+    HASH_FIND_STR(graph->vertices, string, vertex);
+
+    // add the vertex if it doesn't exist
+    if (vertex == NULL) {
+        vertex = abac_xmalloc(sizeof(abac_vertex_t));
+        vertex->role = abac_role_dup(role);
+        vertex->name = abac_role_string(vertex->role);
+
+        // create the list of edges
+        vertex->edges = abac_list_new();
+
+        // add it to the vertices
+        HASH_ADD_KEYPTR(hh, graph->vertices, vertex->name, strlen(vertex->name), vertex);
+    }
+
+    return vertex;
+}
+
+/**
+ * Add a credential to the credential graph.
+ */
+int abac_graph_add_credential(abac_graph_t *graph, abac_credential_t *cred) {
+    abac_vertex_t *head_vertex, *tail_vertex;
+
+    assert(cred != NULL);
+
+    abac_role_t *head = abac_credential_head(cred);
+    abac_role_t *tail = abac_credential_tail(cred);
+
+    // a valid credential must have a role for the head
+    if (!abac_role_is_role(head)) return 0;
+
+    head_vertex = _get_vertex(graph, head);
+    tail_vertex = _get_vertex(graph, tail);
+
+    // create the edge and add it
+    abac_edge_t *edge = abac_xmalloc(sizeof(abac_edge_t));
+    edge->vertex = tail_vertex;
+    edge->credential = abac_credential_dup(cred);
+
+    abac_list_add(head_vertex->edges, edge);
+
+    // must re-derive edges
+    graph->dirty = 1;
+
+    return 1;
+}
+
+// find the principals that have a role
+static abac_set_t *_find_principals(abac_graph_t *graph, abac_vertex_t *start_vertex) {
+    abac_set_t *principals = abac_set_new();
+
+    abac_list_t *traversal = abac_graph_postorder(graph, start_vertex->role);
+    abac_vertex_t *vertex;
+
+    abac_list_foreach(traversal, vertex,
+        if (abac_role_is_principal(vertex->role))
+            abac_set_add(principals, abac_role_string(vertex->role));
+    );
+
+    abac_list_free(traversal);
+    return principals;
+}
+
+// remove any derived edges from the graph
+void _clear_derived(abac_graph_t *graph) {
+    abac_derived_t *current;
+
+    while (graph->derived) {
+        current = graph->derived;
+
+        HASH_DEL(graph->derived, current);
+
+        abac_vertex_t *head = current->key.head;
+        abac_edge_t *tail = current->key.tail;
+        assert(tail->credential == NULL);
+
+        // this can fail, but we assume the data structures are consistent
+        abac_list_remove(head->edges, tail);
+
+        free(current);
+        free(tail);
+    }
+}
+
+void abac_graph_derive_links(abac_graph_t *graph) {
+    abac_vertex_t *vertex;
+
+    if (!graph->dirty)
+        return;
+
+    for (vertex = graph->vertices; vertex != NULL; vertex = vertex->hh.next) {
+        // we only care about linking roles
+        if (!abac_role_is_linking(vertex->role))
+            continue;
+
+        // linking roles take the form A.r1.r2
+        char *A_r1 = abac_role_linked_role(vertex->role);
+        char *r2 = abac_role_role_name(vertex->role);
+
+        // find the linked role in the graph
+        abac_vertex_t *A_r1_vertex;
+        HASH_FIND_STR(graph->vertices, A_r1, A_r1_vertex);
+        if (A_r1_vertex == NULL)
+            continue;
+
+        // find the principals that have A.r1
+        abac_set_t *principals = _find_principals(graph, A_r1_vertex);
+        char *B;
+
+        abac_list_t *elts = abac_set_elements(principals);
+
+        // and add a link for each B.r2 to A.r1.r2
+        abac_list_foreach(elts, B,
+            int B_len = strlen(B);
+            int r2_len = strlen(r2);
+
+            // create the string B.r2, thx C
+            char *B_r2 = malloc(B_len + r2_len + 2);
+            memcpy(B_r2, B, B_len);
+            B_r2[B_len] = '.';
+            memcpy(B_r2 + B_len + 1, r2, r2_len);
+            B_r2[B_len + r2_len + 1] = 0;
+
+            abac_vertex_t *B_r2_vertex;
+            HASH_FIND_STR(graph->vertices, B_r2, B_r2_vertex);
+
+            // add an edge if the principal's granted it to someone
+            if (B_r2_vertex) {
+                debug_printf("adding edge from %s to %s\n", B_r2, abac_role_string(vertex->role));
+                abac_edge_t *edge = abac_xmalloc(sizeof(abac_edge_t));
+                edge->vertex = B_r2_vertex;
+                edge->credential = NULL;
+                abac_list_add(vertex->edges, edge);
+
+                // add to list of derived edges
+                abac_derived_t *derived = abac_xmalloc(sizeof(abac_derived_t));
+                derived->key.head = vertex;
+                derived->key.tail = edge;
+                HASH_ADD(hh, graph->derived, key, sizeof(abac_derived_key_t), derived);
+            }
+
+#ifdef DEBUG
+            debug_printf("    incoming edges for %s\n", abac_role_string(vertex->role));
+            abac_edge_t *cur;
+            abac_list_foreach(vertex->edges, cur,
+                debug_printf("        %s (%s)\n", abac_role_string(cur->vertex->role), cur->vertex->name);
+            );
+#endif
+
+            free(B_r2);
+        );
+
+        abac_list_free(elts);
+        abac_set_free(principals);
+    }
+
+    graph->dirty = 0;
+}
+
+static void _order_recurse(abac_vertex_t *vertex, abac_set_t *seen, int preorder, abac_list_t *stack) {
+    abac_edge_t *incoming;
+
+    // don't revisit nodes
+    if (!abac_set_add(seen, abac_role_string(vertex->role)))
+        return;
+
+    if (preorder)
+        abac_list_add(stack, vertex);
+
+    // recurse along the incoming vertices
+    abac_list_foreach(vertex->edges, incoming,
+        _order_recurse(incoming->vertex, seen, preorder, stack);
+    );
+
+    if (!preorder)
+        abac_list_add(stack, vertex);
+}
+
+static abac_list_t *_order(abac_graph_t *graph, abac_role_t *start, int preorder) {
+    debug_printf("%sorder at %s\n", preorder ? "pre" : "post", abac_role_string(start));
+
+    abac_vertex_t *start_vertex = _get_vertex(graph, start);
+    abac_set_t *seen = abac_set_new();
+
+    // create the return list
+    abac_list_t *stack = abac_list_new();
+
+    _order_recurse(start_vertex, seen, preorder, stack);
+
+    abac_set_free(seen);
+
+    return stack;
+}
+
+abac_list_t *abac_graph_postorder(abac_graph_t *graph, abac_role_t *start) {
+    return _order(graph, start, 0);
+}
+
+/**
+ * Postorder traverse the graph and return all the credentials within.
+ */
+abac_list_t *abac_graph_postorder_credentials(abac_graph_t *graph, char *start) {
+    abac_vertex_t *vertex;
+    abac_edge_t *incoming;
+
+    // get the postorder of vertices
+    abac_role_t *role = abac_role_from_string(start);
+    abac_list_t *order = abac_graph_postorder(graph, role);
+
+    // go through the list and dup all the credentials
+    abac_list_t *credentials = abac_list_new();
+    abac_list_foreach(order, vertex,
+        abac_list_foreach(vertex->edges, incoming,
+            if (incoming->credential != NULL)
+                abac_list_add(credentials, abac_credential_dup(incoming->credential));
+        );
+    );
+
+    abac_role_free(role);
+    abac_list_free(order);
+
+    return credentials;
+}
+
+static void _query(abac_graph_t *graph, char *role_name, char *principal, abac_graph_t *return_graph) {
+    abac_vertex_t *vertex;
+    abac_edge_t *incoming;
+
+    abac_role_t *role = abac_role_from_string(role_name);
+    abac_role_t *prin_role = abac_role_from_string(principal);
+
+    abac_set_t *on_path = abac_set_new();
+    abac_set_add(on_path, abac_role_string(prin_role));
+
+    abac_list_t *traversal = abac_graph_postorder(graph, role);
+    abac_list_foreach(traversal, vertex,
+        abac_role_t *role = vertex->role;
+
+        abac_list_foreach(vertex->edges, incoming,
+            abac_role_t *incoming_role = incoming->vertex->role;
+
+            if (!abac_set_contains(on_path, abac_role_string(incoming_role)))
+                continue;
+
+            abac_set_add(on_path, abac_role_string(role));
+
+            // add non-derived edges to the proof graph
+            if (!abac_role_is_linking(role))
+                abac_graph_add_credential(return_graph, incoming->credential);
+
+            // recursively find linked roles
+            else {
+                char *linked_role = abac_role_linked_role(role);
+                char *principal = abac_role_principal(incoming_role);
+
+                _query(graph, linked_role, principal, return_graph);
+            }
+        );
+    );
+
+    abac_list_free(traversal);
+    abac_set_free(on_path);
+    abac_role_free(role);
+    abac_role_free(prin_role);
+}
+
+abac_graph_t *abac_graph_query(abac_graph_t *graph, char *role, char *principal) {
+    abac_graph_derive_links(graph);
+
+    abac_graph_t *return_graph = abac_graph_new();
+    _query(graph, role, principal, return_graph);
+    abac_graph_derive_links(return_graph);
+    return return_graph;
+}
+
+/**
+ * Get all the credentials (attribute/issuer cert pairs) from the graph.
+ */
+abac_list_t *abac_graph_credentials(abac_graph_t *graph) {
+    abac_list_t *credentials = abac_list_new();
+
+    abac_vertex_t *vertex;
+
+    for (vertex = graph->vertices; vertex != NULL; vertex = vertex->hh.next) {
+        abac_edge_t *edge;
+        abac_list_foreach(vertex->edges, edge,
+            if (edge->credential != NULL)
+                abac_list_add(credentials, abac_credential_dup(edge->credential));
+        );
+    }
+
+    return credentials;
+}
+
+void abac_graph_free(abac_graph_t *graph) {
+    abac_vertex_t *vertex;
+    abac_edge_t *edge;
+
+    // kill derived edges
+    _clear_derived(graph);
+
+    // delete vertices
+    while ((vertex = graph->vertices) != NULL) {
+        HASH_DEL(graph->vertices, vertex);
+
+        abac_role_free(vertex->role);
+
+        abac_list_foreach(vertex->edges, edge,
+            if (edge->credential != NULL)
+                abac_credential_free(edge->credential);
+            free(edge);
+        );
+        abac_list_free(vertex->edges);
+        free(vertex);
+    }
+
+    free(graph);
+}
+
+abac_role_t *abac_vertex_role(abac_vertex_t *vertex) {
+    return vertex->role;
+}
Index: libabac/abac_graph.h
===================================================================
--- libabac/abac_graph.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_graph.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,23 @@
+#ifndef __GRAPH_H__
+#define __GRAPH_H__
+
+#include "abac.h"
+#include "abac_list.h"
+#include "abac_verifier.h"
+
+typedef struct _abac_graph_t abac_graph_t;
+typedef struct _abac_vertex_t abac_vertex_t;
+
+abac_graph_t *abac_graph_new(void);
+abac_graph_t *abac_graph_dup(abac_graph_t *graph);
+int abac_graph_add_credential(abac_graph_t *graph, abac_credential_t *cred);
+void abac_graph_derive_links(abac_graph_t *graph);
+abac_list_t *abac_graph_postorder(abac_graph_t *graph, abac_role_t *start);
+abac_list_t *abac_graph_postorder_credentials(abac_graph_t *graph, char *start);
+abac_graph_t *abac_graph_query(abac_graph_t *graph, char *role, char *principal);
+abac_list_t *abac_graph_credentials(abac_graph_t *graph);
+void abac_graph_free(abac_graph_t *graph);
+
+abac_role_t *abac_vertex_role(abac_vertex_t *vertex);
+
+#endif /* __GRAPH_H__ */
Index: libabac/abac_list.c
===================================================================
--- libabac/abac_list.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_list.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,53 @@
+#include <stdlib.h>
+
+#include "abac_list.h"
+#include "abac_util.h"
+
+abac_list_t *abac_list_new(void) {
+    abac_list_t *ret = abac_xmalloc(sizeof(abac_list_t));
+    ret->elts = NULL;
+    ret->size = 0;
+    return ret;
+}
+
+void abac_list_add(abac_list_t *list, void *elt) {
+    abac_list_element_t *new_element = abac_xmalloc(sizeof(abac_list_element_t));
+
+    new_element->ptr = elt;
+    DL_APPEND(list->elts, new_element);
+    ++list->size;
+}
+
+int abac_list_remove(abac_list_t *list, void *elt) {
+    abac_list_element_t *cur;
+
+    // iterate the list, remove the item if we find it
+    DL_FOREACH(list->elts, cur) {
+        if (cur->ptr == elt) {
+            DL_DELETE(list->elts, cur);
+            free(cur);
+            --list->size;
+            return 1;
+        }
+    }
+
+    // reutrn false if we don't
+    return 0;
+}
+
+int abac_list_size(abac_list_t *list) {
+    return list->size;
+}
+
+void abac_list_free(abac_list_t *list) {
+    abac_list_element_t *elt, *tmp;
+
+    // free everthing in the list
+    DL_FOREACH_SAFE(list->elts, elt, tmp) {
+        DL_DELETE(list->elts, elt);
+        free(elt);
+    }
+
+    // free the list
+    free(list);
+}
Index: libabac/abac_list.h
===================================================================
--- libabac/abac_list.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_list.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,33 @@
+#ifndef __LIST_H__
+#define __LIST_H__
+
+#include "utlist.h"
+
+typedef struct _abac_list_t abac_list_t;
+typedef struct _abac_list_element_t abac_list_element_t;
+
+struct _abac_list_element_t {
+    void *ptr;
+    abac_list_element_t *prev, *next;
+};
+
+struct _abac_list_t {
+    abac_list_element_t *elts;
+    int size;
+};
+
+abac_list_t *abac_list_new(void);
+void abac_list_add(abac_list_t *list, void *elt);
+int abac_list_remove(abac_list_t *list, void *elt);
+int abac_list_size(abac_list_t *list);
+void abac_list_free(abac_list_t *list);
+
+#define abac_list_foreach(LIST, CURRENT, BODY) do {  \
+    abac_list_element_t *_elt;                  \
+    DL_FOREACH(LIST->elts, _elt) {              \
+        CURRENT = (typeof(CURRENT))_elt->ptr;   \
+        BODY                                    \
+    }                                           \
+} while (0)
+
+#endif /* __LIST_H__ */
Index: libabac/abac_role.c
===================================================================
--- libabac/abac_role.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_role.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,289 @@
+#include <assert.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "abac.h"
+#include "abac_util.h"
+
+// typedef'd in role.h
+struct _abac_role_t {
+    char *principal;
+    char *linked_role;
+    char *abac_role_name;
+
+    char *string;
+    char *linked;
+};
+
+/**
+ * Create a new principal and initialize it.
+ */
+abac_role_t *abac_role_principal_new(char *principal) {
+    assert(principal != NULL);
+
+    abac_role_t *role;
+
+    if (strlen(principal) == 0)
+        return NULL;
+
+    role = abac_xmalloc(sizeof(abac_role_t));
+
+    role->principal = abac_xstrdup(principal);
+    role->abac_role_name = NULL;
+    role->linked_role = NULL;
+
+    role->string = abac_xstrdup(principal);
+    role->linked = NULL;
+
+    return role;
+}
+
+/**
+ * Create a new role and initialize it.
+ */
+abac_role_t *abac_role_role_new(char *principal, char *abac_role_name) {
+    assert(principal != NULL);
+    assert(abac_role_name != NULL);
+
+    abac_role_t *role;
+
+    if (strlen(principal) == 0 || strlen(abac_role_name) == 0)
+        return NULL;
+
+    role = abac_xmalloc(sizeof(abac_role_t));
+
+    role->principal = abac_xstrdup(principal);
+    role->abac_role_name = abac_xstrdup(abac_role_name);
+    role->linked_role = NULL;
+
+    int prin_len = strlen(principal);
+    int abac_role_len = strlen(abac_role_name);
+
+    role->string = abac_xmalloc(prin_len + 1 + abac_role_len + 1);
+    memcpy(role->string, principal, prin_len);
+    role->string[prin_len] = '.';
+    memcpy(role->string + prin_len + 1, abac_role_name, abac_role_len);
+    role->string[prin_len + 1 + abac_role_len] = 0;
+
+    role->linked = NULL;
+
+    return role;
+}
+
+/**
+ * Created a new linking role and initialize it.
+ */
+abac_role_t *abac_role_linking_new(char *principal, char *linked, char *abac_role_name) {
+    assert(principal != NULL);
+    assert(linked != NULL);
+    assert(abac_role_name != NULL);
+
+    abac_role_t *role;
+
+    if (strlen(principal) == 0 || strlen(linked) == 0 || strlen(abac_role_name) == 0)
+        return NULL;
+
+    role = abac_xmalloc(sizeof(abac_role_t));
+
+    role->principal = abac_xstrdup(principal);
+    role->linked_role = abac_xstrdup(linked);
+    role->abac_role_name = abac_xstrdup(abac_role_name);
+
+    int prin_len = strlen(principal);
+    int link_len = strlen(linked);
+    int abac_role_len = strlen(abac_role_name);
+
+    role->string = abac_xmalloc(prin_len + 1 + link_len + 1 + abac_role_len + 1);
+
+    memcpy(role->string, principal, prin_len);
+    role->string[prin_len] = '.';
+    memcpy(role->string + prin_len + 1, linked, link_len);
+    role->string[prin_len + 1 + link_len] = 0;
+
+    // hack: linked role is first two parts of full string
+    role->linked = abac_xstrdup(role->string);
+
+    role->string[prin_len + 1 + link_len] = '.';
+    memcpy(role->string + prin_len + 1 + link_len + 1, abac_role_name, abac_role_len);
+    role->string[prin_len + 1 + link_len + 1 + abac_role_len] = 0;
+
+    return role;
+}
+
+/**
+ * Free the memory used by a role.
+ */
+void abac_role_free(abac_role_t *role) {
+    if (role == NULL)
+        return;
+
+    free(role->principal);
+    free(role->linked_role);
+    free(role->abac_role_name);
+
+    free(role->string);
+    free(role->linked);
+
+    free(role);
+}
+
+/**
+ * Create a role from a string. Handles principals, roles, and linking roles.
+ */
+abac_role_t *abac_role_from_string(char *string) {
+    int num_dots = 0;
+    char *dot = string;
+
+    // count the dots
+    while ((dot = strchr(dot, '.')) != NULL) {
+        ++num_dots;
+        ++dot;
+    }
+
+    // no dots: easy case, principal
+    if (num_dots == 0)
+        return abac_role_principal_new(string);
+
+    abac_role_t *ret = NULL;
+
+    // make a copy so we can mess with it
+    string = abac_xstrdup(string);
+
+    // a role has exactly 1 dot
+    if (num_dots == 1) {
+        char *principal = string;
+
+        // terminate the principal part
+        dot = strchr(principal, '.');
+        *dot = 0;
+
+        // role name comes after the dot
+        char *abac_role_name = dot + 1;
+
+        // create the role (if possible)
+        ret = abac_role_role_new(string, abac_role_name);
+    }
+
+    // a linked role has 2 dots
+    else if (num_dots == 2) {
+        char *principal = string;
+
+        // terminate the principal part
+        dot = strchr(principal, '.');
+        *dot = 0;
+
+        // linked name is next, terminate it
+        char *linked = dot + 1;
+        dot = strchr(linked, '.');
+        *dot = 0;
+
+        // role name is last, already terminated
+        char *abac_role_name = dot + 1;
+
+        ret = abac_role_linking_new(principal, linked, abac_role_name);
+    }
+
+    // more than two dots: return NULL
+
+    free(string);
+
+    return ret;
+}
+
+/**
+ * Duplicate a role.
+ */
+abac_role_t *abac_role_dup(abac_role_t *role) {
+    abac_role_t *ret = abac_xmalloc(sizeof(abac_role_t));
+
+    ret->principal = abac_xstrdup(role->principal);
+    ret->linked_role = abac_xstrdup(role->linked_role);
+    ret->abac_role_name = abac_xstrdup(role->abac_role_name);
+
+    ret->string = abac_xstrdup(role->string);
+    ret->linked = abac_xstrdup(role->linked);
+
+    return ret;
+}
+
+/**
+ * True if a role is a principal.
+ */
+int abac_role_is_principal(abac_role_t *role) {
+    assert(role != NULL);
+    return role->abac_role_name == NULL && role->linked_role == NULL;
+}
+
+/**
+ * True if a role is a role.
+ */
+int abac_role_is_role(abac_role_t *role) {
+    assert(role != NULL);
+    return role->abac_role_name != NULL && role->linked_role == NULL; 
+}
+
+/**
+ * True if a role is a linked role.
+ */
+int abac_role_is_linking(abac_role_t *role) {
+    assert(role != NULL);
+    return role->linked_role != NULL;
+}
+
+/**
+ * Returns the string representation of the role.
+ */
+char *abac_role_string(abac_role_t *role) {
+    assert(role != NULL);
+    return role->string;
+}
+
+/**
+ * Returns the name of a role. If the role is A.r1 then return r1. If the role
+ * is A.r1.r2 then return r2.
+ */
+char *abac_role_role_name(abac_role_t *role) {
+    assert(role != NULL);
+    return role->abac_role_name;
+}
+
+/**
+ * Returns the linked part of a linking role. For instance, if the role is
+ * A.r1.r2, this returns A.r1.
+ */
+char *abac_role_linked_role(abac_role_t *role) {
+    assert(role != NULL);
+    return role->linked;
+}
+
+/**
+ * Returns the principal part of a role. The stuff before the first dot.
+ */
+char *abac_role_principal(abac_role_t *role) {
+    assert(role != NULL);
+    return role->principal;
+}
+
+/**
+ * Build an attribute key from head and tail roles. Static.
+ */
+#define ROLE_SEPARATOR " <- "
+char *abac_role_attr_key(abac_role_t *head_role, abac_role_t *tail_role) {
+    char *head = abac_role_string(head_role);
+    int head_len = strlen(head);
+
+    char *tail = abac_role_string(tail_role);
+    int tail_len = strlen(tail);
+
+    int sep_len = sizeof(ROLE_SEPARATOR) - 1;
+
+    // "head <- tail"
+    char *ret = abac_xmalloc(head_len + tail_len + sep_len + 1);
+    memcpy(ret, head, head_len);
+    memcpy(ret + head_len, ROLE_SEPARATOR, sep_len);
+    memcpy(ret + head_len + sep_len, tail, tail_len);
+    ret[head_len + sep_len + tail_len] = 0;
+
+    return ret;
+}
Index: libabac/abac_set.c
===================================================================
--- libabac/abac_set.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_set.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,80 @@
+#include <stdlib.h>
+
+#include "abac_set.h"
+#include "abac_util.h"
+
+#include "uthash.h"
+
+typedef struct _abac_set_element_t {
+    char *key;
+    UT_hash_handle hh;
+} abac_set_element_t;
+
+struct _abac_set_t {
+    abac_set_element_t *elts;
+};
+
+/**
+ * Create a new struct.
+ */
+abac_set_t *abac_set_new(void) {
+    abac_set_t *ret = abac_xmalloc(sizeof(abac_set_t));
+    ret->elts = NULL;
+    return ret;
+}
+
+/**
+ * Add an item to the set, returns true if it doesn't exist.
+ */
+int abac_set_add(abac_set_t *set, char *value) {
+    abac_set_element_t *elt;
+
+    HASH_FIND_STR(set->elts, value, elt);
+    if (elt) return 0; // already exists
+
+    elt = abac_xmalloc(sizeof(abac_set_element_t));
+    elt->key = abac_xstrdup(value);
+    HASH_ADD_KEYPTR(hh, set->elts, elt->key, strlen(elt->key), elt);
+
+    return 1;
+}
+
+/**
+ * Does the set contain the value.
+ */
+int abac_set_contains(abac_set_t *set, char *value) {
+    abac_set_element_t *elt;
+
+    HASH_FIND_STR(set->elts, value, elt);
+    return elt != NULL;
+}
+
+/**
+ * Return a list of the set's elements.
+ */
+abac_list_t *abac_set_elements(abac_set_t *set) {
+    abac_set_element_t *elt;
+    abac_list_t *ret = abac_list_new();
+
+    for (elt = set->elts; elt != NULL; elt = elt->hh.next) {
+        char *next = elt->key;
+        abac_list_add(ret, next);
+    }
+
+    return ret;
+}
+
+/**
+ * Destroy a set.
+ */
+void abac_set_free(abac_set_t *set) {
+    abac_set_element_t *elt;
+
+    while ((elt = set->elts) != NULL) {
+        HASH_DEL(set->elts, elt);
+        free(elt->key);
+        free(elt);
+    }
+
+    free(set);
+}
Index: libabac/abac_set.h
===================================================================
--- libabac/abac_set.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_set.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,14 @@
+#ifndef __SET_H__
+#define __SET_H__
+
+#include "abac_list.h"
+
+typedef struct _abac_set_t abac_set_t;
+
+abac_set_t *abac_set_new(void);
+int abac_set_add(abac_set_t *set, char *value);
+int abac_set_contains(abac_set_t *set, char *value);
+abac_list_t *abac_set_elements(abac_set_t *set);
+void abac_set_free(abac_set_t *set);
+
+#endif /* __SET_H__ */
Index: libabac/abac_util.c
===================================================================
--- libabac/abac_util.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_util.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,32 @@
+#include <err.h>
+#include <stdlib.h>
+#include <string.h>
+
+/**
+ * Malloc, fatal on error.
+ */
+void *abac_xmalloc(size_t size) {
+    void *ret;
+    
+    ret = malloc(size);
+    if (ret == NULL)
+        err(1, "malloc");
+
+    return ret;
+}
+
+/**
+ * strdup fatal on error
+ */
+char *abac_xstrdup(char *source) {
+    char *ret;
+
+    if (source == NULL)
+        return NULL;
+
+    ret = strdup(source);
+    if (ret == NULL)
+        err(1, "strdup");
+
+    return ret;
+}
Index: libabac/abac_util.h
===================================================================
--- libabac/abac_util.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_util.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,15 @@
+#ifndef __UTIL_H__
+#define __UTTL_H__
+
+#include <sys/types.h>
+
+void *abac_xmalloc(size_t);
+char *abac_xstrdup(char *);
+
+#ifdef DEBUG
+#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
+#else
+#define debug_printf(...) do { } while (0)
+#endif
+
+#endif /* __UTIL_H__ */
Index: libabac/abac_verifier.c
===================================================================
--- libabac/abac_verifier.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_verifier.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,311 @@
+#include <assert.h>
+
+#include <library.h>
+#include <credentials/certificates/certificate.h>
+#include <credentials/certificates/x509.h>
+#include <credentials/certificates/ac.h>
+
+#include "abac_verifier.h"
+
+#include "abac_util.h"
+
+typedef struct _abac_id_cert_t {
+    char *keyid;
+    certificate_t *cert;
+
+    UT_hash_handle hh;
+} abac_id_cert_t;
+
+struct _abac_credential_t {
+    abac_role_t *head;
+    abac_role_t *tail;
+    certificate_t *cert;
+    certificate_t *issuer;
+};
+
+abac_id_cert_t *id_certs = NULL;
+
+// convert a chunk to a lowercase binary string
+// malloc's the string
+static char *_chunk_to_string(chunk_t chunk) {
+    int i;
+
+    char *ret = abac_xmalloc(chunk.len * 2 + 1);
+
+    for (i = 0; i < chunk.len; ++i)
+        sprintf(ret + 2 * i, "%02x", chunk.ptr[i]);
+
+    return ret;
+}
+
+// verify that cert was issued by issuer
+// cert and issuer can be the same, in which case the self-sig is validated
+static int _verify_cert(certificate_t *issuer, certificate_t *cert) {
+    // XXX make sure this checks signature
+    if (cert->issued_by(cert, issuer))
+        if (cert->get_validity(cert, NULL, NULL, NULL))
+            return 1;
+    return 0;
+}
+
+/**
+ * Init the verifier subsystem.
+ */
+void abac_verifier_init(void) {
+    atexit(library_deinit);
+
+    if (!library_init(NULL))
+        exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
+
+    if (!lib->plugins->load(lib->plugins, NULL,
+            lib->settings->get_str(lib->settings, "pki.load", PLUGINS)))
+        exit(SS_RC_INITIALIZATION_FAILED);
+}
+
+/**
+ * Uninitialize the system, free up any allocated memory.
+ */
+void abac_verifier_deinit(void) {
+    abac_id_cert_t *id;
+
+    while ((id = id_certs) != NULL) {
+        HASH_DEL(id_certs, id);
+
+        free(id->keyid);
+        id->cert->destroy(id->cert);
+        free(id);
+    }
+}
+
+/**
+ * Load an ID certificate.
+ */
+static int _load_id(certificate_t *cert) {
+    public_key_t *public = NULL;
+    char *keyid = NULL;
+    chunk_t id;
+    int ret;
+
+    assert(cert != NULL);
+
+    // get the cert's pub key
+    public = cert->get_public_key(cert);
+    if (public == NULL) goto error;
+
+    // get the pubkey's fingerprint
+    ret = public->get_fingerprint(
+        public,
+        KEY_ID_PUBKEY_INFO_SHA1, &id
+    );
+    if (!ret) goto error;
+
+    // validate sig
+    ret = _verify_cert(cert, cert);
+    if (!ret) goto error;
+
+    keyid = _chunk_to_string(id);
+
+    // success, add the key to the map of certificates
+    abac_id_cert_t *id_cert = abac_xmalloc(sizeof(abac_id_cert_t));
+    id_cert->keyid = keyid;
+    id_cert->cert = cert;
+    HASH_ADD_KEYPTR(hh, id_certs, id_cert->keyid, strlen(id_cert->keyid), id_cert);
+
+    public->destroy(public);
+
+    return 1;
+
+error:
+    if (public != NULL) public->destroy(public);
+
+    return 0;
+}
+
+/**
+ * Load an ID cert from a file.
+ */
+int abac_verifier_load_id_file(char *filename) {
+    // load the cert
+    certificate_t *cert = lib->creds->create(
+        lib->creds, CRED_CERTIFICATE, CERT_X509,
+        BUILD_FROM_FILE, filename,
+        BUILD_X509_FLAG, X509_AA, // attribute authority, dumb
+        BUILD_END
+    );
+    if (cert == NULL)
+        return 0;
+    return _load_id(cert);
+}
+
+/**
+ * Load an ID cert from a chunk.
+ */
+int abac_verifier_load_id_chunk(chunk_t chunk) {
+    // load the cert
+    certificate_t *cert = lib->creds->create(
+        lib->creds, CRED_CERTIFICATE, CERT_X509,
+        BUILD_BLOB_ASN1_DER, chunk,
+        BUILD_X509_FLAG, X509_AA, // attribute authority, dumb
+        BUILD_END
+    );
+    if (cert == NULL)
+        return 0;
+    return _load_id(cert);
+}
+
+/**
+ * Load an attribute cert.
+ * Returns true only if the certificate is valid and is issued by the proper
+ * authority.
+ */
+static abac_credential_t *_load_attribute_cert(certificate_t *cert) {
+    ietf_attributes_t *attr_cert = NULL;
+    abac_role_t *head_role = NULL;
+    abac_role_t *tail_role = NULL;
+    abac_id_cert_t *issuer;
+    int ret;
+
+    // get the attr
+    ac_t *ac = (ac_t *)cert;
+    attr_cert = ac->get_groups(ac);
+    if (attr_cert == NULL) goto error;
+
+    char *attr_string = attr_cert->get_string(attr_cert);
+    if (attr_string == NULL) goto error;
+
+    // split into head/tail parts
+    char head[256], tail[256];
+    ret = sscanf(attr_string, "%255s <- %255s", head, tail);
+    if (ret != 2) goto error;
+
+    // must be a role
+    head_role = abac_role_from_string(head);
+    if (head_role == NULL) goto error;
+    if (!abac_role_is_role(head_role)) goto error;
+
+    // make sure the tail role is valid
+    tail_role = abac_role_from_string(tail);
+    if (tail_role == NULL) goto error;
+
+    // get the issuer based on keyid
+    char *principal = abac_role_principal(head_role);
+    HASH_FIND_STR(id_certs, principal, issuer);
+    if (issuer == NULL) goto error;
+
+    // make sure the issuer's signed it
+    ret = _verify_cert(issuer->cert, cert);
+    if (!ret) goto error;
+
+    // at this point we know we have a good attribute cert
+    abac_credential_t *cred = abac_xmalloc(sizeof(abac_credential_t));
+    cred->head = head_role;
+    cred->tail = tail_role;
+    cred->cert = cert;
+    cred->issuer = issuer->cert->get_ref(issuer->cert);
+
+    // free up some crap
+    attr_cert->destroy(attr_cert);
+
+    return cred;
+
+error:
+    if (cert != NULL) cert->destroy(cert);
+    if (attr_cert != NULL) attr_cert->destroy(attr_cert);
+    if (head_role != NULL) abac_role_free(head_role);
+    if (tail_role != NULL) abac_role_free(tail_role);
+
+    return NULL;
+}
+
+/**
+ * Load an attribute cert from a file.
+ */
+abac_credential_t *abac_verifier_load_attribute_cert_file(char *filename) {
+    // load the cert
+    certificate_t *cert = lib->creds->create(
+        lib->creds, CRED_CERTIFICATE, CERT_X509_AC,
+        BUILD_FROM_FILE, filename,
+        BUILD_END
+    );
+    if (cert == NULL)
+        return NULL;
+    return _load_attribute_cert(cert);
+}
+
+/**
+ * Load an attribute cert from a chunk.
+ */
+abac_credential_t *abac_verifier_load_attribute_cert_chunk(chunk_t chunk) {
+    // load the cert
+    certificate_t *cert = lib->creds->create(
+        lib->creds, CRED_CERTIFICATE, CERT_X509_AC,
+        BUILD_BLOB_ASN1_DER, chunk,
+        BUILD_END
+    );
+    if (cert == NULL)
+        return NULL;
+    return _load_attribute_cert(cert);
+}
+
+/**
+ * Return the head role.
+ */
+abac_role_t *abac_credential_head(abac_credential_t *cred) {
+    return cred->head;
+}
+
+/**
+ * Return the tail role.
+ */
+abac_role_t *abac_credential_tail(abac_credential_t *cred) {
+    return cred->tail;
+}
+
+/**
+ * Return the encoding of the attribute cert.
+ */
+abac_chunk_t abac_credential_attribute_cert(abac_credential_t *cred) {
+    chunk_t encoding = cred->cert->get_encoding(cred->cert);
+    abac_chunk_t ret = { encoding.ptr, encoding.len };
+    return ret;
+}
+
+/**
+ * Return the encoding of the issuer cert.
+ */
+abac_chunk_t abac_credential_issuer_cert(abac_credential_t *cred) {
+    chunk_t encoding = cred->issuer->get_encoding(cred->issuer);
+    abac_chunk_t ret = { encoding.ptr, encoding.len };
+    return ret;
+}
+
+/**
+ * Copy a credential.
+ */
+abac_credential_t *abac_credential_dup(abac_credential_t *cred) {
+    assert(cred != NULL);
+
+    abac_credential_t *clone = abac_xmalloc(sizeof(abac_credential_t));
+
+    clone->head = abac_role_dup(cred->head);
+    clone->tail = abac_role_dup(cred->tail);
+    clone->cert = cred->cert->get_ref(cred->cert);
+    clone->issuer = cred->issuer->get_ref(cred->issuer);
+
+    return clone;
+}
+
+/**
+ * Free a credential.
+ */
+void abac_credential_free(abac_credential_t *cred) {
+    if (cred == NULL)
+        return;
+
+    abac_role_free(cred->head);
+    abac_role_free(cred->tail);
+    cred->cert->destroy(cred->cert);
+    cred->issuer->destroy(cred->issuer); // reference counted
+
+    free(cred);
+}
Index: libabac/abac_verifier.h
===================================================================
--- libabac/abac_verifier.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/abac_verifier.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,18 @@
+#ifndef __VERIFIER_H__
+#define __VERIFIER_H__
+
+#include <chunk.h>
+
+#include "abac.h"
+
+#include "uthash.h"
+
+void abac_verifier_init(void);
+void abac_verifier_deinit(void);
+
+int abac_verifier_load_id_file(char *filename);
+int abac_verifier_load_id_chunk(chunk_t chunk);
+abac_credential_t *abac_verifier_load_attribute_cert_file(char *filename);
+abac_credential_t *abac_verifier_load_attribute_cert_chunk(chunk_t chunk);
+
+#endif /* __VERIFIER_H__ */
Index: libabac/prover.c
===================================================================
--- libabac/prover.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/prover.c	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,46 @@
+#include <err.h>
+#include <stdio.h>
+
+#include "abac.h"
+#include "abac_util.h"
+
+int main(int argc, char **argv) {
+    int i, success;
+    abac_credential_t *cred;
+
+    if (argc < 2)
+        errx(1, "Usage: %s <keystore>", argv[0]);
+
+    libabac_init();
+
+    abac_context_t *ctx = abac_context_new();
+    abac_context_load_directory(ctx, argv[1]);
+
+    debug_printf("querying\n");
+
+    abac_credential_t **credentials = abac_context_query(ctx,
+        "3f1aca4c5911b345d81c5f1a77675dce13249d0c.fed_create",
+        "5839d714b16bbe108642c5eb586c2173420bed19",
+        &success
+    );
+
+    if (success)
+        puts("success");
+
+    if (credentials != NULL)
+        for (i = 0; credentials[i] != NULL; ++i) {
+            cred = credentials[i];
+            printf("credential %s <- %s\n",
+                    abac_role_string(abac_credential_head(cred)),
+                    abac_role_string(abac_credential_tail(cred))
+                  );
+        }
+
+    abac_context_query_free(credentials);
+
+    abac_context_free(ctx);
+
+    libabac_deinit();
+
+    return 0;
+}
Index: libabac/prover.cc
===================================================================
--- libabac/prover.cc	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/prover.cc	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,44 @@
+#include <err.h>
+#include <stdio.h>
+#include <vector>
+
+#include "abac.hh"
+#include "abac_util.h"
+
+using namespace ABAC;
+using std::vector;
+
+int main(int argc, char **argv) {
+    int i;
+    abac_credential_t *cred;
+
+    if (argc < 2)
+        errx(1, "Usage: %s <keystore>", argv[0]);
+
+    libabac_init();
+
+    Context ctx;
+    ctx.load_directory(argv[1]);
+
+    debug_printf("querying\n");
+
+    bool success;
+    vector<Credential> credentials = ctx.query(
+        "3f1aca4c5911b345d81c5f1a77675dce13249d0c.fed_create",
+        "5839d714b16bbe108642c5eb586c2173420bed19",
+        success
+    );
+
+    if (success)
+        puts("success");
+    for (vector<Credential>::iterator i = credentials.begin(); i != credentials.end(); ++i) {
+        printf("credential %s <- %s\n",
+            i->head().string(),
+            i->tail().string()
+        );
+    }
+
+    libabac_deinit();
+
+    return 0;
+}
Index: libabac/uthash.h
===================================================================
--- libabac/uthash.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/uthash.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,960 @@
+/*
+Copyright (c) 2003-2010, Troy D. Hanson     http://uthash.sourceforge.net
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef UTHASH_H
+#define UTHASH_H 
+
+#include <string.h>   /* memcmp,strlen */
+#include <stddef.h>   /* ptrdiff_t */
+
+/* These macros use decltype or the earlier __typeof GNU extension.
+   As decltype is only available in newer compilers (VS2010 or gcc 4.3+
+   when compiling c++ source) this code uses whatever method is needed
+   or, for VS2008 where neither is available, uses casting workarounds. */
+#ifdef _MSC_VER         /* MS compiler */
+#if _MSC_VER >= 1600 && __cplusplus  /* VS2010 or newer in C++ mode */
+#define DECLTYPE(x) (decltype(x))
+#else                   /* VS2008 or older (or VS2010 in C mode) */
+#define NO_DECLTYPE
+#define DECLTYPE(x)
+#endif
+#else                   /* GNU, Sun and other compilers */
+#define DECLTYPE(x) (__typeof(x))
+#endif
+
+#ifdef NO_DECLTYPE
+#define DECLTYPE_ASSIGN(dst,src)                                                 \
+do {                                                                             \
+  char **_da_dst = (char**)(&(dst));                                             \
+  *_da_dst = (char*)(src);                                                       \
+} while(0)
+#else 
+#define DECLTYPE_ASSIGN(dst,src)                                                 \
+do {                                                                             \
+  (dst) = DECLTYPE(dst)(src);                                                    \
+} while(0)
+#endif
+
+/* a number of the hash function use uint32_t which isn't defined on win32 */
+#ifdef _MSC_VER
+typedef unsigned int uint32_t;
+#else
+#include <inttypes.h>   /* uint32_t */
+#endif
+
+#define UTHASH_VERSION 1.9.1
+
+#define uthash_fatal(msg) exit(-1)        /* fatal error (out of memory,etc) */
+#define uthash_malloc(sz) malloc(sz)      /* malloc fcn                      */
+#define uthash_free(ptr) free(ptr)        /* free fcn                        */
+
+#define uthash_noexpand_fyi(tbl)          /* can be defined to log noexpand  */
+#define uthash_expand_fyi(tbl)            /* can be defined to log expands   */
+
+/* initial number of buckets */
+#define HASH_INITIAL_NUM_BUCKETS 32      /* initial number of buckets        */
+#define HASH_INITIAL_NUM_BUCKETS_LOG2 5  /* lg2 of initial number of buckets */
+#define HASH_BKT_CAPACITY_THRESH 10      /* expand when bucket count reaches */
+
+/* calculate the element whose hash handle address is hhe */
+#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho)))
+
+#define HASH_FIND(hh,head,keyptr,keylen,out)                                     \
+do {                                                                             \
+  unsigned _hf_bkt,_hf_hashv;                                                    \
+  out=NULL;                                                                      \
+  if (head) {                                                                    \
+     HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt);   \
+     if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) {                           \
+       HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ],  \
+                        keyptr,keylen,out);                                      \
+     }                                                                           \
+  }                                                                              \
+} while (0)
+
+#ifdef HASH_BLOOM
+#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM)
+#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0)
+#define HASH_BLOOM_MAKE(tbl)                                                     \
+do {                                                                             \
+  (tbl)->bloom_nbits = HASH_BLOOM;                                               \
+  (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN);                 \
+  if (!((tbl)->bloom_bv))  { uthash_fatal( "out of memory"); }                   \
+  memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN);                                \
+  (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE;                                       \
+} while (0);
+
+#define HASH_BLOOM_FREE(tbl)                                                     \
+do {                                                                             \
+  uthash_free((tbl)->bloom_bv);                                                  \
+} while (0);
+
+#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8)))
+#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8)))
+
+#define HASH_BLOOM_ADD(tbl,hashv)                                                \
+  HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1)))
+
+#define HASH_BLOOM_TEST(tbl,hashv)                                               \
+  HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1)))
+
+#else
+#define HASH_BLOOM_MAKE(tbl) 
+#define HASH_BLOOM_FREE(tbl) 
+#define HASH_BLOOM_ADD(tbl,hashv) 
+#define HASH_BLOOM_TEST(tbl,hashv) (1)
+#endif
+
+#define HASH_MAKE_TABLE(hh,head)                                                 \
+do {                                                                             \
+  (head)->hh.tbl = (UT_hash_table*)uthash_malloc(                                \
+                  sizeof(UT_hash_table));                                        \
+  if (!((head)->hh.tbl))  { uthash_fatal( "out of memory"); }                    \
+  memset((head)->hh.tbl, 0, sizeof(UT_hash_table));                              \
+  (head)->hh.tbl->tail = &((head)->hh);                                          \
+  (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS;                        \
+  (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2;              \
+  (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head);                    \
+  (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc(                      \
+          HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket));               \
+  if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); }             \
+  memset((head)->hh.tbl->buckets, 0,                                             \
+          HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket));               \
+  HASH_BLOOM_MAKE((head)->hh.tbl);                                               \
+  (head)->hh.tbl->signature = HASH_SIGNATURE;                                    \
+} while(0)
+
+#define HASH_ADD(hh,head,fieldname,keylen_in,add)                                \
+        HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add)
+ 
+#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add)                            \
+do {                                                                             \
+ unsigned _ha_bkt;                                                               \
+ (add)->hh.next = NULL;                                                          \
+ (add)->hh.key = (char*)keyptr;                                                  \
+ (add)->hh.keylen = keylen_in;                                                   \
+ if (!(head)) {                                                                  \
+    head = (add);                                                                \
+    (head)->hh.prev = NULL;                                                      \
+    HASH_MAKE_TABLE(hh,head);                                                    \
+ } else {                                                                        \
+    (head)->hh.tbl->tail->next = (add);                                          \
+    (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail);         \
+    (head)->hh.tbl->tail = &((add)->hh);                                         \
+ }                                                                               \
+ (head)->hh.tbl->num_items++;                                                    \
+ (add)->hh.tbl = (head)->hh.tbl;                                                 \
+ HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets,                         \
+         (add)->hh.hashv, _ha_bkt);                                              \
+ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh);                   \
+ HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv);                                 \
+ HASH_EMIT_KEY(hh,head,keyptr,keylen_in);                                        \
+ HASH_FSCK(hh,head);                                                             \
+} while(0)
+
+#define HASH_TO_BKT( hashv, num_bkts, bkt )                                      \
+do {                                                                             \
+  bkt = ((hashv) & ((num_bkts) - 1));                                            \
+} while(0)
+
+/* delete "delptr" from the hash table.
+ * "the usual" patch-up process for the app-order doubly-linked-list.
+ * The use of _hd_hh_del below deserves special explanation.
+ * These used to be expressed using (delptr) but that led to a bug
+ * if someone used the same symbol for the head and deletee, like
+ *  HASH_DELETE(hh,users,users);
+ * We want that to work, but by changing the head (users) below
+ * we were forfeiting our ability to further refer to the deletee (users)
+ * in the patch-up process. Solution: use scratch space to
+ * copy the deletee pointer, then the latter references are via that
+ * scratch pointer rather than through the repointed (users) symbol.
+ */
+#define HASH_DELETE(hh,head,delptr)                                              \
+do {                                                                             \
+    unsigned _hd_bkt;                                                            \
+    struct UT_hash_handle *_hd_hh_del;                                           \
+    if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) )  {         \
+        uthash_free((head)->hh.tbl->buckets );                                   \
+        HASH_BLOOM_FREE((head)->hh.tbl);                                         \
+        uthash_free((head)->hh.tbl);                                             \
+        head = NULL;                                                             \
+    } else {                                                                     \
+        _hd_hh_del = &((delptr)->hh);                                            \
+        if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) {     \
+            (head)->hh.tbl->tail =                                               \
+                (UT_hash_handle*)((char*)((delptr)->hh.prev) +                   \
+                (head)->hh.tbl->hho);                                            \
+        }                                                                        \
+        if ((delptr)->hh.prev) {                                                 \
+            ((UT_hash_handle*)((char*)((delptr)->hh.prev) +                      \
+                    (head)->hh.tbl->hho))->next = (delptr)->hh.next;             \
+        } else {                                                                 \
+            DECLTYPE_ASSIGN(head,(delptr)->hh.next);                             \
+        }                                                                        \
+        if (_hd_hh_del->next) {                                                  \
+            ((UT_hash_handle*)((char*)_hd_hh_del->next +                         \
+                    (head)->hh.tbl->hho))->prev =                                \
+                    _hd_hh_del->prev;                                            \
+        }                                                                        \
+        HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt);   \
+        HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del);        \
+        (head)->hh.tbl->num_items--;                                             \
+    }                                                                            \
+    HASH_FSCK(hh,head);                                                          \
+} while (0)
+
+
+/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */
+#define HASH_FIND_STR(head,findstr,out)                                          \
+    HASH_FIND(hh,head,findstr,strlen(findstr),out)
+#define HASH_ADD_STR(head,strfield,add)                                          \
+    HASH_ADD(hh,head,strfield,strlen(add->strfield),add)
+#define HASH_FIND_INT(head,findint,out)                                          \
+    HASH_FIND(hh,head,findint,sizeof(int),out)
+#define HASH_ADD_INT(head,intfield,add)                                          \
+    HASH_ADD(hh,head,intfield,sizeof(int),add)
+#define HASH_FIND_PTR(head,findptr,out)                                          \
+    HASH_FIND(hh,head,findptr,sizeof(void *),out)
+#define HASH_ADD_PTR(head,ptrfield,add)                                          \
+    HASH_ADD(hh,head,ptrfield,sizeof(void *),add)
+#define HASH_DEL(head,delptr)                                                    \
+    HASH_DELETE(hh,head,delptr)
+
+/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined.
+ * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined.
+ */
+#ifdef HASH_DEBUG
+#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0)
+#define HASH_FSCK(hh,head)                                                       \
+do {                                                                             \
+    unsigned _bkt_i;                                                             \
+    unsigned _count, _bkt_count;                                                 \
+    char *_prev;                                                                 \
+    struct UT_hash_handle *_thh;                                                 \
+    if (head) {                                                                  \
+        _count = 0;                                                              \
+        for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) {       \
+            _bkt_count = 0;                                                      \
+            _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head;                      \
+            _prev = NULL;                                                        \
+            while (_thh) {                                                       \
+               if (_prev != (char*)(_thh->hh_prev)) {                            \
+                   HASH_OOPS("invalid hh_prev %p, actual %p\n",                  \
+                    _thh->hh_prev, _prev );                                      \
+               }                                                                 \
+               _bkt_count++;                                                     \
+               _prev = (char*)(_thh);                                            \
+               _thh = _thh->hh_next;                                             \
+            }                                                                    \
+            _count += _bkt_count;                                                \
+            if ((head)->hh.tbl->buckets[_bkt_i].count !=  _bkt_count) {          \
+               HASH_OOPS("invalid bucket count %d, actual %d\n",                 \
+                (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count);              \
+            }                                                                    \
+        }                                                                        \
+        if (_count != (head)->hh.tbl->num_items) {                               \
+            HASH_OOPS("invalid hh item count %d, actual %d\n",                   \
+                (head)->hh.tbl->num_items, _count );                             \
+        }                                                                        \
+        /* traverse hh in app order; check next/prev integrity, count */         \
+        _count = 0;                                                              \
+        _prev = NULL;                                                            \
+        _thh =  &(head)->hh;                                                     \
+        while (_thh) {                                                           \
+           _count++;                                                             \
+           if (_prev !=(char*)(_thh->prev)) {                                    \
+              HASH_OOPS("invalid prev %p, actual %p\n",                          \
+                    _thh->prev, _prev );                                         \
+           }                                                                     \
+           _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh);                    \
+           _thh = ( _thh->next ?  (UT_hash_handle*)((char*)(_thh->next) +        \
+                                  (head)->hh.tbl->hho) : NULL );                 \
+        }                                                                        \
+        if (_count != (head)->hh.tbl->num_items) {                               \
+            HASH_OOPS("invalid app item count %d, actual %d\n",                  \
+                (head)->hh.tbl->num_items, _count );                             \
+        }                                                                        \
+    }                                                                            \
+} while (0)
+#else
+#define HASH_FSCK(hh,head) 
+#endif
+
+/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to 
+ * the descriptor to which this macro is defined for tuning the hash function.
+ * The app can #include <unistd.h> to get the prototype for write(2). */
+#ifdef HASH_EMIT_KEYS
+#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)                                   \
+do {                                                                             \
+    unsigned _klen = fieldlen;                                                   \
+    write(HASH_EMIT_KEYS, &_klen, sizeof(_klen));                                \
+    write(HASH_EMIT_KEYS, keyptr, fieldlen);                                     \
+} while (0)
+#else 
+#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)                    
+#endif
+
+/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */
+#ifdef HASH_FUNCTION 
+#define HASH_FCN HASH_FUNCTION
+#else
+#define HASH_FCN HASH_JEN
+#endif
+
+/* The Bernstein hash function, used in Perl prior to v5.6 */
+#define HASH_BER(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _hb_keylen=keylen;                                                    \
+  char *_hb_key=(char*)key;                                                      \
+  (hashv) = 0;                                                                   \
+  while (_hb_keylen--)  { (hashv) = ((hashv) * 33) + *_hb_key++; }               \
+  bkt = (hashv) & (num_bkts-1);                                                  \
+} while (0)
+
+
+/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at 
+ * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */
+#define HASH_SAX(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _sx_i;                                                                \
+  char *_hs_key=(char*)key;                                                      \
+  hashv = 0;                                                                     \
+  for(_sx_i=0; _sx_i < keylen; _sx_i++)                                          \
+      hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i];                     \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while (0)
+
+#define HASH_FNV(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _fn_i;                                                                \
+  char *_hf_key=(char*)key;                                                      \
+  hashv = 2166136261UL;                                                          \
+  for(_fn_i=0; _fn_i < keylen; _fn_i++)                                          \
+      hashv = (hashv * 16777619) ^ _hf_key[_fn_i];                               \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0);
+ 
+#define HASH_OAT(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _ho_i;                                                                \
+  char *_ho_key=(char*)key;                                                      \
+  hashv = 0;                                                                     \
+  for(_ho_i=0; _ho_i < keylen; _ho_i++) {                                        \
+      hashv += _ho_key[_ho_i];                                                   \
+      hashv += (hashv << 10);                                                    \
+      hashv ^= (hashv >> 6);                                                     \
+  }                                                                              \
+  hashv += (hashv << 3);                                                         \
+  hashv ^= (hashv >> 11);                                                        \
+  hashv += (hashv << 15);                                                        \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0)
+
+#define HASH_JEN_MIX(a,b,c)                                                      \
+do {                                                                             \
+  a -= b; a -= c; a ^= ( c >> 13 );                                              \
+  b -= c; b -= a; b ^= ( a << 8 );                                               \
+  c -= a; c -= b; c ^= ( b >> 13 );                                              \
+  a -= b; a -= c; a ^= ( c >> 12 );                                              \
+  b -= c; b -= a; b ^= ( a << 16 );                                              \
+  c -= a; c -= b; c ^= ( b >> 5 );                                               \
+  a -= b; a -= c; a ^= ( c >> 3 );                                               \
+  b -= c; b -= a; b ^= ( a << 10 );                                              \
+  c -= a; c -= b; c ^= ( b >> 15 );                                              \
+} while (0)
+
+#define HASH_JEN(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  unsigned _hj_i,_hj_j,_hj_k;                                                    \
+  char *_hj_key=(char*)key;                                                      \
+  hashv = 0xfeedbeef;                                                            \
+  _hj_i = _hj_j = 0x9e3779b9;                                                    \
+  _hj_k = keylen;                                                                \
+  while (_hj_k >= 12) {                                                          \
+    _hj_i +=    (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 )                      \
+        + ( (unsigned)_hj_key[2] << 16 )                                         \
+        + ( (unsigned)_hj_key[3] << 24 ) );                                      \
+    _hj_j +=    (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 )                      \
+        + ( (unsigned)_hj_key[6] << 16 )                                         \
+        + ( (unsigned)_hj_key[7] << 24 ) );                                      \
+    hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 )                         \
+        + ( (unsigned)_hj_key[10] << 16 )                                        \
+        + ( (unsigned)_hj_key[11] << 24 ) );                                     \
+                                                                                 \
+     HASH_JEN_MIX(_hj_i, _hj_j, hashv);                                          \
+                                                                                 \
+     _hj_key += 12;                                                              \
+     _hj_k -= 12;                                                                \
+  }                                                                              \
+  hashv += keylen;                                                               \
+  switch ( _hj_k ) {                                                             \
+     case 11: hashv += ( (unsigned)_hj_key[10] << 24 );                          \
+     case 10: hashv += ( (unsigned)_hj_key[9] << 16 );                           \
+     case 9:  hashv += ( (unsigned)_hj_key[8] << 8 );                            \
+     case 8:  _hj_j += ( (unsigned)_hj_key[7] << 24 );                           \
+     case 7:  _hj_j += ( (unsigned)_hj_key[6] << 16 );                           \
+     case 6:  _hj_j += ( (unsigned)_hj_key[5] << 8 );                            \
+     case 5:  _hj_j += _hj_key[4];                                               \
+     case 4:  _hj_i += ( (unsigned)_hj_key[3] << 24 );                           \
+     case 3:  _hj_i += ( (unsigned)_hj_key[2] << 16 );                           \
+     case 2:  _hj_i += ( (unsigned)_hj_key[1] << 8 );                            \
+     case 1:  _hj_i += _hj_key[0];                                               \
+  }                                                                              \
+  HASH_JEN_MIX(_hj_i, _hj_j, hashv);                                             \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0)
+
+/* The Paul Hsieh hash function */
+#undef get16bits
+#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__)             \
+  || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
+#define get16bits(d) (*((const uint16_t *) (d)))
+#endif
+
+#if !defined (get16bits)
+#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)             \
+                       +(uint32_t)(((const uint8_t *)(d))[0]) )
+#endif
+#define HASH_SFH(key,keylen,num_bkts,hashv,bkt)                                  \
+do {                                                                             \
+  char *_sfh_key=(char*)key;                                                     \
+  uint32_t _sfh_tmp, _sfh_len = keylen;                                          \
+                                                                                 \
+  int _sfh_rem = _sfh_len & 3;                                                   \
+  _sfh_len >>= 2;                                                                \
+  hashv = 0xcafebabe;                                                            \
+                                                                                 \
+  /* Main loop */                                                                \
+  for (;_sfh_len > 0; _sfh_len--) {                                              \
+    hashv    += get16bits (_sfh_key);                                            \
+    _sfh_tmp       = (get16bits (_sfh_key+2) << 11) ^ hashv;                     \
+    hashv     = (hashv << 16) ^ _sfh_tmp;                                        \
+    _sfh_key += 2*sizeof (uint16_t);                                             \
+    hashv    += hashv >> 11;                                                     \
+  }                                                                              \
+                                                                                 \
+  /* Handle end cases */                                                         \
+  switch (_sfh_rem) {                                                            \
+    case 3: hashv += get16bits (_sfh_key);                                       \
+            hashv ^= hashv << 16;                                                \
+            hashv ^= _sfh_key[sizeof (uint16_t)] << 18;                          \
+            hashv += hashv >> 11;                                                \
+            break;                                                               \
+    case 2: hashv += get16bits (_sfh_key);                                       \
+            hashv ^= hashv << 11;                                                \
+            hashv += hashv >> 17;                                                \
+            break;                                                               \
+    case 1: hashv += *_sfh_key;                                                  \
+            hashv ^= hashv << 10;                                                \
+            hashv += hashv >> 1;                                                 \
+  }                                                                              \
+                                                                                 \
+    /* Force "avalanching" of final 127 bits */                                  \
+    hashv ^= hashv << 3;                                                         \
+    hashv += hashv >> 5;                                                         \
+    hashv ^= hashv << 4;                                                         \
+    hashv += hashv >> 17;                                                        \
+    hashv ^= hashv << 25;                                                        \
+    hashv += hashv >> 6;                                                         \
+    bkt = hashv & (num_bkts-1);                                                  \
+} while(0);
+
+#ifdef HASH_USING_NO_STRICT_ALIASING
+/* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads.
+ * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error.
+ * So MurmurHash comes in two versions, the faster unaligned one and the slower
+ * aligned one. We only use the faster one on CPU's where we know it's safe. 
+ *
+ * Note the preprocessor built-in defines can be emitted using:
+ *
+ *   gcc -m64 -dM -E - < /dev/null                  (on gcc)
+ *   cc -## a.c (where a.c is a simple test file)   (Sun Studio)
+ */
+#if (defined(__i386__) || defined(__x86_64__)) 
+#define HASH_MUR HASH_MUR_UNALIGNED
+#else
+#define HASH_MUR HASH_MUR_ALIGNED
+#endif
+
+/* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */
+#define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt)                        \
+do {                                                                             \
+  const unsigned int _mur_m = 0x5bd1e995;                                        \
+  const int _mur_r = 24;                                                         \
+  hashv = 0xcafebabe ^ keylen;                                                   \
+  char *_mur_key = (char *)key;                                                  \
+  uint32_t _mur_tmp, _mur_len = keylen;                                          \
+                                                                                 \
+  for (;_mur_len >= 4; _mur_len-=4) {                                            \
+    _mur_tmp = *(uint32_t *)_mur_key;                                            \
+    _mur_tmp *= _mur_m;                                                          \
+    _mur_tmp ^= _mur_tmp >> _mur_r;                                              \
+    _mur_tmp *= _mur_m;                                                          \
+    hashv *= _mur_m;                                                             \
+    hashv ^= _mur_tmp;                                                           \
+    _mur_key += 4;                                                               \
+  }                                                                              \
+                                                                                 \
+  switch(_mur_len)                                                               \
+  {                                                                              \
+    case 3: hashv ^= _mur_key[2] << 16;                                          \
+    case 2: hashv ^= _mur_key[1] << 8;                                           \
+    case 1: hashv ^= _mur_key[0];                                                \
+            hashv *= _mur_m;                                                     \
+  };                                                                             \
+                                                                                 \
+  hashv ^= hashv >> 13;                                                          \
+  hashv *= _mur_m;                                                               \
+  hashv ^= hashv >> 15;                                                          \
+                                                                                 \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0)
+
+/* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */
+#define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt)                          \
+do {                                                                             \
+  const unsigned int _mur_m = 0x5bd1e995;                                        \
+  const int _mur_r = 24;                                                         \
+  hashv = 0xcafebabe ^ keylen;                                                   \
+  char *_mur_key = (char *)key;                                                  \
+  uint32_t _mur_len = keylen;                                                    \
+  int _mur_align = (int)_mur_key & 3;                                            \
+                                                                                 \
+  if (_mur_align && (_mur_len >= 4)) {                                           \
+    unsigned _mur_t = 0, _mur_d = 0;                                             \
+    switch(_mur_align) {                                                         \
+      case 1: _mur_t |= _mur_key[2] << 16;                                       \
+      case 2: _mur_t |= _mur_key[1] << 8;                                        \
+      case 3: _mur_t |= _mur_key[0];                                             \
+    }                                                                            \
+    _mur_t <<= (8 * _mur_align);                                                 \
+    _mur_key += 4-_mur_align;                                                    \
+    _mur_len -= 4-_mur_align;                                                    \
+    int _mur_sl = 8 * (4-_mur_align);                                            \
+    int _mur_sr = 8 * _mur_align;                                                \
+                                                                                 \
+    for (;_mur_len >= 4; _mur_len-=4) {                                          \
+      _mur_d = *(unsigned *)_mur_key;                                            \
+      _mur_t = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);                        \
+      unsigned _mur_k = _mur_t;                                                  \
+      _mur_k *= _mur_m;                                                          \
+      _mur_k ^= _mur_k >> _mur_r;                                                \
+      _mur_k *= _mur_m;                                                          \
+      hashv *= _mur_m;                                                           \
+      hashv ^= _mur_k;                                                           \
+      _mur_t = _mur_d;                                                           \
+      _mur_key += 4;                                                             \
+    }                                                                            \
+    _mur_d = 0;                                                                  \
+    if(_mur_len >= _mur_align) {                                                 \
+      switch(_mur_align) {                                                       \
+        case 3: _mur_d |= _mur_key[2] << 16;                                     \
+        case 2: _mur_d |= _mur_key[1] << 8;                                      \
+        case 1: _mur_d |= _mur_key[0];                                           \
+      }                                                                          \
+      unsigned _mur_k = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);               \
+      _mur_k *= _mur_m;                                                          \
+      _mur_k ^= _mur_k >> _mur_r;                                                \
+      _mur_k *= _mur_m;                                                          \
+      hashv *= _mur_m;                                                           \
+      hashv ^= _mur_k;                                                           \
+      _mur_k += _mur_align;                                                      \
+      _mur_len -= _mur_align;                                                    \
+                                                                                 \
+      switch(_mur_len)                                                           \
+      {                                                                          \
+        case 3: hashv ^= _mur_key[2] << 16;                                      \
+        case 2: hashv ^= _mur_key[1] << 8;                                       \
+        case 1: hashv ^= _mur_key[0];                                            \
+                hashv *= _mur_m;                                                 \
+      }                                                                          \
+    } else {                                                                     \
+      switch(_mur_len)                                                           \
+      {                                                                          \
+        case 3: _mur_d ^= _mur_key[2] << 16;                                     \
+        case 2: _mur_d ^= _mur_key[1] << 8;                                      \
+        case 1: _mur_d ^= _mur_key[0];                                           \
+        case 0: hashv ^= (_mur_t >> _mur_sr) | (_mur_d << _mur_sl);              \
+        hashv *= _mur_m;                                                         \
+      }                                                                          \
+    }                                                                            \
+                                                                                 \
+    hashv ^= hashv >> 13;                                                        \
+    hashv *= _mur_m;                                                             \
+    hashv ^= hashv >> 15;                                                        \
+  } else {                                                                       \
+    for (;_mur_len >= 4; _mur_len-=4) {                                          \
+      unsigned _mur_k = *(unsigned*)_mur_key;                                    \
+      _mur_k *= _mur_m;                                                          \
+      _mur_k ^= _mur_k >> _mur_r;                                                \
+      _mur_k *= _mur_m;                                                          \
+      hashv *= _mur_m;                                                           \
+      hashv ^= _mur_k;                                                           \
+      _mur_key += 4;                                                             \
+    }                                                                            \
+    switch(_mur_len)                                                             \
+    {                                                                            \
+      case 3: hashv ^= _mur_key[2] << 16;                                        \
+      case 2: hashv ^= _mur_key[1] << 8;                                         \
+      case 1: hashv ^= _mur_key[0];                                              \
+      hashv *= _mur_m;                                                           \
+    }                                                                            \
+                                                                                 \
+    hashv ^= hashv >> 13;                                                        \
+    hashv *= _mur_m;                                                             \
+    hashv ^= hashv >> 15;                                                        \
+  }                                                                              \
+  bkt = hashv & (num_bkts-1);                                                    \
+} while(0)
+#endif  /* HASH_USING_NO_STRICT_ALIASING */
+
+/* key comparison function; return 0 if keys equal */
+#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) 
+
+/* iterate over items in a known bucket to find desired item */
+#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out)                       \
+do {                                                                             \
+ if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head));          \
+ else out=NULL;                                                                  \
+ while (out) {                                                                   \
+    if (out->hh.keylen == keylen_in) {                                           \
+        if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break;             \
+    }                                                                            \
+    if (out->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,out->hh.hh_next)); \
+    else out = NULL;                                                             \
+ }                                                                               \
+} while(0)
+
+/* add an item to a bucket  */
+#define HASH_ADD_TO_BKT(head,addhh)                                              \
+do {                                                                             \
+ head.count++;                                                                   \
+ (addhh)->hh_next = head.hh_head;                                                \
+ (addhh)->hh_prev = NULL;                                                        \
+ if (head.hh_head) { (head).hh_head->hh_prev = (addhh); }                        \
+ (head).hh_head=addhh;                                                           \
+ if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH)             \
+     && (addhh)->tbl->noexpand != 1) {                                           \
+       HASH_EXPAND_BUCKETS((addhh)->tbl);                                        \
+ }                                                                               \
+} while(0)
+
+/* remove an item from a given bucket */
+#define HASH_DEL_IN_BKT(hh,head,hh_del)                                          \
+    (head).count--;                                                              \
+    if ((head).hh_head == hh_del) {                                              \
+      (head).hh_head = hh_del->hh_next;                                          \
+    }                                                                            \
+    if (hh_del->hh_prev) {                                                       \
+        hh_del->hh_prev->hh_next = hh_del->hh_next;                              \
+    }                                                                            \
+    if (hh_del->hh_next) {                                                       \
+        hh_del->hh_next->hh_prev = hh_del->hh_prev;                              \
+    }                                                                
+
+/* Bucket expansion has the effect of doubling the number of buckets
+ * and redistributing the items into the new buckets. Ideally the
+ * items will distribute more or less evenly into the new buckets
+ * (the extent to which this is true is a measure of the quality of
+ * the hash function as it applies to the key domain). 
+ * 
+ * With the items distributed into more buckets, the chain length
+ * (item count) in each bucket is reduced. Thus by expanding buckets
+ * the hash keeps a bound on the chain length. This bounded chain 
+ * length is the essence of how a hash provides constant time lookup.
+ * 
+ * The calculation of tbl->ideal_chain_maxlen below deserves some
+ * explanation. First, keep in mind that we're calculating the ideal
+ * maximum chain length based on the *new* (doubled) bucket count.
+ * In fractions this is just n/b (n=number of items,b=new num buckets).
+ * Since the ideal chain length is an integer, we want to calculate 
+ * ceil(n/b). We don't depend on floating point arithmetic in this
+ * hash, so to calculate ceil(n/b) with integers we could write
+ * 
+ *      ceil(n/b) = (n/b) + ((n%b)?1:0)
+ * 
+ * and in fact a previous version of this hash did just that.
+ * But now we have improved things a bit by recognizing that b is
+ * always a power of two. We keep its base 2 log handy (call it lb),
+ * so now we can write this with a bit shift and logical AND:
+ * 
+ *      ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0)
+ * 
+ */
+#define HASH_EXPAND_BUCKETS(tbl)                                                 \
+do {                                                                             \
+    unsigned _he_bkt;                                                            \
+    unsigned _he_bkt_i;                                                          \
+    struct UT_hash_handle *_he_thh, *_he_hh_nxt;                                 \
+    UT_hash_bucket *_he_new_buckets, *_he_newbkt;                                \
+    _he_new_buckets = (UT_hash_bucket*)uthash_malloc(                            \
+             2 * tbl->num_buckets * sizeof(struct UT_hash_bucket));              \
+    if (!_he_new_buckets) { uthash_fatal( "out of memory"); }                    \
+    memset(_he_new_buckets, 0,                                                   \
+            2 * tbl->num_buckets * sizeof(struct UT_hash_bucket));               \
+    tbl->ideal_chain_maxlen =                                                    \
+       (tbl->num_items >> (tbl->log2_num_buckets+1)) +                           \
+       ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0);                    \
+    tbl->nonideal_items = 0;                                                     \
+    for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++)                \
+    {                                                                            \
+        _he_thh = tbl->buckets[ _he_bkt_i ].hh_head;                             \
+        while (_he_thh) {                                                        \
+           _he_hh_nxt = _he_thh->hh_next;                                        \
+           HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt);            \
+           _he_newbkt = &(_he_new_buckets[ _he_bkt ]);                           \
+           if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) {                \
+             tbl->nonideal_items++;                                              \
+             _he_newbkt->expand_mult = _he_newbkt->count /                       \
+                                        tbl->ideal_chain_maxlen;                 \
+           }                                                                     \
+           _he_thh->hh_prev = NULL;                                              \
+           _he_thh->hh_next = _he_newbkt->hh_head;                               \
+           if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev =               \
+                _he_thh;                                                         \
+           _he_newbkt->hh_head = _he_thh;                                        \
+           _he_thh = _he_hh_nxt;                                                 \
+        }                                                                        \
+    }                                                                            \
+    tbl->num_buckets *= 2;                                                       \
+    tbl->log2_num_buckets++;                                                     \
+    uthash_free( tbl->buckets );                                                 \
+    tbl->buckets = _he_new_buckets;                                              \
+    tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ?         \
+        (tbl->ineff_expands+1) : 0;                                              \
+    if (tbl->ineff_expands > 1) {                                                \
+        tbl->noexpand=1;                                                         \
+        uthash_noexpand_fyi(tbl);                                                \
+    }                                                                            \
+    uthash_expand_fyi(tbl);                                                      \
+} while(0)
+
+
+/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */
+/* Note that HASH_SORT assumes the hash handle name to be hh. 
+ * HASH_SRT was added to allow the hash handle name to be passed in. */
+#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn)
+#define HASH_SRT(hh,head,cmpfcn)                                                 \
+do {                                                                             \
+  unsigned _hs_i;                                                                \
+  unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize;               \
+  struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail;            \
+  if (head) {                                                                    \
+      _hs_insize = 1;                                                            \
+      _hs_looping = 1;                                                           \
+      _hs_list = &((head)->hh);                                                  \
+      while (_hs_looping) {                                                      \
+          _hs_p = _hs_list;                                                      \
+          _hs_list = NULL;                                                       \
+          _hs_tail = NULL;                                                       \
+          _hs_nmerges = 0;                                                       \
+          while (_hs_p) {                                                        \
+              _hs_nmerges++;                                                     \
+              _hs_q = _hs_p;                                                     \
+              _hs_psize = 0;                                                     \
+              for ( _hs_i = 0; _hs_i  < _hs_insize; _hs_i++ ) {                  \
+                  _hs_psize++;                                                   \
+                  _hs_q = (UT_hash_handle*)((_hs_q->next) ?                      \
+                          ((void*)((char*)(_hs_q->next) +                        \
+                          (head)->hh.tbl->hho)) : NULL);                         \
+                  if (! (_hs_q) ) break;                                         \
+              }                                                                  \
+              _hs_qsize = _hs_insize;                                            \
+              while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) {           \
+                  if (_hs_psize == 0) {                                          \
+                      _hs_e = _hs_q;                                             \
+                      _hs_q = (UT_hash_handle*)((_hs_q->next) ?                  \
+                              ((void*)((char*)(_hs_q->next) +                    \
+                              (head)->hh.tbl->hho)) : NULL);                     \
+                      _hs_qsize--;                                               \
+                  } else if ( (_hs_qsize == 0) || !(_hs_q) ) {                   \
+                      _hs_e = _hs_p;                                             \
+                      _hs_p = (UT_hash_handle*)((_hs_p->next) ?                  \
+                              ((void*)((char*)(_hs_p->next) +                    \
+                              (head)->hh.tbl->hho)) : NULL);                     \
+                      _hs_psize--;                                               \
+                  } else if ((                                                   \
+                      cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \
+                             DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \
+                             ) <= 0) {                                           \
+                      _hs_e = _hs_p;                                             \
+                      _hs_p = (UT_hash_handle*)((_hs_p->next) ?                  \
+                              ((void*)((char*)(_hs_p->next) +                    \
+                              (head)->hh.tbl->hho)) : NULL);                     \
+                      _hs_psize--;                                               \
+                  } else {                                                       \
+                      _hs_e = _hs_q;                                             \
+                      _hs_q = (UT_hash_handle*)((_hs_q->next) ?                  \
+                              ((void*)((char*)(_hs_q->next) +                    \
+                              (head)->hh.tbl->hho)) : NULL);                     \
+                      _hs_qsize--;                                               \
+                  }                                                              \
+                  if ( _hs_tail ) {                                              \
+                      _hs_tail->next = ((_hs_e) ?                                \
+                            ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL);          \
+                  } else {                                                       \
+                      _hs_list = _hs_e;                                          \
+                  }                                                              \
+                  _hs_e->prev = ((_hs_tail) ?                                    \
+                     ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL);              \
+                  _hs_tail = _hs_e;                                              \
+              }                                                                  \
+              _hs_p = _hs_q;                                                     \
+          }                                                                      \
+          _hs_tail->next = NULL;                                                 \
+          if ( _hs_nmerges <= 1 ) {                                              \
+              _hs_looping=0;                                                     \
+              (head)->hh.tbl->tail = _hs_tail;                                   \
+              DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list));      \
+          }                                                                      \
+          _hs_insize *= 2;                                                       \
+      }                                                                          \
+      HASH_FSCK(hh,head);                                                        \
+ }                                                                               \
+} while (0)
+
+/* This function selects items from one hash into another hash. 
+ * The end result is that the selected items have dual presence 
+ * in both hashes. There is no copy of the items made; rather 
+ * they are added into the new hash through a secondary hash 
+ * hash handle that must be present in the structure. */
+#define HASH_SELECT(hh_dst, dst, hh_src, src, cond)                              \
+do {                                                                             \
+  unsigned _src_bkt, _dst_bkt;                                                   \
+  void *_last_elt=NULL, *_elt;                                                   \
+  UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL;                         \
+  ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst));                 \
+  if (src) {                                                                     \
+    for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) {     \
+      for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head;                \
+          _src_hh;                                                               \
+          _src_hh = _src_hh->hh_next) {                                          \
+          _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh);                       \
+          if (cond(_elt)) {                                                      \
+            _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho);               \
+            _dst_hh->key = _src_hh->key;                                         \
+            _dst_hh->keylen = _src_hh->keylen;                                   \
+            _dst_hh->hashv = _src_hh->hashv;                                     \
+            _dst_hh->prev = _last_elt;                                           \
+            _dst_hh->next = NULL;                                                \
+            if (_last_elt_hh) { _last_elt_hh->next = _elt; }                     \
+            if (!dst) {                                                          \
+              DECLTYPE_ASSIGN(dst,_elt);                                         \
+              HASH_MAKE_TABLE(hh_dst,dst);                                       \
+            } else {                                                             \
+              _dst_hh->tbl = (dst)->hh_dst.tbl;                                  \
+            }                                                                    \
+            HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt);    \
+            HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh);            \
+            (dst)->hh_dst.tbl->num_items++;                                      \
+            _last_elt = _elt;                                                    \
+            _last_elt_hh = _dst_hh;                                              \
+          }                                                                      \
+      }                                                                          \
+    }                                                                            \
+  }                                                                              \
+  HASH_FSCK(hh_dst,dst);                                                         \
+} while (0)
+
+#define HASH_CLEAR(hh,head)                                                      \
+do {                                                                             \
+  if (head) {                                                                    \
+    uthash_free((head)->hh.tbl->buckets );                                       \
+    uthash_free((head)->hh.tbl);                                                 \
+    (head)=NULL;                                                                 \
+  }                                                                              \
+} while(0)
+
+/* obtain a count of items in the hash */
+#define HASH_COUNT(head) HASH_CNT(hh,head) 
+#define HASH_CNT(hh,head) (head?(head->hh.tbl->num_items):0)
+
+typedef struct UT_hash_bucket {
+   struct UT_hash_handle *hh_head;
+   unsigned count;
+
+   /* expand_mult is normally set to 0. In this situation, the max chain length
+    * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If
+    * the bucket's chain exceeds this length, bucket expansion is triggered). 
+    * However, setting expand_mult to a non-zero value delays bucket expansion
+    * (that would be triggered by additions to this particular bucket)
+    * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH.
+    * (The multiplier is simply expand_mult+1). The whole idea of this
+    * multiplier is to reduce bucket expansions, since they are expensive, in
+    * situations where we know that a particular bucket tends to be overused.
+    * It is better to let its chain length grow to a longer yet-still-bounded
+    * value, than to do an O(n) bucket expansion too often. 
+    */
+   unsigned expand_mult;
+
+} UT_hash_bucket;
+
+/* random signature used only to find hash tables in external analysis */
+#define HASH_SIGNATURE 0xa0111fe1
+#define HASH_BLOOM_SIGNATURE 0xb12220f2
+
+typedef struct UT_hash_table {
+   UT_hash_bucket *buckets;
+   unsigned num_buckets, log2_num_buckets;
+   unsigned num_items;
+   struct UT_hash_handle *tail; /* tail hh in app order, for fast append    */
+   ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */
+
+   /* in an ideal situation (all buckets used equally), no bucket would have
+    * more than ceil(#items/#buckets) items. that's the ideal chain length. */
+   unsigned ideal_chain_maxlen;
+
+   /* nonideal_items is the number of items in the hash whose chain position
+    * exceeds the ideal chain maxlen. these items pay the penalty for an uneven
+    * hash distribution; reaching them in a chain traversal takes >ideal steps */
+   unsigned nonideal_items;
+
+   /* ineffective expands occur when a bucket doubling was performed, but 
+    * afterward, more than half the items in the hash had nonideal chain
+    * positions. If this happens on two consecutive expansions we inhibit any
+    * further expansion, as it's not helping; this happens when the hash
+    * function isn't a good fit for the key domain. When expansion is inhibited
+    * the hash will still work, albeit no longer in constant time. */
+   unsigned ineff_expands, noexpand;
+
+   uint32_t signature; /* used only to find hash tables in external analysis */
+#ifdef HASH_BLOOM
+   uint32_t bloom_sig; /* used only to test bloom exists in external analysis */
+   uint8_t *bloom_bv;
+   char bloom_nbits;
+#endif
+
+} UT_hash_table;
+
+typedef struct UT_hash_handle {
+   struct UT_hash_table *tbl;
+   void *prev;                       /* prev element in app order      */
+   void *next;                       /* next element in app order      */
+   struct UT_hash_handle *hh_prev;   /* previous hh in bucket order    */
+   struct UT_hash_handle *hh_next;   /* next hh in bucket order        */
+   void *key;                        /* ptr to enclosing struct's key  */
+   unsigned keylen;                  /* enclosing struct's key len     */
+   unsigned hashv;                   /* result of hash-fcn(key)        */
+} UT_hash_handle;
+
+#endif /* UTHASH_H */
Index: libabac/utlist.h
===================================================================
--- libabac/utlist.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
+++ libabac/utlist.h	(revision 15200beba77a0ea12f6dcaabfa529d03962d71fc)
@@ -0,0 +1,490 @@
+/*
+Copyright (c) 2007-2010, Troy D. Hanson   http://uthash.sourceforge.net
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef UTLIST_H
+#define UTLIST_H
+
+#define UTLIST_VERSION 1.9.1
+
+/* 
+ * This file contains macros to manipulate singly and doubly-linked lists.
+ *
+ * 1. LL_ macros:  singly-linked lists.
+ * 2. DL_ macros:  doubly-linked lists.
+ * 3. CDL_ macros: circular doubly-linked lists.
+ *
+ * To use singly-linked lists, your structure must have a "next" pointer.
+ * To use doubly-linked lists, your structure must "prev" and "next" pointers.
+ * Either way, the pointer to the head of the list must be initialized to NULL.
+ * 
+ * ----------------.EXAMPLE -------------------------
+ * struct item {
+ *      int id;
+ *      struct item *prev, *next;
+ * }
+ *
+ * struct item *list = NULL:
+ *
+ * int main() {
+ *      struct item *item;
+ *      ... allocate and populate item ...
+ *      DL_APPEND(list, item);
+ * }
+ * --------------------------------------------------
+ *
+ * For doubly-linked lists, the append and delete macros are O(1)
+ * For singly-linked lists, append and delete are O(n) but prepend is O(1)
+ * The sort macro is O(n log(n)) for all types of single/double/circular lists.
+ */
+
+/* These macros use decltype or the earlier __typeof GNU extension.
+   As decltype is only available in newer compilers (VS2010 or gcc 4.3+
+   when compiling c++ code), this code uses whatever method is needed
+   or, for VS2008 where neither is available, uses casting workarounds. */
+#ifdef _MSC_VER            /* MS compiler */
+#if _MSC_VER >= 1600 && __cplusplus  /* VS2010 and newer in C++ mode */
+#define LDECLTYPE(x) decltype(x)
+#else                     /* VS2008 or older (or VS2010 in C mode) */
+#define NO_DECLTYPE
+#define LDECLTYPE(x) char*
+#endif
+#else                      /* GNU, Sun and other compilers */
+#define LDECLTYPE(x) __typeof(x)
+#endif
+
+/* for VS2008 we use some workarounds to get around the lack of decltype,
+ * namely, we always reassign our tmp variable to the list head if we need
+ * to dereference its prev/next pointers, and save/restore the real head.*/
+#ifdef NO_DECLTYPE
+#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); }
+#define _NEXT(elt,list) ((char*)((list)->next))
+#define _NEXTASGN(elt,list,to) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); }
+#define _PREV(elt,list) ((char*)((list)->prev))
+#define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); }
+#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; }
+#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); }
+#else 
+#define _SV(elt,list)
+#define _NEXT(elt,list) ((elt)->next)
+#define _NEXTASGN(elt,list,to) ((elt)->next)=(to)
+#define _PREV(elt,list) ((elt)->prev)
+#define _PREVASGN(elt,list,to) ((elt)->prev)=(to)
+#define _RS(list)
+#define _CASTASGN(a,b) (a)=(b)
+#endif
+
+/******************************************************************************
+ * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort    *
+ * Unwieldy variable names used here to avoid shadowing passed-in variables.  *
+ *****************************************************************************/
+#define LL_SORT(list, cmp)                                                                     \
+do {                                                                                           \
+  LDECLTYPE(list) _ls_p;                                                                       \
+  LDECLTYPE(list) _ls_q;                                                                       \
+  LDECLTYPE(list) _ls_e;                                                                       \
+  LDECLTYPE(list) _ls_tail;                                                                    \
+  LDECLTYPE(list) _ls_oldhead;                                                                 \
+  LDECLTYPE(list) _tmp;                                                                        \
+  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
+  if (list) {                                                                                  \
+    _ls_insize = 1;                                                                            \
+    _ls_looping = 1;                                                                           \
+    while (_ls_looping) {                                                                      \
+      _CASTASGN(_ls_p,list);                                                                   \
+      _CASTASGN(_ls_oldhead,list);                                                             \
+      list = NULL;                                                                             \
+      _ls_tail = NULL;                                                                         \
+      _ls_nmerges = 0;                                                                         \
+      while (_ls_p) {                                                                          \
+        _ls_nmerges++;                                                                         \
+        _ls_q = _ls_p;                                                                         \
+        _ls_psize = 0;                                                                         \
+        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
+          _ls_psize++;                                                                         \
+          _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list);                               \
+          if (!_ls_q) break;                                                                   \
+        }                                                                                      \
+        _ls_qsize = _ls_insize;                                                                \
+        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
+          if (_ls_psize == 0) {                                                                \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+          } else {                                                                             \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+          }                                                                                    \
+          if (_ls_tail) {                                                                      \
+            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
+          } else {                                                                             \
+            _CASTASGN(list,_ls_e);                                                             \
+          }                                                                                    \
+          _ls_tail = _ls_e;                                                                    \
+        }                                                                                      \
+        _ls_p = _ls_q;                                                                         \
+      }                                                                                        \
+      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list);                            \
+      if (_ls_nmerges <= 1) {                                                                  \
+        _ls_looping=0;                                                                         \
+      }                                                                                        \
+      _ls_insize *= 2;                                                                         \
+    }                                                                                          \
+  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
+} while (0)
+
+#define DL_SORT(list, cmp)                                                                     \
+do {                                                                                           \
+  LDECLTYPE(list) _ls_p;                                                                       \
+  LDECLTYPE(list) _ls_q;                                                                       \
+  LDECLTYPE(list) _ls_e;                                                                       \
+  LDECLTYPE(list) _ls_tail;                                                                    \
+  LDECLTYPE(list) _ls_oldhead;                                                                 \
+  LDECLTYPE(list) _tmp;                                                                        \
+  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
+  if (list) {                                                                                  \
+    _ls_insize = 1;                                                                            \
+    _ls_looping = 1;                                                                           \
+    while (_ls_looping) {                                                                      \
+      _CASTASGN(_ls_p,list);                                                                   \
+      _CASTASGN(_ls_oldhead,list);                                                             \
+      list = NULL;                                                                             \
+      _ls_tail = NULL;                                                                         \
+      _ls_nmerges = 0;                                                                         \
+      while (_ls_p) {                                                                          \
+        _ls_nmerges++;                                                                         \
+        _ls_q = _ls_p;                                                                         \
+        _ls_psize = 0;                                                                         \
+        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
+          _ls_psize++;                                                                         \
+          _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list);                               \
+          if (!_ls_q) break;                                                                   \
+        }                                                                                      \
+        _ls_qsize = _ls_insize;                                                                \
+        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
+          if (_ls_psize == 0) {                                                                \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+          } else {                                                                             \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+          }                                                                                    \
+          if (_ls_tail) {                                                                      \
+            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
+          } else {                                                                             \
+            _CASTASGN(list,_ls_e);                                                             \
+          }                                                                                    \
+          _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list);                          \
+          _ls_tail = _ls_e;                                                                    \
+        }                                                                                      \
+        _ls_p = _ls_q;                                                                         \
+      }                                                                                        \
+      _CASTASGN(list->prev, _ls_tail);                                                         \
+      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list);                            \
+      if (_ls_nmerges <= 1) {                                                                  \
+        _ls_looping=0;                                                                         \
+      }                                                                                        \
+      _ls_insize *= 2;                                                                         \
+    }                                                                                          \
+  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
+} while (0)
+
+#define CDL_SORT(list, cmp)                                                                    \
+do {                                                                                           \
+  LDECLTYPE(list) _ls_p;                                                                       \
+  LDECLTYPE(list) _ls_q;                                                                       \
+  LDECLTYPE(list) _ls_e;                                                                       \
+  LDECLTYPE(list) _ls_tail;                                                                    \
+  LDECLTYPE(list) _ls_oldhead;                                                                 \
+  LDECLTYPE(list) _tmp;                                                                        \
+  LDECLTYPE(list) _tmp2;                                                                       \
+  int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping;                       \
+  if (list) {                                                                                  \
+    _ls_insize = 1;                                                                            \
+    _ls_looping = 1;                                                                           \
+    while (_ls_looping) {                                                                      \
+      _CASTASGN(_ls_p,list);                                                                   \
+      _CASTASGN(_ls_oldhead,list);                                                             \
+      list = NULL;                                                                             \
+      _ls_tail = NULL;                                                                         \
+      _ls_nmerges = 0;                                                                         \
+      while (_ls_p) {                                                                          \
+        _ls_nmerges++;                                                                         \
+        _ls_q = _ls_p;                                                                         \
+        _ls_psize = 0;                                                                         \
+        for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) {                                         \
+          _ls_psize++;                                                                         \
+          _SV(_ls_q,list);                                                                     \
+          if (_NEXT(_ls_q,list) == _ls_oldhead) {                                              \
+            _ls_q = NULL;                                                                      \
+          } else {                                                                             \
+            _ls_q = _NEXT(_ls_q,list);                                                         \
+          }                                                                                    \
+          _RS(list);                                                                           \
+          if (!_ls_q) break;                                                                   \
+        }                                                                                      \
+        _ls_qsize = _ls_insize;                                                                \
+        while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) {                                    \
+          if (_ls_psize == 0) {                                                                \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+            if (_ls_q == _ls_oldhead) { _ls_q = NULL; }                                        \
+          } else if (_ls_qsize == 0 || !_ls_q) {                                               \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+            if (_ls_p == _ls_oldhead) { _ls_p = NULL; }                                        \
+          } else if (cmp(_ls_p,_ls_q) <= 0) {                                                  \
+            _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \
+            if (_ls_p == _ls_oldhead) { _ls_p = NULL; }                                        \
+          } else {                                                                             \
+            _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \
+            if (_ls_q == _ls_oldhead) { _ls_q = NULL; }                                        \
+          }                                                                                    \
+          if (_ls_tail) {                                                                      \
+            _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list);                     \
+          } else {                                                                             \
+            _CASTASGN(list,_ls_e);                                                             \
+          }                                                                                    \
+          _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list);                          \
+          _ls_tail = _ls_e;                                                                    \
+        }                                                                                      \
+        _ls_p = _ls_q;                                                                         \
+      }                                                                                        \
+      _CASTASGN(list->prev,_ls_tail);                                                          \
+      _CASTASGN(_tmp2,list);                                                                   \
+      _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp2); _RS(list);                           \
+      if (_ls_nmerges <= 1) {                                                                  \
+        _ls_looping=0;                                                                         \
+      }                                                                                        \
+      _ls_insize *= 2;                                                                         \
+    }                                                                                          \
+  } else _tmp=NULL; /* quiet gcc unused variable warning */                                    \
+} while (0)
+
+/******************************************************************************
+ * singly linked list macros (non-circular)                                   *
+ *****************************************************************************/
+#define LL_PREPEND(head,add)                                                                   \
+do {                                                                                           \
+  (add)->next = head;                                                                          \
+  head = add;                                                                                  \
+} while (0)
+
+#define LL_APPEND(head,add)                                                                    \
+do {                                                                                           \
+  LDECLTYPE(head) _tmp;                                                                        \
+  (add)->next=NULL;                                                                            \
+  if (head) {                                                                                  \
+    _tmp = head;                                                                               \
+    while (_tmp->next) { _tmp = _tmp->next; }                                                  \
+    _tmp->next=(add);                                                                          \
+  } else {                                                                                     \
+    (head)=(add);                                                                              \
+  }                                                                                            \
+} while (0)
+
+#define LL_DELETE(head,del)                                                                    \
+do {                                                                                           \
+  LDECLTYPE(head) _tmp;                                                                        \
+  if ((head) == (del)) {                                                                       \
+    (head)=(head)->next;                                                                       \
+  } else {                                                                                     \
+    _tmp = head;                                                                               \
+    while (_tmp->next && (_tmp->next != (del))) {                                              \
+      _tmp = _tmp->next;                                                                       \
+    }                                                                                          \
+    if (_tmp->next) {                                                                          \
+      _tmp->next = ((del)->next);                                                              \
+    }                                                                                          \
+  }                                                                                            \
+} while (0)
+
+/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */
+#define LL_APPEND_VS2008(head,add)                                                             \
+do {                                                                                           \
+  if (head) {                                                                                  \
+    (add)->next = head;     /* use add->next as a temp variable */                             \
+    while ((add)->next->next) { (add)->next = (add)->next->next; }                             \
+    (add)->next->next=(add);                                                                   \
+  } else {                                                                                     \
+    (head)=(add);                                                                              \
+  }                                                                                            \
+  (add)->next=NULL;                                                                            \
+} while (0)
+
+#define LL_DELETE_VS2008(head,del)                                                             \
+do {                                                                                           \
+  if ((head) == (del)) {                                                                       \
+    (head)=(head)->next;                                                                       \
+  } else {                                                                                     \
+    char *_tmp = (char*)(head);                                                                \
+    while (head->next && (head->next != (del))) {                                              \
+      head = head->next;                                                                       \
+    }                                                                                          \
+    if (head->next) {                                                                          \
+      head->next = ((del)->next);                                                              \
+    }                                                                                          \
+    {                                                                                          \
+      char **_head_alias = (char**)&(head);                                                    \
+      *_head_alias = _tmp;                                                                     \
+    }                                                                                          \
+  }                                                                                            \
+} while (0)
+#ifdef NO_DECLTYPE
+#undef LL_APPEND
+#define LL_APPEND LL_APPEND_VS2008
+#undef LL_DELETE
+#define LL_DELETE LL_DELETE_VS2008
+#endif
+/* end VS2008 replacements */
+
+#define LL_FOREACH(head,el)                                                                    \
+    for(el=head;el;el=el->next)
+
+#define LL_FOREACH_SAFE(head,el,tmp)                                                           \
+  for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp)
+
+#define LL_SEARCH_SCALAR(head,out,field,val)                                                   \
+do {                                                                                           \
+    LL_FOREACH(head,out) {                                                                     \
+      if ((out)->field == (val)) break;                                                        \
+    }                                                                                          \
+} while(0) 
+
+#define LL_SEARCH(head,out,elt,cmp)                                                            \
+do {                                                                                           \
+    LL_FOREACH(head,out) {                                                                     \
+      if ((cmp(out,elt))==0) break;                                                            \
+    }                                                                                          \
+} while(0) 
+
+/******************************************************************************
+ * doubly linked list macros (non-circular)                                   *
+ *****************************************************************************/
+#define DL_PREPEND(head,add)                                                                   \
+do {                                                                                           \
+ (add)->next = head;                                                                           \
+ if (head) {                                                                                   \
+   (add)->prev = (head)->prev;                                                                 \
+   (head)->prev = (add);                                                                       \
+ } else {                                                                                      \
+   (add)->prev = (add);                                                                        \
+ }                                                                                             \
+ (head) = (add);                                                                               \
+} while (0)
+
+#define DL_APPEND(head,add)                                                                    \
+do {                                                                                           \
+  if (head) {                                                                                  \
+      (add)->prev = (head)->prev;                                                              \
+      (head)->prev->next = (add);                                                              \
+      (head)->prev = (add);                                                                    \
+      (add)->next = NULL;                                                                      \
+  } else {                                                                                     \
+      (head)=(add);                                                                            \
+      (head)->prev = (head);                                                                   \
+      (head)->next = NULL;                                                                     \
+  }                                                                                            \
+} while (0);
+
+#define DL_DELETE(head,del)                                                                    \
+do {                                                                                           \
+  if ((del)->prev == (del)) {                                                                  \
+      (head)=NULL;                                                                             \
+  } else if ((del)==(head)) {                                                                  \
+      (del)->next->prev = (del)->prev;                                                         \
+      (head) = (del)->next;                                                                    \
+  } else {                                                                                     \
+      (del)->prev->next = (del)->next;                                                         \
+      if ((del)->next) {                                                                       \
+          (del)->next->prev = (del)->prev;                                                     \
+      } else {                                                                                 \
+          (head)->prev = (del)->prev;                                                          \
+      }                                                                                        \
+  }                                                                                            \
+} while (0);
+
+
+#define DL_FOREACH(head,el)                                                                    \
+    for(el=head;el;el=el->next)
+
+/* this version is safe for deleting the elements during iteration */
+#define DL_FOREACH_SAFE(head,el,tmp)                                                           \
+  for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp)
+
+/* these are identical to their singly-linked list counterparts */
+#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR
+#define DL_SEARCH LL_SEARCH
+
+/******************************************************************************
+ * circular doubly linked list macros                                         *
+ *****************************************************************************/
+#define CDL_PREPEND(head,add)                                                                  \
+do {                                                                                           \
+ if (head) {                                                                                   \
+   (add)->prev = (head)->prev;                                                                 \
+   (add)->next = (head);                                                                       \
+   (head)->prev = (add);                                                                       \
+   (add)->prev->next = (add);                                                                  \
+ } else {                                                                                      \
+   (add)->prev = (add);                                                                        \
+   (add)->next = (add);                                                                        \
+ }                                                                                             \
+(head)=(add);                                                                                  \
+} while (0)
+
+#define CDL_DELETE(head,del)                                                                   \
+do {                                                                                           \
+  if ( ((head)==(del)) && ((head)->next == (head))) {                                          \
+      (head) = 0L;                                                                             \
+  } else {                                                                                     \
+     (del)->next->prev = (del)->prev;                                                          \
+     (del)->prev->next = (del)->next;                                                          \
+     if ((del) == (head)) (head)=(del)->next;                                                  \
+  }                                                                                            \
+} while (0);
+
+#define CDL_FOREACH(head,el)                                                                   \
+    for(el=head;el;el=(el->next==head ? 0L : el->next)) 
+
+#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2)                                                    \
+  for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL);                                        \
+      (el) && ((tmp2)=(el)->next, 1);                                                          \
+      ((el) = (((el)==(tmp1)) ? 0L : (tmp2))))
+
+#define CDL_SEARCH_SCALAR(head,out,field,val)                                                  \
+do {                                                                                           \
+    CDL_FOREACH(head,out) {                                                                    \
+      if ((out)->field == (val)) break;                                                        \
+    }                                                                                          \
+} while(0) 
+
+#define CDL_SEARCH(head,out,elt,cmp)                                                           \
+do {                                                                                           \
+    CDL_FOREACH(head,out) {                                                                    \
+      if ((cmp(out,elt))==0) break;                                                            \
+    }                                                                                          \
+} while(0) 
+
+#endif /* UTLIST_H */
+
