-add newline
[oweals/gnunet.git] / src / regex / regex.c
index a5d84ce95612cdd555be13632ed4cfe8f06b0b8b..0a2671fa0f24e2c8fe492ab69d80c222fa948ba3 100644 (file)
@@ -19,7 +19,9 @@
 */
 /**
  * @file src/regex/regex.c
- * @brief library to create automatons from regular expressions
+ * @brief library to create Deterministic Finite Automatons (DFAs) from regular
+ * expressions (regexes). Used by mesh for announcing regexes in the network and
+ * matching strings against published regexes.
  * @author Maximilian Szengel
  */
 #include "platform.h"
 #include "gnunet_regex_lib.h"
 #include "regex_internal.h"
 
-
 /**
- * Constant for how many bits the initial string regex should have.
+ * Set this to GNUNET_YES to enable state naming. Used to debug NFA->DFA
+ * creation. Disabled by default for better performance.
  */
-#define INITIAL_BITS 8
-
+#define REGEX_DEBUG_DFA GNUNET_NO
 
 /**
- * Set of states.
+ * Set of states using MDLL API.
  */
-struct GNUNET_REGEX_StateSet
+struct GNUNET_REGEX_StateSet_MDLL
 {
   /**
-   * Array of states.
+   * MDLL of states.
+   */
+  struct GNUNET_REGEX_State *head;
+
+  /**
+   * MDLL of states.
    */
-  struct GNUNET_REGEX_State **states;
+  struct GNUNET_REGEX_State *tail;
 
   /**
-   * Length of the 'states' array.
+   * Length of the MDLL.
    */
   unsigned int len;
 };
 
 
+/**
+ * Append state to the given StateSet '
+ *
+ * @param set set to be modified
+ * @param state state to be appended
+ */
+static void
+state_set_append (struct GNUNET_REGEX_StateSet *set,
+                 struct GNUNET_REGEX_State *state)
+{
+  if (set->off == set->size)
+    GNUNET_array_grow (set->states, set->size, set->size * 2 + 4);
+  set->states[set->off++] = state;
+}
+
+
 /**
  * Compare two strings for equality. If either is NULL they are not equal.
  *
@@ -86,7 +108,6 @@ state_add_transition (struct GNUNET_REGEX_Context *ctx,
                       struct GNUNET_REGEX_State *from_state, const char *label,
                       struct GNUNET_REGEX_State *to_state)
 {
-  int is_dup;
   struct GNUNET_REGEX_Transition *t;
   struct GNUNET_REGEX_Transition *oth;
 
@@ -96,22 +117,15 @@ state_add_transition (struct GNUNET_REGEX_Context *ctx,
     return;
   }
 
-  // Do not add duplicate state transitions
-  is_dup = GNUNET_NO;
+  /* Do not add duplicate state transitions */
   for (t = from_state->transitions_head; NULL != t; t = t->next)
   {
     if (t->to_state == to_state && 0 == nullstrcmp (t->label, label) &&
         t->from_state == from_state)
-    {
-      is_dup = GNUNET_YES;
-      break;
-    }
+      return;
   }
 
-  if (GNUNET_YES == is_dup)
-    return;
-
-  // sort transitions by label
+  /* sort transitions by label */
   for (oth = from_state->transitions_head; NULL != oth; oth = oth->next)
   {
     if (0 < nullstrcmp (oth->label, label))
@@ -128,7 +142,7 @@ state_add_transition (struct GNUNET_REGEX_Context *ctx,
   t->to_state = to_state;
   t->from_state = from_state;
 
-  // Add outgoing transition to 'from_state'
+  /* Add outgoing transition to 'from_state' */
   from_state->transition_count++;
   GNUNET_CONTAINER_DLL_insert_before (from_state->transitions_head,
                                       from_state->transitions_tail, oth, t);
@@ -151,10 +165,12 @@ state_remove_transition (struct GNUNET_REGEX_State *state,
   if (transition->from_state != state)
     return;
 
+  GNUNET_free_non_null (transition->label);
+
   state->transition_count--;
   GNUNET_CONTAINER_DLL_remove (state->transitions_head, state->transitions_tail,
                                transition);
-  GNUNET_free_non_null (transition->label);
+
   GNUNET_free (transition);
 }
 
@@ -172,11 +188,8 @@ state_remove_transition (struct GNUNET_REGEX_State *state,
 static int
 state_compare (const void *a, const void *b)
 {
-  struct GNUNET_REGEX_State **s1;
-  struct GNUNET_REGEX_State **s2;
-
-  s1 = (struct GNUNET_REGEX_State **) a;
-  s2 = (struct GNUNET_REGEX_State **) b;
+  struct GNUNET_REGEX_State **s1 = (struct GNUNET_REGEX_State **) a;
+  struct GNUNET_REGEX_State **s2 = (struct GNUNET_REGEX_State **) b;
 
   return (*s1)->id - (*s2)->id;
 }
@@ -221,10 +234,7 @@ state_get_edges (struct GNUNET_REGEX_State *s, struct GNUNET_REGEX_Edge *edges)
  *
  * @param sset1 first state set
  * @param sset2 second state set
- *
- * @return an integer less than, equal to, or greater than zero
- *         if the first argument is considered to be respectively
- *         less than, equal to, or greater than the second.
+ * @return 0 if the sets are equal, otherwise non-zero
  */
 static int
 state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
@@ -236,15 +246,14 @@ state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
   if (NULL == sset1 || NULL == sset2)
     return 1;
 
-  result = sset1->len - sset2->len;
-
-  for (i = 0; i < sset1->len; i++)
-  {
-    if (0 != result)
+  result = sset1->off - sset2->off;
+  if (result < 0)
+    return -1;
+  if (result > 0)
+    return 1;
+  for (i = 0; i < sset1->off; i++)
+    if (0 != (result = state_compare (&sset1->states[i], &sset2->states[i])))
       break;
-
-    result = state_compare (&sset1->states[i], &sset2->states[i]);
-  }
   return result;
 }
 
@@ -257,11 +266,8 @@ state_set_compare (struct GNUNET_REGEX_StateSet *sset1,
 static void
 state_set_clear (struct GNUNET_REGEX_StateSet *set)
 {
-  if (NULL != set)
-  {
-    GNUNET_free_non_null (set->states);
-    GNUNET_free (set);
-  }
+  GNUNET_array_grow (set->states, set->size, 0);
+  set->off = 0;
 }
 
 
@@ -302,17 +308,13 @@ automaton_destroy_state (struct GNUNET_REGEX_State *s)
 
   GNUNET_free_non_null (s->name);
   GNUNET_free_non_null (s->proof);
-
+  state_set_clear (&s->nfa_set);
   for (t = s->transitions_head; NULL != t; t = next_t)
   {
     next_t = t->next;
-    GNUNET_CONTAINER_DLL_remove (s->transitions_head, s->transitions_tail, t);
-    GNUNET_free_non_null (t->label);
-    GNUNET_free (t);
+    state_remove_transition (s, t);
   }
 
-  state_set_clear (s->nfa_set);
-
   GNUNET_free (s);
 }
 
@@ -329,40 +331,36 @@ static void
 automaton_remove_state (struct GNUNET_REGEX_Automaton *a,
                         struct GNUNET_REGEX_State *s)
 {
-  struct GNUNET_REGEX_State *ss;
   struct GNUNET_REGEX_State *s_check;
   struct GNUNET_REGEX_Transition *t_check;
+  struct GNUNET_REGEX_Transition *t_check_next;
 
   if (NULL == a || NULL == s)
     return;
 
-  // remove state
-  ss = s;
-  GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
-  a->state_count--;
-
-  // remove all transitions leading to this state
+  /* remove all transitions leading to this state */
   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
   {
     for (t_check = s_check->transitions_head; NULL != t_check;
-         t_check = t_check->next)
+         t_check = t_check_next)
     {
-      if (t_check->to_state == ss)
-      {
-        GNUNET_CONTAINER_DLL_remove (s_check->transitions_head,
-                                     s_check->transitions_tail, t_check);
-        s_check->transition_count--;
-      }
+      t_check_next = t_check->next;
+      if (t_check->to_state == s)
+        state_remove_transition (s_check, t_check);
     }
   }
 
-  automaton_destroy_state (ss);
+  /* remove state */
+  GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
+  a->state_count--;
+
+  automaton_destroy_state (s);
 }
 
 
 /**
  * Merge two states into one. Will merge 's1' and 's2' into 's1' and destroy
- * 's2'.
+ * 's2'. 's1' will contain all (non-duplicate) outgoing transitions of 's2'.
  *
  * @param ctx context
  * @param a automaton
@@ -379,16 +377,13 @@ automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
   struct GNUNET_REGEX_Transition *t_check;
   struct GNUNET_REGEX_Transition *t;
   struct GNUNET_REGEX_Transition *t_next;
-  char *new_name;
   int is_dup;
 
-  GNUNET_assert (NULL != ctx && NULL != a && NULL != s1 && NULL != s2);
-
   if (s1 == s2)
     return;
 
-  // 1. Make all transitions pointing to s2 point to s1, unless this transition
-  // does not already exists, if it already exists remove transition.
+  /* 1. Make all transitions pointing to s2 point to s1, unless this transition
+   * does not already exists, if it already exists remove transition. */
   for (s_check = a->states_head; NULL != s_check; s_check = s_check->next)
   {
     for (t_check = s_check->transitions_head; NULL != t_check; t_check = t_next)
@@ -411,19 +406,23 @@ automaton_merge_states (struct GNUNET_REGEX_Context *ctx,
     }
   }
 
-  // 2. Add all transitions from s2 to sX to s1
+  /* 2. Add all transitions from s2 to sX to s1 */
   for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next)
   {
     if (t_check->to_state != s1)
       state_add_transition (ctx, s1, t_check->label, t_check->to_state);
   }
 
-  // 3. Rename s1 to {s1,s2}
+  /* 3. Rename s1 to {s1,s2} */
+#if REGEX_DEBUG_DFA
+  char *new_name;
+
   new_name = s1->name;
   GNUNET_asprintf (&s1->name, "{%s,%s}", new_name, s2->name);
   GNUNET_free (new_name);
+#endif
 
-  // remove state
+  /* remove state */
   GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s2);
   a->state_count--;
   automaton_destroy_state (s2);
@@ -539,149 +538,367 @@ GNUNET_REGEX_automaton_traverse (const struct GNUNET_REGEX_Automaton *a,
 
 
 /**
- * Context for adding strided transitions to a DFA.
+ * String container for faster string operations.
  */
-struct GNUNET_REGEX_Strided_Context
+struct StringBuffer
 {
   /**
-   * Length of the strides.
+   * Buffer holding the string (may start in the middle!);
+   * NOT 0-terminated!
    */
-  const unsigned int stride;
+  char *sbuf;
 
   /**
-   * Strided transitions DLL. New strided transitions will be stored in this DLL
-   * and afterwards added to the DFA.
+   * Allocated buffer.
    */
-  struct GNUNET_REGEX_Transition *transitions_head;
+  char *abuf;
+  
+  /**
+   * Length of the string in the buffer.
+   */
+  size_t slen;
 
   /**
-   * Strided transitions DLL.
+   * Number of bytes allocated for 'sbuf'
    */
-  struct GNUNET_REGEX_Transition *transitions_tail;
+  unsigned int blen;
+
+  /**
+   * Buffer currently represents "NULL" (not the empty string!)
+   */
+  int16_t null_flag;
+
+  /**
+   * If this entry is part of the last/current generation array,
+   * this flag is GNUNET_YES if the last and current generation are
+   * identical (and thus copying is unnecessary if the value didn't
+   * change).  This is used in an optimization that improves
+   * performance by about 1% --- if we use int16_t here.  With just
+   * "int" for both flags, performance drops (on my system) significantly,
+   * most likely due to increased cache misses. 
+   */
+  int16_t synced;
+  
 };
 
 
 /**
- * Recursive helper function to add strides to a DFA.
+ * Compare two strings for equality. If either is NULL they are not equal.
  *
- * @param cls context, contains stride length and strided transitions DLL.
- * @param depth current depth of the depth-first traversal of the graph.
- * @param label current label, string that contains all labels on the path from
- *        'start' to 's'.
- * @param start start state for the depth-first traversal of the graph.
- * @param s current state in the depth-first traversal
+ * @param s1 first string for comparison.
+ * @param s2 second string for comparison.
+ *
+ * @return 0 if the strings are the same or both NULL, 1 or -1 if not.
  */
-void
-add_multi_strides_to_dfa_helper (void *cls, const unsigned int depth,
-                                 char *label, struct GNUNET_REGEX_State *start,
-                                 struct GNUNET_REGEX_State *s)
+static int
+sb_nullstrcmp (const struct StringBuffer *s1,
+              const struct StringBuffer *s2)
 {
-  struct GNUNET_REGEX_Strided_Context *ctx = cls;
-  struct GNUNET_REGEX_Transition *t;
-  char *new_label;
+  if ( (GNUNET_YES == s1->null_flag) &&
+       (GNUNET_YES == s2->null_flag) )
+    return 0;
+  if ( (GNUNET_YES == s1->null_flag) ||
+       (GNUNET_YES == s2->null_flag) )
+    return -1;
+  if (s1->slen != s2->slen)
+    return -1;
+  return memcmp (s1->sbuf, s2->sbuf, s1->slen);
+}
+              
 
-  if (depth == ctx->stride)
-  {
-    t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
-    t->label = GNUNET_strdup (label);
-    t->to_state = s;
-    t->from_state = start;
-    GNUNET_CONTAINER_DLL_insert (ctx->transitions_head, ctx->transitions_tail,
-                                 t);
-  }
-  else
-  {
-    for (t = s->transitions_head; NULL != t; t = t->next)
-    {
-      /* Do not consider self-loops, because it end's up in too many
-       * transitions */
-      if (t->to_state == t->from_state)
-        continue;
+/**
+ * Compare two strings for equality. 
+ *
+ * @param s1 first string for comparison.
+ * @param s2 second string for comparison.
+ *
+ * @return 0 if the strings are the same, 1 or -1 if not.
+ */
+static int
+sb_strcmp (const struct StringBuffer *s1,
+          const struct StringBuffer *s2)
+{
+  if (s1->slen != s2->slen)
+    return -1;
+  return memcmp (s1->sbuf, s2->sbuf, s1->slen);
+}
+        
 
-      if (NULL != label)
-      {
-        GNUNET_asprintf (&new_label, "%s%s", label, t->label);
-      }
-      else
-        new_label = GNUNET_strdup (t->label);
+/**
+ * Reallocate the buffer of 'ret' to fit 'nlen' characters;
+ * move the existing string to the beginning of the new buffer.
+ *
+ * @param ret current buffer, to be updated
+ * @param nlen target length for the buffer, must be at least ret->slen
+ */
+static void
+sb_realloc (struct StringBuffer *ret,
+           size_t nlen)
+{
+  char *old;
+
+  GNUNET_assert (nlen >= ret->slen);
+  old = ret->abuf;
+  ret->abuf = GNUNET_malloc (nlen);
+  ret->blen = nlen;
+  memcpy (ret->abuf,
+         ret->sbuf,
+         ret->slen);
+  ret->sbuf = ret->abuf;
+  GNUNET_free_non_null (old);
+}
+  
 
-      add_multi_strides_to_dfa_helper (cls, (depth + 1), new_label, start,
-                                       t->to_state);
-    }
-  }
-  GNUNET_free_non_null (label);
+/**
+ * Append a string.
+ *
+ * @param ret where to write the result
+ * @param sarg string to append
+ */
+static void
+sb_append (struct StringBuffer *ret,
+          const struct StringBuffer *sarg)
+{
+  if (GNUNET_YES == ret->null_flag)
+    ret->slen = 0;
+  ret->null_flag = GNUNET_NO;
+  if (ret->blen < sarg->slen + ret->slen)
+    sb_realloc (ret, ret->blen + sarg->slen + 128);
+  memcpy (&ret->sbuf[ret->slen],
+         sarg->sbuf,
+         sarg->slen);
+  ret->slen += sarg->slen;
 }
+          
 
+/**
+ * Append a C string.
+ *
+ * @param ret where to write the result
+ * @param cstr string to append
+ */
+static void
+sb_append_cstr (struct StringBuffer *ret,
+               const char *cstr)
+{
+  size_t cstr_len = strlen (cstr);
+
+  if (GNUNET_YES == ret->null_flag)
+    ret->slen = 0;
+  ret->null_flag = GNUNET_NO;
+  if (ret->blen < cstr_len + ret->slen)
+    sb_realloc (ret, ret->blen + cstr_len + 128);
+  memcpy (&ret->sbuf[ret->slen],
+         cstr,
+         cstr_len);
+  ret->slen += cstr_len;
+}
+          
 
 /**
- * Function called for each state in the DFA. Starts a traversal of depth set in
- * context starting from state 's'.
+ * Wrap a string buffer, that is, set ret to the format string
+ * which contains an "%s" which is to be replaced with the original
+ * content of 'ret'.  Note that optimizing this function is not
+ * really worth it, it is rarely called.
+ *
+ * @param ret where to write the result and take the input for %.*s from
+ * @param format format string, fprintf-style, with exactly one "%.*s"
+ * @param extra_chars how long will the result be, in addition to 'sarg' length
+ */
+static void
+sb_wrap (struct StringBuffer *ret,
+        const char *format,
+        size_t extra_chars)
+{
+  char *temp;
+
+  if (GNUNET_YES == ret->null_flag)
+    ret->slen = 0;
+  ret->null_flag = GNUNET_NO;
+  temp = GNUNET_malloc (ret->slen + extra_chars + 1);
+  GNUNET_snprintf (temp,
+                  ret->slen + extra_chars + 1,
+                  format,
+                  (int) ret->slen,
+                  ret->sbuf);
+  GNUNET_free_non_null (ret->abuf);
+  ret->abuf = temp;
+  ret->sbuf = temp;
+  ret->blen = ret->slen + extra_chars + 1;
+  ret->slen = ret->slen + extra_chars;
+}
+
+
+/**
+ * Format a string buffer.    Note that optimizing this function is not
+ * really worth it, it is rarely called.
  *
- * @param cls context.
- * @param count not used.
- * @param s current state.
+ * @param ret where to write the result
+ * @param format format string, fprintf-style, with exactly one "%.*s"
+ * @param extra_chars how long will the result be, in addition to 'sarg' length
+ * @param sarg string to print into the format
  */
-void
-add_multi_strides_to_dfa (void *cls, const unsigned int count,
-                          struct GNUNET_REGEX_State *s)
+static void
+sb_printf1 (struct StringBuffer *ret,
+           const char *format,
+           size_t extra_chars,
+           const struct StringBuffer *sarg)
 {
-  add_multi_strides_to_dfa_helper (cls, 0, NULL, s, s);
+  if (ret->blen < sarg->slen + extra_chars + 1)
+    sb_realloc (ret,
+               sarg->slen + extra_chars + 1);
+  ret->null_flag = GNUNET_NO;
+  ret->sbuf = ret->abuf;
+  ret->slen = sarg->slen + extra_chars;
+  GNUNET_snprintf (ret->sbuf,
+                  ret->blen,
+                  format,
+                  (int) sarg->slen,
+                  sarg->sbuf);
 }
 
 
 /**
- * Adds multi-strided transitions to the given 'dfa'.
+ * Format a string buffer.
  *
- * @param regex_ctx regex context needed to add transitions to the automaton.
- * @param dfa DFA to which the multi strided transitions should be added.
- * @param stride_len length of the strides.
+ * @param ret where to write the result
+ * @param format format string, fprintf-style, with exactly two "%.*s"
+ * @param extra_chars how long will the result be, in addition to 'sarg1/2' length
+ * @param sarg1 first string to print into the format
+ * @param sarg2 second string to print into the format
  */
-void
-GNUNET_REGEX_add_multi_strides_to_dfa (struct GNUNET_REGEX_Context *regex_ctx,
-                                       struct GNUNET_REGEX_Automaton *dfa,
-                                       const unsigned int stride_len)
+static void
+sb_printf2 (struct StringBuffer *ret,
+           const char *format,
+           size_t extra_chars,
+           const struct StringBuffer *sarg1,
+           const struct StringBuffer *sarg2)
 {
-  struct GNUNET_REGEX_Strided_Context ctx = { stride_len, NULL, NULL };
-  struct GNUNET_REGEX_State *s;
-  struct GNUNET_REGEX_State *s_next;
-  struct GNUNET_REGEX_Transition *t;
-  struct GNUNET_REGEX_Transition *t_next;
+  if (ret->blen < sarg1->slen + sarg2->slen + extra_chars + 1)
+    sb_realloc (ret,
+               sarg1->slen + sarg2->slen + extra_chars + 1);
+  ret->null_flag = GNUNET_NO;
+  ret->slen = sarg1->slen + sarg2->slen + extra_chars;
+  ret->sbuf = ret->abuf;
+  GNUNET_snprintf (ret->sbuf,
+                  ret->blen,
+                  format,
+                  (int) sarg1->slen,
+                  sarg1->sbuf,
+                  (int) sarg2->slen,
+                  sarg2->sbuf);
+}
 
-  if (1 > stride_len || GNUNET_YES == dfa->is_multistrided)
-    return;
 
-  // Unmark all states
-  for (s = dfa->states_head; NULL != s; s = s->next)
-    s->marked = GNUNET_NO;
+/**
+ * Format a string buffer.     Note that optimizing this function is not
+ * really worth it, it is rarely called.
+ *
+ * @param ret where to write the result
+ * @param format format string, fprintf-style, with exactly three "%.*s"
+ * @param extra_chars how long will the result be, in addition to 'sarg1/2/3' length
+ * @param sarg1 first string to print into the format
+ * @param sarg2 second string to print into the format
+ * @param sarg3 third string to print into the format
+ */
+static void
+sb_printf3 (struct StringBuffer *ret,
+           const char *format,
+           size_t extra_chars,
+           const struct StringBuffer *sarg1,
+           const struct StringBuffer *sarg2,
+           const struct StringBuffer *sarg3)
+{
+  if (ret->blen < sarg1->slen + sarg2->slen + sarg3->slen + extra_chars + 1)
+    sb_realloc (ret,
+               sarg1->slen + sarg2->slen + sarg3->slen + extra_chars + 1);
+  ret->null_flag = GNUNET_NO;
+  ret->slen = sarg1->slen + sarg2->slen + sarg3->slen + extra_chars;
+  ret->sbuf = ret->abuf;
+  GNUNET_snprintf (ret->sbuf,
+                  ret->blen,
+                  format,
+                  (int) sarg1->slen,
+                  sarg1->sbuf,
+                  (int) sarg2->slen,
+                  sarg2->sbuf,
+                  (int) sarg3->slen,
+                  sarg3->sbuf);
+}
 
-  // Compute the new transitions of given stride_len
-  GNUNET_REGEX_automaton_traverse (dfa, dfa->start, NULL, NULL,
-                                   &add_multi_strides_to_dfa, &ctx);
 
-  // Add all the new transitions to the automaton.
-  for (t = ctx.transitions_head; NULL != t; t = t_next)
+/**
+ * Free resources of the given string buffer.
+ *
+ * @param sb buffer to free (actual pointer is not freed, as they
+ *        should not be individually allocated)
+ */
+static void
+sb_free (struct StringBuffer *sb)
+{
+  GNUNET_array_grow (sb->abuf,
+                    sb->blen,
+                    0);
+  sb->slen = 0;
+  sb->sbuf = NULL;
+  sb->null_flag= GNUNET_YES;
+}
+
+
+/**
+ * Copy the given string buffer from 'in' to 'out'.
+ *
+ * @param in input string
+ * @param out output string
+ */
+static void
+sb_strdup (struct StringBuffer *out,
+          const struct StringBuffer *in)
+          
+{
+  out->null_flag = in->null_flag;
+  if (GNUNET_YES == out->null_flag)
+    return;
+  if (out->blen < in->slen)
   {
-    t_next = t->next;
-    state_add_transition (regex_ctx, t->from_state, t->label, t->to_state);
-    GNUNET_CONTAINER_DLL_remove (ctx.transitions_head, ctx.transitions_tail, t);
-    GNUNET_free_non_null (t->label);
-    GNUNET_free (t);
+    GNUNET_array_grow (out->abuf,
+                      out->blen,
+                      in->slen);
   }
+  out->sbuf = out->abuf;
+  out->slen = in->slen;
+  memcpy (out->sbuf, in->sbuf, out->slen);
+}
 
-  // Remove marked states (including their incoming and outgoing transitions)
-  for (s = dfa->states_head; NULL != s; s = s_next)
+
+/**
+ * Copy the given string buffer from 'in' to 'out'.
+ *
+ * @param cstr input string
+ * @param out output string
+ */
+static void
+sb_strdup_cstr (struct StringBuffer *out,
+               const char *cstr)
+{
+  if (NULL == cstr)
   {
-    s_next = s->next;
-    if (GNUNET_YES == s->marked)
-      automaton_remove_state (dfa, s);
+    out->null_flag = GNUNET_YES;
+    return;
   }
-
-  // Mark this automaton as multistrided
-  dfa->is_multistrided = GNUNET_YES;
+  out->null_flag = GNUNET_NO;
+  out->slen = strlen (cstr);
+  if (out->blen < out->slen)
+  {
+    GNUNET_array_grow (out->abuf,
+                      out->blen,
+                      out->slen);
+  }
+  out->sbuf = out->abuf;
+  memcpy (out->sbuf, cstr, out->slen);
 }
 
 
-
 /**
  * Check if the given string 'str' needs parentheses around it when
  * using it to generate a regex.
@@ -691,35 +908,37 @@ GNUNET_REGEX_add_multi_strides_to_dfa (struct GNUNET_REGEX_Context *regex_ctx,
  * @return GNUNET_YES if parentheses are needed, GNUNET_NO otherwise
  */
 static int
-needs_parentheses (const char *str)
+needs_parentheses (const struct StringBuffer *str)
 {
   size_t slen;
   const char *op;
   const char *cl;
   const char *pos;
+  const char *end;
   unsigned int cnt;
 
-  if ((NULL == str) || ((slen = strlen (str)) < 2))
+  if ((GNUNET_YES == str->null_flag) || ((slen = str->slen) < 2))
     return GNUNET_NO;
-
-  if ('(' != str[0])
+  pos = str->sbuf;
+  if ('(' != pos[0])
     return GNUNET_YES;
+  end = str->sbuf + slen;
   cnt = 1;
-  pos = &str[1];
+  pos++;
   while (cnt > 0)
   {
-    cl = strchr (pos, ')');
+    cl = memchr (pos, ')', end - pos);
     if (NULL == cl)
     {
       GNUNET_break (0);
       return GNUNET_YES;
     }
-    op = strchr (pos, '(');
-    if ((NULL != op) && (op < cl))
+    /* while '(' before ')', count opening parens */
+    while ( (NULL != (op = memchr (pos, '(', end - pos)))  &&
+           (op < cl) ) 
     {
       cnt++;
       pos = op + 1;
-      continue;
     }
     /* got ')' first */
     cnt--;
@@ -734,28 +953,61 @@ needs_parentheses (const char *str)
  * Example: "(a)" becomes "a", "(a|b)|(a|c)" stays the same.
  * You need to GNUNET_free the returned string.
  *
- * @param str string, free'd or re-used by this function, can be NULL
- *
+ * @param str string, modified to contain a
  * @return string without surrounding parentheses, string 'str' if no preceding
  *         epsilon could be found, NULL if 'str' was NULL
  */
-static char *
-remove_parentheses (char *str)
+static void
+remove_parentheses (struct StringBuffer *str)
 {
   size_t slen;
   const char *pos;
+  const char *end;
+  const char *sbuf;
+  const char *op;
+  const char *cp;
+  unsigned int cnt;
 
-  if ((NULL == str) || ('(' != str[0]) ||
-      (str[(slen = strlen (str)) - 1] != ')'))
-    return str;
-
-  pos = strchr (&str[1], ')');
-  if (pos == &str[slen - 1])
+  if (0)
+    return;
+  sbuf = str->sbuf;
+  if ( (GNUNET_YES == str->null_flag) || 
+       (1 >=  (slen = str->slen)) ||
+       ('(' != str->sbuf[0]) ||
+       (')' != str->sbuf[slen - 1]) )
+    return;
+  cnt = 0;
+  pos = &sbuf[1];
+  end = &sbuf[slen - 1];
+  op = memchr (pos, '(', end - pos);
+  cp = memchr (pos, ')', end - pos);
+  while (NULL != cp) 
+  {
+    while ( (NULL != op) &&
+           (op < cp) )
+    {
+      cnt++;
+      pos = op + 1;
+      op = memchr (pos, '(', end - pos);
+    }
+    while ( (NULL != cp) &&
+           ( (NULL == op) ||
+             (cp < op) ) )
+    {
+      if (0 == cnt)
+       return; /* can't strip parens */
+      cnt--;
+      pos = cp + 1;
+      cp = memchr (pos, ')', end - pos);
+    }
+  }
+  if (0 != cnt)
   {
-    memmove (str, &str[1], slen - 2);
-    str[slen - 2] = '\0';
+    GNUNET_break (0);
+    return;
   }
-  return str;
+  str->sbuf++;
+  str->slen -= 2;  
 }
 
 
@@ -768,10 +1020,14 @@ remove_parentheses (char *str)
  * @return 0 if str has no epsilon, 1 if str starts with '(|' and ends with ')'
  */
 static int
-has_epsilon (const char *str)
+has_epsilon (const struct StringBuffer *str)
 {
-  return (NULL != str) && ('(' == str[0]) && ('|' == str[1]) &&
-      (')' == str[strlen (str) - 1]);
+  return 
+    (GNUNET_YES != str->null_flag) && 
+    (0 < str->slen) &&
+    ('(' == str->sbuf[0]) && 
+    ('|' == str->sbuf[1]) &&
+    (')' == str->sbuf[str->slen - 1]);
 }
 
 
@@ -780,57 +1036,136 @@ has_epsilon (const char *str)
  * Example: str = "(|a|b|c)", result: "a|b|c"
  * The returned string needs to be freed.
  *
- * @param str string
- *
- * @return string without preceding epsilon, string 'str' if no preceding
+ * @param str original string
+ * @param ret where to return string without preceding epsilon, string 'str' if no preceding
  *         epsilon could be found, NULL if 'str' was NULL
  */
-static char *
-remove_epsilon (const char *str)
+static void
+remove_epsilon (const struct StringBuffer *str,
+               struct StringBuffer *ret)
 {
-  size_t len;
-
-  if (NULL == str)
-    return NULL;
-  if (('(' == str[0]) && ('|' == str[1]))
+  if (GNUNET_YES == str->null_flag)
   {
-    len = strlen (str);
-    if (')' == str[len - 1])
-      return GNUNET_strndup (&str[2], len - 3);
+    ret->null_flag = GNUNET_YES;
+    return;
+  }  
+  if ( (str->slen > 1) && 
+       ('(' == str->sbuf[0]) &&
+       ('|' == str->sbuf[1]) &&
+       (')' == str->sbuf[str->slen - 1]) )
+  {
+    /* remove epsilon */
+    if (ret->blen < str->slen - 3)
+    {
+      GNUNET_array_grow (ret->abuf,
+                        ret->blen,
+                        str->slen - 3);
+    }
+    ret->sbuf = ret->abuf;
+    ret->slen = str->slen - 3;
+    memcpy (ret->sbuf, &str->sbuf[2], ret->slen);
+    return;
   }
-  return GNUNET_strdup (str);
+  sb_strdup (ret, str);
 }
 
 
 /**
- * Compare 'str1', starting from position 'k',  with whole 'str2'
+ * Compare n bytes of 'str1' and 'str2'
  *
- * @param str1 first string to compare, starting from position 'k'
+ * @param str1 first string to compare
  * @param str2 second string for comparison
- * @param k starting position in 'str1'
+ * @param n number of bytes to compare
  *
  * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise
  */
 static int
-strkcmp (const char *str1, const char *str2, size_t k)
+sb_strncmp (const struct StringBuffer *str1, 
+           const struct StringBuffer *str2, size_t n)
 {
-  if ((NULL == str1) || (NULL == str2) || (strlen (str1) < k))
+  size_t max;
+  
+  if ( (str1->slen != str2->slen) &&
+       ( (str1->slen < n) ||
+        (str2->slen < n) ) )
     return -1;
-  return strcmp (&str1[k], str2);
+  max = GNUNET_MAX (str1->slen, str2->slen);
+  if (max > n)
+    max = n;
+  return memcmp (str1->sbuf, str2->sbuf, max);
 }
 
 
 /**
- * Helper function used as 'action' in 'GNUNET_REGEX_automaton_traverse'
- * function to create the depth-first numbering of the states.
+ * Compare n bytes of 'str1' and 'str2'
  *
- * @param cls states array.
- * @param count current state counter.
- * @param s current state.
+ * @param str1 first string to compare
+ * @param str2 second C string for comparison
+ * @param n number of bytes to compare (and length of str2)
+ *
+ * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise
  */
-void
-number_states (void *cls, const unsigned int count,
-               struct GNUNET_REGEX_State *s)
+static int
+sb_strncmp_cstr (const struct StringBuffer *str1, 
+                const char *str2, size_t n)
+{
+  if (str1->slen < n) 
+    return -1;
+  return memcmp (str1->sbuf, str2, n);
+}
+
+
+/**
+ * Initialize string buffer for storing strings of up to n 
+ * characters.
+ *
+ * @param sb buffer to initialize
+ * @param n desired target length
+ */
+static void
+sb_init (struct StringBuffer *sb,
+        size_t n)
+{
+  sb->null_flag = GNUNET_NO;
+  sb->abuf = sb->sbuf = (0 == n) ? NULL : GNUNET_malloc (n);
+  sb->blen = n;
+  sb->slen = 0;
+}
+
+
+/**
+ * Compare 'str1', starting from position 'k',  with whole 'str2'
+ *
+ * @param str1 first string to compare, starting from position 'k'
+ * @param str2 second string for comparison
+ * @param k starting position in 'str1'
+ *
+ * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise
+ */
+static int
+sb_strkcmp (const struct StringBuffer *str1, 
+           const struct StringBuffer *str2, size_t k)
+{
+  if ( (GNUNET_YES == str1->null_flag) ||
+       (GNUNET_YES == str2->null_flag) ||
+       (k > str1->slen) ||
+       (str1->slen - k != str2->slen) )
+    return -1;
+  return memcmp (&str1->sbuf[k], str2->sbuf, str2->slen);
+}
+
+
+/**
+ * Helper function used as 'action' in 'GNUNET_REGEX_automaton_traverse'
+ * function to create the depth-first numbering of the states.
+ *
+ * @param cls states array.
+ * @param count current state counter.
+ * @param s current state.
+ */
+static void
+number_states (void *cls, const unsigned int count,
+               struct GNUNET_REGEX_State *s)
 {
   struct GNUNET_REGEX_State **states = cls;
 
@@ -840,6 +1175,12 @@ number_states (void *cls, const unsigned int count,
 }
 
 
+
+#define PRIS(a) \
+  ((GNUNET_YES == a.null_flag) ? 6 : (int) a.slen), \
+  ((GNUNET_YES == a.null_flag) ? "(null)" : a.sbuf)
+
+
 /**
  * Construct the regular expression given the inductive step,
  * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^*
@@ -851,511 +1192,565 @@ number_states (void *cls, const unsigned int count,
  * @param R_last_kj value of  $R^{(k-1)_{kj}.
  * @param R_cur_ij result for this inductive step is saved in R_cur_ij, R_cur_ij
  *                 is expected to be NULL when called!
+ * @param R_cur_l optimization -- kept between iterations to avoid realloc
+ * @param R_cur_r optimization -- kept between iterations to avoid realloc
  */
 static void
-automaton_create_proofs_simplify (char *R_last_ij, char *R_last_ik,
-                                  char *R_last_kk, char *R_last_kj,
-                                  char **R_cur_ij)
-{
-  char *R_cur_l;
-  char *R_cur_r;
-  char *temp_a;
-  char *temp_b;
-  char *R_temp_ij;
-  char *R_temp_ik;
-  char *R_temp_kj;
-  char *R_temp_kk;
-
+automaton_create_proofs_simplify (const struct StringBuffer *R_last_ij, 
+                                 const struct StringBuffer *R_last_ik,
+                                  const struct StringBuffer *R_last_kk,
+                                 const struct StringBuffer *R_last_kj,
+                                  struct StringBuffer *R_cur_ij,
+                                 struct StringBuffer *R_cur_l,
+                                 struct StringBuffer *R_cur_r)
+{
+  struct StringBuffer R_temp_ij;
+  struct StringBuffer R_temp_ik;
+  struct StringBuffer R_temp_kj;
+  struct StringBuffer R_temp_kk;
   int eps_check;
   int ij_ik_cmp;
   int ij_kj_cmp;
-
   int ik_kk_cmp;
   int kk_kj_cmp;
   int clean_ik_kk_cmp;
   int clean_kk_kj_cmp;
-  unsigned int cnt;
-
   size_t length;
   size_t length_l;
   size_t length_r;
 
-  GNUNET_assert (NULL == *R_cur_ij && NULL != R_cur_ij);
-
-  // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
-  // R_last == R^{(k-1)}, R_cur == R^{(k)}
-  // R_cur_ij = R_cur_l | R_cur_r
-  // R_cur_l == R^{(k-1)}_{ij}
-  // R_cur_r == R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
+  /*
+   * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
+   * R_last == R^{(k-1)}, R_cur == R^{(k)}
+   * R_cur_ij = R_cur_l | R_cur_r
+   * R_cur_l == R^{(k-1)}_{ij}
+   * R_cur_r == R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
+   */
 
-  if ((NULL == R_last_ij) && ((NULL == R_last_ik) || (NULL == R_last_kk) ||     /* technically cannot happen, but looks saner */
-                              (NULL == R_last_kj)))
+  if ( (GNUNET_YES == R_last_ij->null_flag) && 
+       ( (GNUNET_YES == R_last_ik->null_flag) || 
+        (GNUNET_YES == R_last_kj->null_flag)))
   {
     /* R^{(k)}_{ij} = N | N */
-    *R_cur_ij = NULL;
+    R_cur_ij->null_flag = GNUNET_YES;
+    R_cur_ij->synced = GNUNET_NO;
     return;
   }
 
-  if ((NULL == R_last_ik) || (NULL == R_last_kk) ||     /* technically cannot happen, but looks saner */
-      (NULL == R_last_kj))
+  if ( (GNUNET_YES == R_last_ik->null_flag) || 
+       (GNUNET_YES == R_last_kj->null_flag) )
   {
     /*  R^{(k)}_{ij} = R^{(k-1)}_{ij} | N */
-    *R_cur_ij = GNUNET_strdup (R_last_ij);
+    if (GNUNET_YES == R_last_ij->synced)
+    {
+      R_cur_ij->synced = GNUNET_YES;      
+      R_cur_ij->null_flag = GNUNET_NO;
+      return;
+    }
+    R_cur_ij->synced = GNUNET_YES;
+    sb_strdup (R_cur_ij, R_last_ij);
     return;
   }
-
-  // $R^{(k)}_{ij} = N | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} OR
-  // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
-
-  R_cur_r = NULL;
-  R_cur_l = NULL;
-
-  // cache results from strcmp, we might need these many times
-  ij_kj_cmp = nullstrcmp (R_last_ij, R_last_kj);
-  ij_ik_cmp = nullstrcmp (R_last_ij, R_last_ik);
-  ik_kk_cmp = nullstrcmp (R_last_ik, R_last_kk);
-  kk_kj_cmp = nullstrcmp (R_last_kk, R_last_kj);
-
-  // Assign R_temp_(ik|kk|kj) to R_last[][] and remove epsilon as well
-  // as parentheses, so we can better compare the contents
-  R_temp_ik = remove_parentheses (remove_epsilon (R_last_ik));
-  R_temp_kk = remove_parentheses (remove_epsilon (R_last_kk));
-  R_temp_kj = remove_parentheses (remove_epsilon (R_last_kj));
-
-  clean_ik_kk_cmp = nullstrcmp (R_last_ik, R_temp_kk);
-  clean_kk_kj_cmp = nullstrcmp (R_temp_kk, R_last_kj);
-
-  // construct R_cur_l (and, if necessary R_cur_r)
-  if (NULL != R_last_ij)
-  {
-    // Assign R_temp_ij to R_last_ij and remove epsilon as well
-    // as parentheses, so we can better compare the contents
-    R_temp_ij = remove_parentheses (remove_epsilon (R_last_ij));
-
-    if (0 == strcmp (R_temp_ij, R_temp_ik) && 0 == strcmp (R_temp_ik, R_temp_kk)
-        && 0 == strcmp (R_temp_kk, R_temp_kj))
+  R_cur_ij->synced = GNUNET_NO;
+
+  /* $R^{(k)}_{ij} = N | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} OR
+   * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} */
+
+  R_cur_r->null_flag = GNUNET_YES; 
+  R_cur_r->slen = 0; 
+  R_cur_l->null_flag = GNUNET_YES; 
+  R_cur_l->slen = 0; 
+
+  /* cache results from strcmp, we might need these many times */
+  ij_kj_cmp = sb_nullstrcmp (R_last_ij, R_last_kj);
+  ij_ik_cmp = sb_nullstrcmp (R_last_ij, R_last_ik);
+  ik_kk_cmp = sb_nullstrcmp (R_last_ik, R_last_kk);
+  kk_kj_cmp = sb_nullstrcmp (R_last_kk, R_last_kj);
+
+  /* Assign R_temp_(ik|kk|kj) to R_last[][] and remove epsilon as well
+   * as parentheses, so we can better compare the contents */
+
+  memset (&R_temp_ij, 0, sizeof (struct StringBuffer));
+  memset (&R_temp_ik, 0, sizeof (struct StringBuffer));
+  memset (&R_temp_kk, 0, sizeof (struct StringBuffer));
+  memset (&R_temp_kj, 0, sizeof (struct StringBuffer));
+  remove_epsilon (R_last_ik, &R_temp_ik);
+  remove_epsilon (R_last_kk, &R_temp_kk);
+  remove_epsilon (R_last_kj, &R_temp_kj);
+  remove_parentheses (&R_temp_ik);
+  remove_parentheses (&R_temp_kk);
+  remove_parentheses (&R_temp_kj);
+  clean_ik_kk_cmp = sb_nullstrcmp (R_last_ik, &R_temp_kk);
+  clean_kk_kj_cmp = sb_nullstrcmp (&R_temp_kk, R_last_kj);
+
+  /* construct R_cur_l (and, if necessary R_cur_r) */
+  if (GNUNET_YES != R_last_ij->null_flag)
+  {
+    /* Assign R_temp_ij to R_last_ij and remove epsilon as well
+     * as parentheses, so we can better compare the contents */
+    remove_epsilon (R_last_ij, &R_temp_ij);
+    remove_parentheses (&R_temp_ij);
+
+    if ( (0 == sb_strcmp (&R_temp_ij, &R_temp_ik)) && 
+        (0 == sb_strcmp (&R_temp_ik, &R_temp_kk)) && 
+        (0 == sb_strcmp (&R_temp_kk, &R_temp_kj)) )
     {
-      if (0 == strlen (R_temp_ij))
+      if (0 == R_temp_ij.slen)
       {
-        R_cur_r = GNUNET_strdup ("");
+        R_cur_r->null_flag = GNUNET_NO;
       }
-      else if ((0 == strncmp (R_last_ij, "(|", 2)) ||
-               (0 == strncmp (R_last_ik, "(|", 2) &&
-                0 == strncmp (R_last_kj, "(|", 2)))
+      else if ((0 == sb_strncmp_cstr (R_last_ij, "(|", 2)) ||
+               (0 == sb_strncmp_cstr (R_last_ik, "(|", 2) &&
+                0 == sb_strncmp_cstr (R_last_kj, "(|", 2)))
       {
-        // a|(e|a)a*(e|a) = a*
-        // a|(e|a)(e|a)*(e|a) = a*
-        // (e|a)|aa*a = a*
-        // (e|a)|aa*(e|a) = a*
-        // (e|a)|(e|a)a*a = a*
-        // (e|a)|(e|a)a*(e|a) = a*
-        // (e|a)|(e|a)(e|a)*(e|a) = a*
-        if (GNUNET_YES == needs_parentheses (R_temp_ij))
-          GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_ij);
+        /*
+         * a|(e|a)a*(e|a) = a*
+         * a|(e|a)(e|a)*(e|a) = a*
+         * (e|a)|aa*a = a*
+         * (e|a)|aa*(e|a) = a*
+         * (e|a)|(e|a)a*a = a*
+         * (e|a)|(e|a)a*(e|a) = a*
+         * (e|a)|(e|a)(e|a)*(e|a) = a*
+         */
+        if (GNUNET_YES == needs_parentheses (&R_temp_ij))
+          sb_printf1 (R_cur_r, "(%.*s)*", 3, &R_temp_ij);
         else
-          GNUNET_asprintf (&R_cur_r, "%s*", R_temp_ij);
+          sb_printf1 (R_cur_r, "%.*s*", 1, &R_temp_ij);
       }
       else
       {
-        // a|aa*a = a+
-        // a|(e|a)a*a = a+
-        // a|aa*(e|a) = a+
-        // a|(e|a)(e|a)*a = a+
-        // a|a(e|a)*(e|a) = a+
-        if (GNUNET_YES == needs_parentheses (R_temp_ij))
-          GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_ij);
+        /*
+         * a|aa*a = a+
+         * a|(e|a)a*a = a+
+         * a|aa*(e|a) = a+
+         * a|(e|a)(e|a)*a = a+
+         * a|a(e|a)*(e|a) = a+
+         */
+        if (GNUNET_YES == needs_parentheses (&R_temp_ij))
+          sb_printf1 (R_cur_r, "(%.*s)+", 3, &R_temp_ij);
         else
-          GNUNET_asprintf (&R_cur_r, "%s+", R_temp_ij);
+          sb_printf1 (R_cur_r, "%.*s+", 1, &R_temp_ij);
       }
     }
-    else if (0 == ij_ik_cmp && 0 == clean_kk_kj_cmp && 0 != clean_ik_kk_cmp)
+    else if ( (0 == ij_ik_cmp) && (0 == clean_kk_kj_cmp) && (0 != clean_ik_kk_cmp) )
     {
-      // a|ab*b = ab*
-      if (strlen (R_last_kk) < 1)
-        R_cur_r = GNUNET_strdup (R_last_ij);
-      else if (GNUNET_YES == needs_parentheses (R_temp_kk))
-        GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
+      /* a|ab*b = ab* */
+      if (0 == R_last_kk->slen)
+        sb_strdup (R_cur_r, R_last_ij);
+      else if (GNUNET_YES == needs_parentheses (&R_temp_kk))
+        sb_printf2 (R_cur_r, "%.*s(%.*s)*", 3, R_last_ij, &R_temp_kk);
       else
-        GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_last_kk);
-
-      R_cur_l = NULL;
+        sb_printf2 (R_cur_r, "%.*s%.*s*", 1, R_last_ij, R_last_kk);
+      R_cur_l->null_flag = GNUNET_YES;
     }
-    else if (0 == ij_kj_cmp && 0 == clean_ik_kk_cmp && 0 != clean_kk_kj_cmp)
+    else if ( (0 == ij_kj_cmp) && (0 == clean_ik_kk_cmp) && (0 != clean_kk_kj_cmp))
     {
-      // a|bb*a = b*a
-      if (strlen (R_last_kk) < 1)
-        R_cur_r = GNUNET_strdup (R_last_kj);
-      else if (GNUNET_YES == needs_parentheses (R_temp_kk))
-        GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
+      /* a|bb*a = b*a */
+      if (R_last_kk->slen < 1)
+      {
+        sb_strdup (R_cur_r, R_last_kj);
+      }
+      else if (GNUNET_YES == needs_parentheses (&R_temp_kk))
+        sb_printf2 (R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_kj);
       else
-        GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
+        sb_printf2 (R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_kj);
 
-      R_cur_l = NULL;
+      R_cur_l->null_flag = GNUNET_YES;
     }
-    else if (0 == ij_ik_cmp && 0 == kk_kj_cmp && !has_epsilon (R_last_ij) &&
-             has_epsilon (R_last_kk))
+    else if ( (0 == ij_ik_cmp) && (0 == kk_kj_cmp) && (! has_epsilon (R_last_ij)) &&
+             has_epsilon (R_last_kk))
     {
-      // a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab*
-      if (needs_parentheses (R_temp_kk))
-        GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ij, R_temp_kk);
+      /* a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab* */
+      if (needs_parentheses (&R_temp_kk))
+        sb_printf2 (R_cur_r, "%.*s(%.*s)*", 3, R_last_ij, &R_temp_kk);
       else
-        GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ij, R_temp_kk);
-
-      R_cur_l = NULL;
+        sb_printf2 (R_cur_r, "%.*s%.*s*", 1, R_last_ij, &R_temp_kk);
+      R_cur_l->null_flag = GNUNET_YES;
     }
-    else if (0 == ij_kj_cmp && 0 == ik_kk_cmp && !has_epsilon (R_last_ij) &&
+    else if ( (0 == ij_kj_cmp) && (0 == ik_kk_cmp) && (! has_epsilon (R_last_ij)) &&
              has_epsilon (R_last_kk))
     {
-      // a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|...  = b*a
-      if (needs_parentheses (R_temp_kk))
-        GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_ij);
+      /* a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|...  = b*a */
+      if (needs_parentheses (&R_temp_kk))
+        sb_printf2 (R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_ij);
       else
-        GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_ij);
-
-      R_cur_l = NULL;
+        sb_printf2 (R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_ij);
+      R_cur_l->null_flag = GNUNET_YES;
     }
     else
     {
-      temp_a = (NULL == R_last_ij) ? NULL : GNUNET_strdup (R_last_ij);
-      temp_a = remove_parentheses (temp_a);
-      R_cur_l = temp_a;
+      sb_strdup (R_cur_l, R_last_ij);
+      remove_parentheses (R_cur_l);
     }
-
-    GNUNET_free_non_null (R_temp_ij);
   }
   else
   {
-    // we have no left side
-    R_cur_l = NULL;
-  }
-
-  // construct R_cur_r, if not already constructed
-  if (NULL == R_cur_r)
-  {
-    length = strlen (R_temp_kk) - strlen (R_last_ik);
-
-    // a(ba)*bx = (ab)+x
-    if (length > 0 && NULL != R_last_kk && 0 < strlen (R_last_kk) &&
-        NULL != R_last_kj && 0 < strlen (R_last_kj) && NULL != R_last_ik &&
-        0 < strlen (R_last_ik) && 0 == strkcmp (R_temp_kk, R_last_ik, length) &&
-        0 == strncmp (R_temp_kk, R_last_kj, length))
-    {
-      temp_a = GNUNET_malloc (length + 1);
-      temp_b = GNUNET_malloc ((strlen (R_last_kj) - length) + 1);
-
-      length_l = 0;
-      length_r = 0;
-
-      for (cnt = 0; cnt < strlen (R_last_kj); cnt++)
-      {
-        if (cnt < length)
-        {
-          temp_a[length_l] = R_last_kj[cnt];
-          length_l++;
-        }
-        else
-        {
-          temp_b[length_r] = R_last_kj[cnt];
-          length_r++;
-        }
-      }
-      temp_a[length_l] = '\0';
-      temp_b[length_r] = '\0';
-
-      // e|(ab)+ = (ab)*
-      if (NULL != R_cur_l && 0 == strlen (R_cur_l) && 0 == strlen (temp_b))
+    /* we have no left side */
+    R_cur_l->null_flag = GNUNET_YES;
+  }
+
+  /* construct R_cur_r, if not already constructed */
+  if (GNUNET_YES == R_cur_r->null_flag)
+  {
+    length = R_temp_kk.slen - R_last_ik->slen;
+
+    /* a(ba)*bx = (ab)+x */
+    if ( (length > 0) && 
+        (GNUNET_YES != R_last_kk->null_flag) &&
+        (0 < R_last_kk->slen) &&
+        (GNUNET_YES != R_last_kj->null_flag) && 
+        (0 < R_last_kj->slen) &&
+        (GNUNET_YES != R_last_ik->null_flag) &&
+        (0 < R_last_ik->slen) &&
+        (0 == sb_strkcmp (&R_temp_kk, R_last_ik, length)) &&
+        (0 == sb_strncmp (&R_temp_kk, R_last_kj, length)) )
+    { 
+      struct StringBuffer temp_a;
+      struct StringBuffer temp_b;
+
+      sb_init (&temp_a, length);
+      sb_init (&temp_b, R_last_kj->slen - length);
+
+      length_l = length;
+      temp_a.sbuf = temp_a.abuf;
+      memcpy (temp_a.sbuf, R_last_kj->sbuf, length_l);
+      temp_a.slen = length_l;
+
+      length_r = R_last_kj->slen - length;
+      temp_b.sbuf = temp_b.abuf;
+      memcpy (temp_b.sbuf, &R_last_kj->sbuf[length], length_r);
+      temp_b.slen = length_r;
+
+      /* e|(ab)+ = (ab)* */
+      if ( (GNUNET_YES != R_cur_l->null_flag) &&
+          (0 == R_cur_l->slen) &&
+          (0 == temp_b.slen) )
       {
-        GNUNET_asprintf (&R_cur_r, "(%s%s)*", R_last_ik, temp_a);
-        GNUNET_free (R_cur_l);
-        R_cur_l = NULL;
+        sb_printf2 (R_cur_r, "(%.*s%.*s)*", 3, R_last_ik, &temp_a);
+        sb_free (R_cur_l);
+        R_cur_l->null_flag = GNUNET_YES;
       }
       else
       {
-        GNUNET_asprintf (&R_cur_r, "(%s%s)+%s", R_last_ik, temp_a, temp_b);
+        sb_printf3 (R_cur_r, "(%.*s%.*s)+%.*s", 3, R_last_ik, &temp_a, &temp_b);
       }
-      GNUNET_free (temp_a);
-      GNUNET_free (temp_b);
+      sb_free (&temp_a);
+      sb_free (&temp_b);
     }
-    else if (0 == strcmp (R_temp_ik, R_temp_kk) &&
-             0 == strcmp (R_temp_kk, R_temp_kj))
+    else if (0 == sb_strcmp (&R_temp_ik, &R_temp_kk) &&
+             0 == sb_strcmp (&R_temp_kk, &R_temp_kj))
     {
-      // (e|a)a*(e|a) = a*
-      // (e|a)(e|a)*(e|a) = a*
+      /*
+       * (e|a)a*(e|a) = a*
+       * (e|a)(e|a)*(e|a) = a*
+       */
       if (has_epsilon (R_last_ik) && has_epsilon (R_last_kj))
       {
-        if (needs_parentheses (R_temp_kk))
-          GNUNET_asprintf (&R_cur_r, "(%s)*", R_temp_kk);
+        if (needs_parentheses (&R_temp_kk))
+          sb_printf1 (R_cur_r, "(%.*s)*", 3, &R_temp_kk);
         else
-          GNUNET_asprintf (&R_cur_r, "%s*", R_temp_kk);
+          sb_printf1 (R_cur_r, "%.*s*", 1, &R_temp_kk);
       }
-      // aa*a = a+a
-      else if (0 == clean_ik_kk_cmp && 0 == clean_kk_kj_cmp &&
-               !has_epsilon (R_last_ik))
+      /* aa*a = a+a */
+      else if ( (0 == clean_ik_kk_cmp) && 
+               (0 == clean_kk_kj_cmp) &&
+               (! has_epsilon (R_last_ik)) )
       {
-        if (needs_parentheses (R_temp_kk))
-          GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
+        if (needs_parentheses (&R_temp_kk))
+          sb_printf2 (R_cur_r, "(%.*s)+%.*s", 3, &R_temp_kk, &R_temp_kk);
         else
-          GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_temp_kk);
+          sb_printf2 (R_cur_r, "%.*s+%.*s", 1, &R_temp_kk, &R_temp_kk);
       }
-      // (e|a)a*a = a+
-      // aa*(e|a) = a+
-      // a(e|a)*(e|a) = a+
-      // (e|a)a*a = a+
+      /*
+       * (e|a)a*a = a+
+       * aa*(e|a) = a+
+       * a(e|a)*(e|a) = a+
+       * (e|a)a*a = a+
+       */
       else
       {
         eps_check =
-            (has_epsilon (R_last_ik) + has_epsilon (R_last_kk) +
-             has_epsilon (R_last_kj));
+         (has_epsilon (R_last_ik) + has_epsilon (R_last_kk) +
+          has_epsilon (R_last_kj));
 
-        if (eps_check == 1)
+        if (1 == eps_check)
         {
-          if (needs_parentheses (R_temp_kk))
-            GNUNET_asprintf (&R_cur_r, "(%s)+", R_temp_kk);
+          if (needs_parentheses (&R_temp_kk))
+            sb_printf1 (R_cur_r, "(%.*s)+", 3, &R_temp_kk);
           else
-            GNUNET_asprintf (&R_cur_r, "%s+", R_temp_kk);
+            sb_printf1 (R_cur_r, "%.*s+", 1, &R_temp_kk);
         }
       }
     }
-    // aa*b = a+b
-    // (e|a)(e|a)*b = a*b
-    else if (0 == strcmp (R_temp_ik, R_temp_kk))
+    /*
+     * aa*b = a+b
+     * (e|a)(e|a)*b = a*b
+     */
+    else if (0 == sb_strcmp (&R_temp_ik, &R_temp_kk))
     {
       if (has_epsilon (R_last_ik))
       {
-        if (needs_parentheses (R_temp_kk))
-          GNUNET_asprintf (&R_cur_r, "(%s)*%s", R_temp_kk, R_last_kj);
+        if (needs_parentheses (&R_temp_kk))
+          sb_printf2 (R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_kj);
         else
-          GNUNET_asprintf (&R_cur_r, "%s*%s", R_temp_kk, R_last_kj);
+          sb_printf2 (R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_kj);
       }
       else
       {
-        if (needs_parentheses (R_temp_kk))
-          GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_temp_kk, R_last_kj);
+        if (needs_parentheses (&R_temp_kk))
+          sb_printf2 (R_cur_r, "(%.*s)+%.*s", 3, &R_temp_kk, R_last_kj);
         else
-          GNUNET_asprintf (&R_cur_r, "%s+%s", R_temp_kk, R_last_kj);
+          sb_printf2 (R_cur_r, "%.*s+%.*s", 1, &R_temp_kk, R_last_kj);
       }
     }
-    // ba*a = ba+
-    // b(e|a)*(e|a) = ba*
-    else if (0 == strcmp (R_temp_kk, R_temp_kj))
+    /*
+     * ba*a = ba+
+     * b(e|a)*(e|a) = ba*
+     */
+    else if (0 == sb_strcmp (&R_temp_kk, &R_temp_kj))
     {
       if (has_epsilon (R_last_kj))
       {
-        if (needs_parentheses (R_temp_kk))
-          GNUNET_asprintf (&R_cur_r, "%s(%s)*", R_last_ik, R_temp_kk);
+        if (needs_parentheses (&R_temp_kk))
+          sb_printf2 (R_cur_r, "%.*s(%.*s)*", 3, R_last_ik, &R_temp_kk);
         else
-          GNUNET_asprintf (&R_cur_r, "%s%s*", R_last_ik, R_temp_kk);
+          sb_printf2 (R_cur_r, "%.*s%.*s*", 1, R_last_ik, &R_temp_kk);
       }
       else
       {
-        if (needs_parentheses (R_temp_kk))
-          GNUNET_asprintf (&R_cur_r, "(%s)+%s", R_last_ik, R_temp_kk);
+        if (needs_parentheses (&R_temp_kk))
+          sb_printf2 (R_cur_r, "(%.*s)+%.*s", 3, R_last_ik, &R_temp_kk);
         else
-          GNUNET_asprintf (&R_cur_r, "%s+%s", R_last_ik, R_temp_kk);
+          sb_printf2 (R_cur_r, "%.*s+%.*s", 1, R_last_ik, &R_temp_kk);
       }
     }
     else
     {
-      if (strlen (R_temp_kk) > 0)
+      if (0 < R_temp_kk.slen)
       {
-        if (needs_parentheses (R_temp_kk))
+        if (needs_parentheses (&R_temp_kk))
         {
-          GNUNET_asprintf (&R_cur_r, "%s(%s)*%s", R_last_ik, R_temp_kk,
-                           R_last_kj);
+          sb_printf3 (R_cur_r, "%.*s(%.*s)*%.*s", 3, R_last_ik, &R_temp_kk,
+                     R_last_kj);
         }
         else
         {
-          GNUNET_asprintf (&R_cur_r, "%s%s*%s", R_last_ik, R_temp_kk,
-                           R_last_kj);
+          sb_printf3 (R_cur_r, "%.*s%.*s*%.*s", 1, R_last_ik, &R_temp_kk,
+                     R_last_kj);
         }
       }
       else
       {
-        GNUNET_asprintf (&R_cur_r, "%s%s", R_last_ik, R_last_kj);
+       sb_printf2 (R_cur_r, "%.*s%.*s", 0, R_last_ik, R_last_kj);
       }
     }
   }
+  sb_free (&R_temp_ij);
+  sb_free (&R_temp_ik);
+  sb_free (&R_temp_kk);
+  sb_free (&R_temp_kj);
 
-  GNUNET_free_non_null (R_temp_ik);
-  GNUNET_free_non_null (R_temp_kk);
-  GNUNET_free_non_null (R_temp_kj);
-
-  if (NULL == R_cur_l && NULL == R_cur_r)
+  if ( (GNUNET_YES == R_cur_l->null_flag) && 
+       (GNUNET_YES == R_cur_r->null_flag) )
   {
-    *R_cur_ij = NULL;
+    R_cur_ij->null_flag = GNUNET_YES;
     return;
   }
 
-  if (NULL != R_cur_l && NULL == R_cur_r)
+  if ( (GNUNET_YES != R_cur_l->null_flag) &&
+       (GNUNET_YES == R_cur_r->null_flag) )
   {
-    *R_cur_ij = R_cur_l;
+    struct StringBuffer tmp;
+
+    tmp = *R_cur_ij;
+    *R_cur_ij = *R_cur_l;
+    *R_cur_l = tmp;
     return;
   }
 
-  if (NULL == R_cur_l && NULL != R_cur_r)
+  if ( (GNUNET_YES == R_cur_l->null_flag) &&
+       (GNUNET_YES != R_cur_r->null_flag) )
   {
-    *R_cur_ij = R_cur_r;
+    struct StringBuffer tmp;
+
+    tmp = *R_cur_ij;
+    *R_cur_ij = *R_cur_r;
+    *R_cur_r = tmp;
     return;
   }
 
-  if (0 == nullstrcmp (R_cur_l, R_cur_r))
+  if (0 == sb_nullstrcmp (R_cur_l, R_cur_r))
   {
-    *R_cur_ij = R_cur_l;
-    GNUNET_free (R_cur_r);
+    struct StringBuffer tmp;
+
+    tmp = *R_cur_ij;
+    *R_cur_ij = *R_cur_l;
+    *R_cur_l = tmp;
     return;
   }
-
-  GNUNET_asprintf (R_cur_ij, "(%s|%s)", R_cur_l, R_cur_r);
-
-  GNUNET_free (R_cur_l);
-  GNUNET_free (R_cur_r);
+  sb_printf2 (R_cur_ij, "(%.*s|%.*s)", 3, R_cur_l, R_cur_r);
 }
 
 
 /**
- * create proofs for all states in the given automaton. Implementation of the
+ * Create proofs for all states in the given automaton. Implementation of the
  * algorithm descriped in chapter 3.2.1 of "Automata Theory, Languages, and
  * Computation 3rd Edition" by Hopcroft, Motwani and Ullman.
  *
- * @param a automaton.
+ * Each state in the automaton gets assigned 'proof' and 'hash' (hash of the
+ * proof) fields. The starting state will only have a valid proof/hash if it has
+ * any incoming transitions.
+ *
+ * @param a automaton for which to assign proofs and hashes, must not be NULL
  */
-static void
+static int
 automaton_create_proofs (struct GNUNET_REGEX_Automaton *a)
 {
-  if (NULL == a)
-  {
-    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
-                "Could not create proofs, automaton was NULL\n");
-    return;
-  }
-
   unsigned int n = a->state_count;
   struct GNUNET_REGEX_State *states[n];
-  char *R_last[n][n];
-  char *R_cur[n][n];
-  char *temp;
+  struct StringBuffer *R_last;
+  struct StringBuffer *R_cur;
+  struct StringBuffer R_cur_r;
+  struct StringBuffer R_cur_l;
+  struct StringBuffer *R_swap;
   struct GNUNET_REGEX_Transition *t;
-  char *complete_regex;
+  struct StringBuffer complete_regex;
   unsigned int i;
   unsigned int j;
   unsigned int k;
 
+  R_last = GNUNET_malloc_large (sizeof (struct StringBuffer) * n * n);
+  R_cur = GNUNET_malloc_large (sizeof (struct StringBuffer) * n * n);
+  if ( (NULL == R_last) ||
+       (NULL == R_cur) )
+  {
+    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "malloc");
+    GNUNET_free_non_null (R_cur);
+    GNUNET_free_non_null (R_last);
+    return GNUNET_SYSERR;
+  }
+
   /* create depth-first numbering of the states, initializes 'state' */
   GNUNET_REGEX_automaton_traverse (a, a->start, NULL, NULL, &number_states,
                                    states);
 
   for (i = 0; i < n; i++)
     GNUNET_assert (NULL != states[i]);
+  for (i = 0; i < n; i++)
+    for (j = 0; j < n; j++)
+      R_last[i *n + j].null_flag = GNUNET_YES;
 
   /* Compute regular expressions of length "1" between each pair of states */
   for (i = 0; i < n; i++)
   {
-    for (j = 0; j < n; j++)
-    {
-      R_cur[i][j] = NULL;
-      R_last[i][j] = NULL;
-    }
     for (t = states[i]->transitions_head; NULL != t; t = t->next)
     {
       j = t->to_state->dfs_id;
-      if (NULL == R_last[i][j])
-        GNUNET_asprintf (&R_last[i][j], "%s", t->label);
+      if (GNUNET_YES == R_last[i * n + j].null_flag)
+      {
+        sb_strdup_cstr (&R_last[i * n + j], t->label);
+      }
       else
       {
-        temp = R_last[i][j];
-        GNUNET_asprintf (&R_last[i][j], "%s|%s", R_last[i][j], t->label);
-        GNUNET_free (temp);
+       sb_append_cstr (&R_last[i * n + j], "|");
+       sb_append_cstr (&R_last[i * n + j], t->label);
       }
     }
-    if (NULL == R_last[i][i])
-      GNUNET_asprintf (&R_last[i][i], "");
+    /* add self-loop: i is reachable from i via epsilon-transition */
+    if (GNUNET_YES == R_last[i * n + i].null_flag)
+    {
+      R_last[i * n + i].slen = 0;
+      R_last[i * n + i].null_flag = GNUNET_NO;
+    }
     else
     {
-      temp = R_last[i][i];
-      GNUNET_asprintf (&R_last[i][i], "(|%s)", R_last[i][i]);
-      GNUNET_free (temp);
+      sb_wrap (&R_last[i * n + i], "(|%.*s)", 3);
     }
   }
   for (i = 0; i < n; i++)
     for (j = 0; j < n; j++)
-      if (needs_parentheses (R_last[i][j]))
-      {
-        temp = R_last[i][j];
-        GNUNET_asprintf (&R_last[i][j], "(%s)", R_last[i][j]);
-        GNUNET_free (temp);
-      }
-
+      if (needs_parentheses (&R_last[i * n + j]))
+        sb_wrap (&R_last[i * n + j], "(%.*s)", 2);  
   /* Compute regular expressions of length "k" between each pair of states per
    * induction */
+  memset (&R_cur_l, 0, sizeof (struct StringBuffer));
+  memset (&R_cur_r, 0, sizeof (struct StringBuffer));
   for (k = 0; k < n; k++)
   {
     for (i = 0; i < n; i++)
     {
       for (j = 0; j < n; j++)
       {
-        // Basis for the recursion:
-        // $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
-        // R_last == R^{(k-1)}, R_cur == R^{(k)}
-
-        // Create R_cur[i][j] and simplify the expression
-        automaton_create_proofs_simplify (R_last[i][j], R_last[i][k],
-                                          R_last[k][k], R_last[k][j],
-                                          &R_cur[i][j]);
+        /* Basis for the recursion:
+         * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj}
+         * R_last == R^{(k-1)}, R_cur == R^{(k)}
+         */
+
+        /* Create R_cur[i][j] and simplify the expression */
+        automaton_create_proofs_simplify (&R_last[i * n + j], &R_last[i * n + k],
+                                          &R_last[k * n + k], &R_last[k * n + j],
+                                          &R_cur[i * n + j],
+                                         &R_cur_l, &R_cur_r);
       }
     }
-
-    // set R_last = R_cur
+    /* set R_last = R_cur */
+    R_swap = R_last;
+    R_last = R_cur;
+    R_cur = R_swap;
+    /* clear 'R_cur' for next iteration */
     for (i = 0; i < n; i++)
-    {
       for (j = 0; j < n; j++)
-      {
-        GNUNET_free_non_null (R_last[i][j]);
-        R_last[i][j] = R_cur[i][j];
-        R_cur[i][j] = NULL;
-      }
-    }
+        R_cur[i * n + j].null_flag = GNUNET_YES;
   }
-
-  // assign proofs and hashes
+  sb_free (&R_cur_l);
+  sb_free (&R_cur_r);
+  /* assign proofs and hashes */
   for (i = 0; i < n; i++)
   {
-    if (NULL != R_last[a->start->dfs_id][i])
+    if (GNUNET_YES != R_last[a->start->dfs_id * n + i].null_flag)
     {
-      states[i]->proof = GNUNET_strdup (R_last[a->start->dfs_id][i]);
+      states[i]->proof = GNUNET_strndup (R_last[a->start->dfs_id * n + i].sbuf,
+                                        R_last[a->start->dfs_id * n + i].slen);
       GNUNET_CRYPTO_hash (states[i]->proof, strlen (states[i]->proof),
                           &states[i]->hash);
     }
   }
 
-  // complete regex for whole DFA: union of all pairs (start state/accepting
-  // state(s)).
-  complete_regex = NULL;
+  /* complete regex for whole DFA: union of all pairs (start state/accepting
+   * state(s)). */
+  sb_init (&complete_regex, 16 * n);
   for (i = 0; i < n; i++)
   {
     if (states[i]->accepting)
     {
-      if (NULL == complete_regex && 0 < strlen (R_last[a->start->dfs_id][i]))
+      if ( (0 == complete_regex.slen) &&
+          (0 < R_last[a->start->dfs_id * n + i].slen) )
       {
-        GNUNET_asprintf (&complete_regex, "%s", R_last[a->start->dfs_id][i]);
+       sb_append (&complete_regex, 
+                  &R_last[a->start->dfs_id * n + i]);
       }
-      else if (NULL != R_last[a->start->dfs_id][i] &&
-               0 < strlen (R_last[a->start->dfs_id][i]))
+      else if ( (GNUNET_YES != R_last[a->start->dfs_id * n + i].null_flag) &&
+               (0 < R_last[a->start->dfs_id * n + i].slen) )
       {
-        temp = complete_regex;
-        GNUNET_asprintf (&complete_regex, "%s|%s", complete_regex,
-                         R_last[a->start->dfs_id][i]);
-        GNUNET_free (temp);
+       sb_append_cstr (&complete_regex, "|");
+       sb_append (&complete_regex, 
+                  &R_last[a->start->dfs_id * n + i]);
       }
     }
   }
-  a->canonical_regex = complete_regex;
+  a->canonical_regex = GNUNET_strndup (complete_regex.sbuf, complete_regex.slen);
 
-  // cleanup
-  for (i = 0; i < n; i++)
-  {
+  /* cleanup */
+  sb_free (&complete_regex);
+  for (i = 0; i < n; i++)  
     for (j = 0; j < n; j++)
-      GNUNET_free_non_null (R_last[i][j]);
-  }
+    {
+      sb_free (&R_cur[i * n + j]);  
+      sb_free (&R_last[i * n + j]);  
+    }
+  GNUNET_free (R_cur);
+  GNUNET_free (R_last);
+  return GNUNET_OK;
 }
 
 
@@ -1373,22 +1768,16 @@ dfa_state_create (struct GNUNET_REGEX_Context *ctx,
                   struct GNUNET_REGEX_StateSet *nfa_states)
 {
   struct GNUNET_REGEX_State *s;
-  char *name;
-  int len = 0;
+  char *pos;
+  size_t len;
   struct GNUNET_REGEX_State *cstate;
   struct GNUNET_REGEX_Transition *ctran;
   unsigned int i;
 
   s = GNUNET_malloc (sizeof (struct GNUNET_REGEX_State));
   s->id = ctx->state_id++;
-  s->accepting = 0;
-  s->marked = GNUNET_NO;
-  s->name = NULL;
-  s->scc_id = 0;
   s->index = -1;
   s->lowlink = -1;
-  s->contained = 0;
-  s->proof = NULL;
 
   if (NULL == nfa_states)
   {
@@ -1396,45 +1785,38 @@ dfa_state_create (struct GNUNET_REGEX_Context *ctx,
     return s;
   }
 
-  s->nfa_set = nfa_states;
+  s->nfa_set = *nfa_states;
 
-  if (nfa_states->len < 1)
+  if (nfa_states->off < 1)
     return s;
 
-  // Create a name based on 'nfa_states'
-  s->name = GNUNET_malloc (sizeof (char) * 2);
+  /* Create a name based on 'nfa_states' */
+  len = nfa_states->off * 14 + 4;
+  s->name = GNUNET_malloc (len);
   strcat (s->name, "{");
-  name = NULL;
+  pos = s->name + 1;
 
-  for (i = 0; i < nfa_states->len; i++)
+  for (i = 0; i < nfa_states->off; i++)
   {
     cstate = nfa_states->states[i];
-    GNUNET_asprintf (&name, "%i,", cstate->id);
+    GNUNET_snprintf (pos, pos - s->name + len,
+                    "%i,", cstate->id);
+    pos += strlen (pos);
 
-    if (NULL != name)
-    {
-      len = strlen (s->name) + strlen (name) + 1;
-      s->name = GNUNET_realloc (s->name, len);
-      strcat (s->name, name);
-      GNUNET_free (name);
-      name = NULL;
-    }
-
-    // Add a transition for each distinct label to NULL state
-    for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)
-    {
+    /* Add a transition for each distinct label to NULL state */
+    for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next)    
       if (NULL != ctran->label)
-        state_add_transition (ctx, s, ctran->label, NULL);
-    }
+        state_add_transition (ctx, s, ctran->label, NULL);    
 
-    // If the nfa_states contain an accepting state, the new dfa state is also
-    // accepting
+    /* If the nfa_states contain an accepting state, the new dfa state is also
+     * accepting. */
     if (cstate->accepting)
       s->accepting = 1;
-  }
-
-  s->name[strlen (s->name) - 1] = '}';
+  }  
+  pos[-1] = '}';
+  s->name = GNUNET_realloc (s->name, strlen (s->name) + 1);
 
+  memset (nfa_states, 0, sizeof (struct GNUNET_REGEX_StateSet));
   return s;
 }
 
@@ -1483,6 +1865,7 @@ dfa_move (struct GNUNET_REGEX_State **s, const char *str)
   return max_len;
 }
 
+
 /**
  * Set the given state 'marked' to GNUNET_YES. Used by the
  * 'dfa_remove_unreachable_states' function to detect unreachable states in the
@@ -1492,12 +1875,13 @@ dfa_move (struct GNUNET_REGEX_State **s, const char *str)
  * @param count count, not used.
  * @param s state where the marked attribute will be set to GNUNET_YES.
  */
-void
+static void
 mark_states (void *cls, const unsigned int count, struct GNUNET_REGEX_State *s)
 {
   s->marked = GNUNET_YES;
 }
 
+
 /**
  * Remove all unreachable states from DFA 'a'. Unreachable states are those
  * states that are not reachable from the starting state.
@@ -1510,14 +1894,14 @@ dfa_remove_unreachable_states (struct GNUNET_REGEX_Automaton *a)
   struct GNUNET_REGEX_State *s;
   struct GNUNET_REGEX_State *s_next;
 
-  // 1. unmark all states
+  /* 1. unmark all states */
   for (s = a->states_head; NULL != s; s = s->next)
     s->marked = GNUNET_NO;
 
-  // 2. traverse dfa from start state and mark all visited states
+  /* 2. traverse dfa from start state and mark all visited states */
   GNUNET_REGEX_automaton_traverse (a, a->start, NULL, NULL, &mark_states, NULL);
 
-  // 3. delete all states that were not visited
+  /* 3. delete all states that were not visited */
   for (s = a->states_head; NULL != s; s = s_next)
   {
     s_next = s->next;
@@ -1537,13 +1921,16 @@ static void
 dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
 {
   struct GNUNET_REGEX_State *s;
+  struct GNUNET_REGEX_State *s_next;
   struct GNUNET_REGEX_Transition *t;
   int dead;
 
   GNUNET_assert (DFA == a->type);
 
-  for (s = a->states_head; NULL != s; s = s->next)
+  for (s = a->states_head; NULL != s; s = s_next)
   {
+    s_next = s->next;
+
     if (s->accepting)
       continue;
 
@@ -1560,7 +1947,7 @@ dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
     if (0 == dead)
       continue;
 
-    // state s is dead, remove it
+    /* state s is dead, remove it */
     automaton_remove_state (a, s);
   }
 }
@@ -1571,12 +1958,13 @@ dfa_remove_dead_states (struct GNUNET_REGEX_Automaton *a)
  *
  * @param ctx context
  * @param a DFA automaton
+ * @return GNUNET_OK on success
  */
-static void
+static int
 dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
                                      struct GNUNET_REGEX_Automaton *a)
 {
-  int table[a->state_count][a->state_count];
+  uint32_t *table;
   struct GNUNET_REGEX_State *s1;
   struct GNUNET_REGEX_State *s2;
   struct GNUNET_REGEX_Transition *t1;
@@ -1586,29 +1974,39 @@ dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
   int change;
   unsigned int num_equal_edges;
   unsigned int i;
+  unsigned int state_cnt;
+  unsigned long long idx;
+  unsigned long long idx1;
+
+  if ( (NULL == a) || (0 == a->state_count) )
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                "Could not merge nondistinguishable states, automaton was NULL.\n");
+    return GNUNET_SYSERR;
+  }
 
-  for (i = 0, s1 = a->states_head; i < a->state_count && NULL != s1;
-       i++, s1 = s1->next)
+  state_cnt = a->state_count;
+  table = GNUNET_malloc_large ((sizeof (uint32_t) * state_cnt * state_cnt / 32)  + sizeof (uint32_t));
+  if (NULL == table)
   {
-    s1->marked = i;
+    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "malloc");
+    return GNUNET_SYSERR;
   }
 
-  // Mark all pairs of accepting/!accepting states
+  for (i = 0, s1 = a->states_head; NULL != s1; s1 = s1->next)
+    s1->marked = i++;
+
+  /* Mark all pairs of accepting/!accepting states */
   for (s1 = a->states_head; NULL != s1; s1 = s1->next)
-  {
     for (s2 = a->states_head; NULL != s2; s2 = s2->next)
-    {
-      table[s1->marked][s2->marked] = 0;
-
-      if ((s1->accepting && !s2->accepting) ||
-          (!s1->accepting && s2->accepting))
+      if ( (s1->accepting && !s2->accepting) ||
+          (!s1->accepting && s2->accepting) )
       {
-        table[s1->marked][s2->marked] = 1;
+       idx = s1->marked * state_cnt + s2->marked;
+        table[idx / 32] |= (1 << (idx % 32));
       }
-    }
-  }
 
-  // Find all equal states
+  /* Find all equal states */
   change = 1;
   while (0 != change)
   {
@@ -1617,47 +2015,57 @@ dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
     {
       for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next)
       {
-        if (0 != table[s1->marked][s2->marked])
+       idx = s1->marked * state_cnt + s2->marked;
+        if (0 != (table[idx / 32] & (1 << (idx % 32))))
           continue;
-
         num_equal_edges = 0;
         for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next)
         {
           for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next)
           {
             if (0 == strcmp (t1->label, t2->label))
-            {
-              num_equal_edges++;
-              if (0 != table[t1->to_state->marked][t2->to_state->marked] ||
-                  0 != table[t2->to_state->marked][t1->to_state->marked])
-              {
-                table[s1->marked][s2->marked] = 1;
-                change = 1;
-              }
-            }
-          }
+           {
+             num_equal_edges++;
+             /* same edge, but targets definitively different, so we're different
+                as well */
+             if (t1->to_state->marked > t2->to_state->marked)
+               idx1 = t1->to_state->marked * state_cnt + t2->to_state->marked;
+             else
+               idx1 = t2->to_state->marked * state_cnt + t1->to_state->marked;
+             if (0 != (table[idx1 / 32] & (1 << (idx1 % 32))))
+             {
+               table[idx / 32] |= (1 << (idx % 32));
+               change = 1; /* changed a marker, need to run again */
+             }
+           }
+         }
         }
-        if (num_equal_edges != s1->transition_count ||
-            num_equal_edges != s2->transition_count)
+        if ( (num_equal_edges != s1->transition_count) ||
+            (num_equal_edges != s2->transition_count) )
         {
-          // Make sure ALL edges of possible equal states are the same
-          table[s1->marked][s2->marked] = -2;
+          /* Make sure ALL edges of possible equal states are the same */
+         table[idx / 32] |= (1 << (idx % 32));
+         change = 1;  /* changed a marker, need to run again */
         }
       }
     }
   }
 
-  // Merge states that are equal
+  /* Merge states that are equal */
   for (s1 = a->states_head; NULL != s1; s1 = s1_next)
   {
     s1_next = s1->next;
     for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next)
     {
       s2_next = s2->next;
-      if (table[s1->marked][s2->marked] == 0)
+      idx = s1->marked * state_cnt + s2->marked;
+      if (0 == (table[idx / 32] & (1 << (idx % 32))))
         automaton_merge_states (ctx, a, s1, s2);
     }
   }
+
+  GNUNET_free (table);
+  return GNUNET_OK;
 }
 
 
@@ -1667,24 +2075,288 @@ dfa_merge_nondistinguishable_states (struct GNUNET_REGEX_Context *ctx,
  *
  * @param ctx context
  * @param a DFA automaton
+ * @return GNUNET_OK on success
  */
-static void
+static int
 dfa_minimize (struct GNUNET_REGEX_Context *ctx,
               struct GNUNET_REGEX_Automaton *a)
 {
-  if (NULL == a)
+  if (NULL == a)
+    return GNUNET_SYSERR;
+
+  GNUNET_assert (DFA == a->type);
+
+  /* 1. remove unreachable states */
+  dfa_remove_unreachable_states (a);
+
+  /* 2. remove dead states */
+  dfa_remove_dead_states (a);
+
+  /* 3. Merge nondistinguishable states */
+  if (GNUNET_OK != dfa_merge_nondistinguishable_states (ctx, a))
+    return GNUNET_SYSERR;
+  return GNUNET_OK;
+}
+
+
+/**
+ * Context for adding strided transitions to a DFA.
+ */
+struct GNUNET_REGEX_Strided_Context
+{
+  /**
+   * Length of the strides.
+   */
+  const unsigned int stride;
+
+  /**
+   * Strided transitions DLL. New strided transitions will be stored in this DLL
+   * and afterwards added to the DFA.
+   */
+  struct GNUNET_REGEX_Transition *transitions_head;
+
+  /**
+   * Strided transitions DLL.
+   */
+  struct GNUNET_REGEX_Transition *transitions_tail;
+};
+
+
+/**
+ * Recursive helper function to add strides to a DFA.
+ *
+ * @param cls context, contains stride length and strided transitions DLL.
+ * @param depth current depth of the depth-first traversal of the graph.
+ * @param label current label, string that contains all labels on the path from
+ *        'start' to 's'.
+ * @param start start state for the depth-first traversal of the graph.
+ * @param s current state in the depth-first traversal
+ */
+void
+dfa_add_multi_strides_helper (void *cls, const unsigned int depth, char *label,
+                              struct GNUNET_REGEX_State *start,
+                              struct GNUNET_REGEX_State *s)
+{
+  struct GNUNET_REGEX_Strided_Context *ctx = cls;
+  struct GNUNET_REGEX_Transition *t;
+  char *new_label;
+
+  if (depth == ctx->stride)
+  {
+    t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
+    t->label = GNUNET_strdup (label);
+    t->to_state = s;
+    t->from_state = start;
+    GNUNET_CONTAINER_DLL_insert (ctx->transitions_head, ctx->transitions_tail,
+                                 t);
+  }
+  else
+  {
+    for (t = s->transitions_head; NULL != t; t = t->next)
+    {
+      /* Do not consider self-loops, because it end's up in too many
+       * transitions */
+      if (t->to_state == t->from_state)
+        continue;
+
+      if (NULL != label)
+      {
+        GNUNET_asprintf (&new_label, "%s%s", label, t->label);
+      }
+      else
+        new_label = GNUNET_strdup (t->label);
+
+      dfa_add_multi_strides_helper (cls, (depth + 1), new_label, start,
+                                    t->to_state);
+    }
+  }
+  GNUNET_free_non_null (label);
+}
+
+
+/**
+ * Function called for each state in the DFA. Starts a traversal of depth set in
+ * context starting from state 's'.
+ *
+ * @param cls context.
+ * @param count not used.
+ * @param s current state.
+ */
+void
+dfa_add_multi_strides (void *cls, const unsigned int count,
+                       struct GNUNET_REGEX_State *s)
+{
+  dfa_add_multi_strides_helper (cls, 0, NULL, s, s);
+}
+
+
+/**
+ * Adds multi-strided transitions to the given 'dfa'.
+ *
+ * @param regex_ctx regex context needed to add transitions to the automaton.
+ * @param dfa DFA to which the multi strided transitions should be added.
+ * @param stride_len length of the strides.
+ */
+void
+GNUNET_REGEX_dfa_add_multi_strides (struct GNUNET_REGEX_Context *regex_ctx,
+                                    struct GNUNET_REGEX_Automaton *dfa,
+                                    const unsigned int stride_len)
+{
+  struct GNUNET_REGEX_Strided_Context ctx = { stride_len, NULL, NULL };
+  struct GNUNET_REGEX_Transition *t;
+  struct GNUNET_REGEX_Transition *t_next;
+
+  if (1 > stride_len || GNUNET_YES == dfa->is_multistrided)
+    return;
+
+  /* Compute the new transitions of given stride_len */
+  GNUNET_REGEX_automaton_traverse (dfa, dfa->start, NULL, NULL,
+                                   &dfa_add_multi_strides, &ctx);
+
+  /* Add all the new transitions to the automaton. */
+  for (t = ctx.transitions_head; NULL != t; t = t_next)
+  {
+    t_next = t->next;
+    state_add_transition (regex_ctx, t->from_state, t->label, t->to_state);
+    GNUNET_CONTAINER_DLL_remove (ctx.transitions_head, ctx.transitions_tail, t);
+    GNUNET_free_non_null (t->label);
+    GNUNET_free (t);
+  }
+
+  /* Mark this automaton as multistrided */
+  dfa->is_multistrided = GNUNET_YES;
+}
+
+/**
+ * Recursive Helper function for DFA path compression. Does DFS on the DFA graph
+ * and adds new transitions to the given transitions DLL and marks states that
+ * should be removed by setting state->contained to GNUNET_YES.
+ *
+ * @param dfa DFA for which the paths should be compressed.
+ * @param start starting state for linear path search.
+ * @param cur current state in the recursive DFS.
+ * @param label current label (string of traversed labels).
+ * @param max_len maximal path compression length.
+ * @param transitions_head transitions DLL.
+ * @param transitions_tail transitions DLL.
+ */
+void
+dfa_compress_paths_helper (struct GNUNET_REGEX_Automaton *dfa,
+                           struct GNUNET_REGEX_State *start,
+                           struct GNUNET_REGEX_State *cur, char *label,
+                           unsigned int max_len,
+                           struct GNUNET_REGEX_Transition **transitions_head,
+                           struct GNUNET_REGEX_Transition **transitions_tail)
+{
+  struct GNUNET_REGEX_Transition *t;
+  char *new_label;
+
+
+  if (NULL != label &&
+      ((cur->incoming_transition_count > 1 || GNUNET_YES == cur->accepting ||
+        GNUNET_YES == cur->marked) || (start != dfa->start && max_len > 0 &&
+                                       max_len == strlen (label)) ||
+       (start == dfa->start && GNUNET_REGEX_INITIAL_BYTES == strlen (label))))
+  {
+    t = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Transition));
+    t->label = GNUNET_strdup (label);
+    t->to_state = cur;
+    t->from_state = start;
+    GNUNET_CONTAINER_DLL_insert (*transitions_head, *transitions_tail, t);
+
+    if (GNUNET_NO == cur->marked)
+    {
+      dfa_compress_paths_helper (dfa, cur, cur, NULL, max_len, transitions_head,
+                                 transitions_tail);
+    }
+    return;
+  }
+  else if (cur != start)
+    cur->contained = GNUNET_YES;
+
+  if (GNUNET_YES == cur->marked && cur != start)
+    return;
+
+  cur->marked = GNUNET_YES;
+
+
+  for (t = cur->transitions_head; NULL != t; t = t->next)
+  {
+    if (NULL != label)
+      GNUNET_asprintf (&new_label, "%s%s", label, t->label);
+    else
+      new_label = GNUNET_strdup (t->label);
+
+    if (t->to_state != cur)
+    {
+      dfa_compress_paths_helper (dfa, start, t->to_state, new_label, max_len,
+                                 transitions_head, transitions_tail);
+    }
+    GNUNET_free (new_label);
+  }
+}
+
+
+/**
+ * Compress paths in the given 'dfa'. Linear paths like 0->1->2->3 will be
+ * compressed to 0->3 by combining transitions.
+ *
+ * @param regex_ctx context for adding new transitions.
+ * @param dfa DFA representation, will directly modify the given DFA.
+ * @param max_len maximal length of the compressed paths.
+ */
+static void
+dfa_compress_paths (struct GNUNET_REGEX_Context *regex_ctx,
+                    struct GNUNET_REGEX_Automaton *dfa, unsigned int max_len)
+{
+  struct GNUNET_REGEX_State *s;
+  struct GNUNET_REGEX_State *s_next;
+  struct GNUNET_REGEX_Transition *t;
+  struct GNUNET_REGEX_Transition *t_next;
+  struct GNUNET_REGEX_Transition *transitions_head = NULL;
+  struct GNUNET_REGEX_Transition *transitions_tail = NULL;
+
+  if (NULL == dfa)
     return;
 
-  GNUNET_assert (DFA == a->type);
+  /* Count the incoming transitions on each state. */
+  for (s = dfa->states_head; NULL != s; s = s->next)
+  {
+    for (t = s->transitions_head; NULL != t; t = t->next)
+    {
+      if (NULL != t->to_state)
+        t->to_state->incoming_transition_count++;
+    }
+  }
 
-  // 1. remove unreachable states
-  dfa_remove_unreachable_states (a);
+  /* Unmark all states. */
+  for (s = dfa->states_head; NULL != s; s = s->next)
+  {
+    s->marked = GNUNET_NO;
+    s->contained = GNUNET_NO;
+  }
 
-  // 2. remove dead states
-  dfa_remove_dead_states (a);
+  /* Add strides and mark states that can be deleted. */
+  dfa_compress_paths_helper (dfa, dfa->start, dfa->start, NULL, max_len,
+                             &transitions_head, &transitions_tail);
+
+  /* Add all the new transitions to the automaton. */
+  for (t = transitions_head; NULL != t; t = t_next)
+  {
+    t_next = t->next;
+    state_add_transition (regex_ctx, t->from_state, t->label, t->to_state);
+    GNUNET_CONTAINER_DLL_remove (transitions_head, transitions_tail, t);
+    GNUNET_free_non_null (t->label);
+    GNUNET_free (t);
+  }
 
-  // 3. Merge nondistinguishable states
-  dfa_merge_nondistinguishable_states (ctx, a);
+  /* Remove marked states (including their incoming and outgoing transitions). */
+  for (s = dfa->states_head; NULL != s; s = s_next)
+  {
+    s_next = s->next;
+    if (GNUNET_YES == s->contained)
+      automaton_remove_state (dfa, s);
+  }
 }
 
 
@@ -1791,127 +2463,73 @@ nfa_state_create (struct GNUNET_REGEX_Context *ctx, int accepting)
 }
 
 
-/**
- * Calculates the NFA closure set for the given state.
- *
- * @param nfa the NFA containing 's'
- * @param s starting point state
- * @param label transitioning label on which to base the closure on,
- *                pass NULL for epsilon transition
- *
- * @return sorted nfa closure on 'label' (epsilon closure if 'label' is NULL)
- */
-static struct GNUNET_REGEX_StateSet *
-nfa_closure_create (struct GNUNET_REGEX_Automaton *nfa,
-                    struct GNUNET_REGEX_State *s, const char *label)
-{
-  struct GNUNET_REGEX_StateSet *cls;
-  struct GNUNET_REGEX_StateSet *cls_check;
-  struct GNUNET_REGEX_State *clsstate;
-  struct GNUNET_REGEX_State *currentstate;
-  struct GNUNET_REGEX_Transition *ctran;
-
-  if (NULL == s)
-    return NULL;
-
-  cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
-  cls_check = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
-
-  for (clsstate = nfa->states_head; NULL != clsstate; clsstate = clsstate->next)
-    clsstate->contained = 0;
-
-  // Add start state to closure only for epsilon closure
-  if (NULL == label)
-    GNUNET_array_append (cls->states, cls->len, s);
-
-  GNUNET_array_append (cls_check->states, cls_check->len, s);
-  while (cls_check->len > 0)
-  {
-    currentstate = cls_check->states[cls_check->len - 1];
-    GNUNET_array_grow (cls_check->states, cls_check->len, cls_check->len - 1);
-
-    for (ctran = currentstate->transitions_head; NULL != ctran;
-         ctran = ctran->next)
-    {
-      if (NULL != ctran->to_state && 0 == nullstrcmp (label, ctran->label))
-      {
-        clsstate = ctran->to_state;
-
-        if (NULL != clsstate && 0 == clsstate->contained)
-        {
-          GNUNET_array_append (cls->states, cls->len, clsstate);
-          GNUNET_array_append (cls_check->states, cls_check->len, clsstate);
-          clsstate->contained = 1;
-        }
-      }
-    }
-  }
-  GNUNET_assert (0 == cls_check->len);
-  GNUNET_free (cls_check);
-
-  // sort the states
-  if (cls->len > 1)
-    qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
-           state_compare);
-
-  return cls;
-}
-
-
 /**
  * Calculates the closure set for the given set of states.
  *
+ * @param ret set to sorted nfa closure on 'label' (epsilon closure if 'label' is NULL)
  * @param nfa the NFA containing 's'
  * @param states list of states on which to base the closure on
  * @param label transitioning label for which to base the closure on,
  *                pass NULL for epsilon transition
- *
- * @return sorted nfa closure on 'label' (epsilon closure if 'label' is NULL)
  */
-static struct GNUNET_REGEX_StateSet *
-nfa_closure_set_create (struct GNUNET_REGEX_Automaton *nfa,
+static void
+nfa_closure_set_create (struct GNUNET_REGEX_StateSet *ret,
+                       struct GNUNET_REGEX_Automaton *nfa,
                         struct GNUNET_REGEX_StateSet *states, const char *label)
 {
   struct GNUNET_REGEX_State *s;
-  struct GNUNET_REGEX_StateSet *sset;
-  struct GNUNET_REGEX_StateSet *cls;
   unsigned int i;
-  unsigned int j;
-  unsigned int k;
-  unsigned int contains;
+  struct GNUNET_REGEX_StateSet_MDLL cls_stack;
+  struct GNUNET_REGEX_State *clsstate;
+  struct GNUNET_REGEX_State *currentstate;
+  struct GNUNET_REGEX_Transition *ctran;
 
+  memset (ret, 0, sizeof (struct GNUNET_REGEX_StateSet));
   if (NULL == states)
-    return NULL;
-
-  cls = GNUNET_malloc (sizeof (struct GNUNET_REGEX_StateSet));
+    return;
 
-  for (i = 0; i < states->len; i++)
+  for (i = 0; i < states->off; i++)
   {
     s = states->states[i];
-    sset = nfa_closure_create (nfa, s, label);
 
-    for (j = 0; j < sset->len; j++)
+    /* Add start state to closure only for epsilon closure */
+    if (NULL == label)
+      state_set_append (ret, s);
+    
+    /* initialize work stack */
+    cls_stack.head = NULL;
+    cls_stack.tail = NULL;
+    GNUNET_CONTAINER_MDLL_insert (ST, cls_stack.head, cls_stack.tail, s);
+    cls_stack.len = 1;
+
+    while (NULL != (currentstate = cls_stack.tail))
     {
-      contains = 0;
-      for (k = 0; k < cls->len; k++)
+      GNUNET_CONTAINER_MDLL_remove (ST, cls_stack.head, cls_stack.tail,
+                                   currentstate);
+      cls_stack.len--;      
+      for (ctran = currentstate->transitions_head; NULL != ctran;
+          ctran = ctran->next)
       {
-        if (sset->states[j]->id == cls->states[k]->id)
-        {
-          contains = 1;
-          break;
-        }
-      }
-      if (!contains)
-        GNUNET_array_append (cls->states, cls->len, sset->states[j]);
+       if (NULL == (clsstate = ctran->to_state))
+         continue;
+       if (0 != clsstate->contained)
+         continue;
+       if (0 != nullstrcmp (label, ctran->label))
+         continue;
+       state_set_append (ret, clsstate);
+       GNUNET_CONTAINER_MDLL_insert_tail (ST, cls_stack.head, cls_stack.tail,
+                                          clsstate);
+       cls_stack.len++;
+       clsstate->contained = 1;
+      }    
     }
-    state_set_clear (sset);
   }
+  for (i = 0; i < ret->off; i++)
+    ret->states[i]->contained = 0;
 
-  if (cls->len > 1)
-    qsort (cls->states, cls->len, sizeof (struct GNUNET_REGEX_State *),
-           state_compare);
-
-  return cls;
+  if (ret->off > 1)
+    qsort (ret->states, ret->off, sizeof (struct GNUNET_REGEX_State *),
+           &state_compare);
 }
 
 
@@ -2005,6 +2623,14 @@ nfa_add_plus_op (struct GNUNET_REGEX_Context *ctx)
   struct GNUNET_REGEX_Automaton *a;
 
   a = ctx->stack_tail;
+
+  if (NULL == a)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                "nfa_add_plus_op failed, because there was no element on the stack");
+    return;
+  }
+
   GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a);
 
   state_add_transition (ctx, a->end, NULL, a->start);
@@ -2048,9 +2674,8 @@ nfa_add_question_op (struct GNUNET_REGEX_Context *ctx)
 
   new_nfa = nfa_fragment_create (start, end);
   nfa_add_states (new_nfa, a->states_head, a->states_tail);
-  automaton_fragment_clear (a);
-
   GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa);
+  automaton_fragment_clear (a);
 }
 
 
@@ -2161,7 +2786,8 @@ GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
   unsigned int count;
   unsigned int altcount;
   unsigned int atomcount;
-  unsigned int pcount;
+  unsigned int poff;
+  unsigned int psize;
   struct
   {
     int altcount;
@@ -2175,7 +2801,6 @@ GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
 
     return NULL;
   }
-
   GNUNET_REGEX_context_init (&ctx);
 
   regexp = regex;
@@ -2184,7 +2809,8 @@ GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
   error_msg = NULL;
   altcount = 0;
   atomcount = 0;
-  pcount = 0;
+  poff = 0;
+  psize = 0;
 
   for (count = 0; count < len && *regexp; count++, regexp++)
   {
@@ -2196,9 +2822,11 @@ GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
         --atomcount;
         nfa_add_concatenation (&ctx);
       }
-      GNUNET_array_grow (p, pcount, pcount + 1);
-      p[pcount - 1].altcount = altcount;
-      p[pcount - 1].atomcount = atomcount;
+      if (poff == psize)
+       GNUNET_array_grow (p, psize, psize * 2 + 4);
+      p[poff].altcount = altcount;
+      p[poff].atomcount = atomcount;
+      poff++;
       altcount = 0;
       atomcount = 0;
       break;
@@ -2213,26 +2841,26 @@ GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
       altcount++;
       break;
     case ')':
-      if (0 == pcount)
+      if (0 == poff)
       {
         error_msg = "Missing opening '('";
         goto error;
       }
       if (0 == atomcount)
       {
-        // Ignore this: "()"
-        pcount--;
-        altcount = p[pcount].altcount;
-        atomcount = p[pcount].atomcount;
+        /* Ignore this: "()" */
+        poff--;
+        altcount = p[poff].altcount;
+        atomcount = p[poff].atomcount;
         break;
       }
       while (--atomcount > 0)
         nfa_add_concatenation (&ctx);
       for (; altcount > 0; altcount--)
         nfa_add_alternation (&ctx);
-      pcount--;
-      altcount = p[pcount].altcount;
-      atomcount = p[pcount].atomcount;
+      poff--;
+      altcount = p[poff].altcount;
+      atomcount = p[poff].atomcount;
       atomcount++;
       break;
     case '*':
@@ -2271,7 +2899,7 @@ GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
       break;
     }
   }
-  if (0 != pcount)
+  if (0 != poff)
   {
     error_msg = "Unbalanced parenthesis";
     goto error;
@@ -2281,7 +2909,7 @@ GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
   for (; altcount > 0; altcount--)
     nfa_add_alternation (&ctx);
 
-  GNUNET_free_non_null (p);
+  GNUNET_array_grow (p, psize, 0);
 
   nfa = ctx.stack_tail;
   GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa);
@@ -2304,7 +2932,7 @@ GNUNET_REGEX_construct_nfa (const char *regex, const size_t len)
   return nfa;
 
 error:
-  GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: %s\n", regex);
+  GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: `%s'\n", regex);
   if (NULL != error_msg)
     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg);
 
@@ -2336,31 +2964,34 @@ construct_dfa_states (struct GNUNET_REGEX_Context *ctx,
                       struct GNUNET_REGEX_State *dfa_state)
 {
   struct GNUNET_REGEX_Transition *ctran;
-  struct GNUNET_REGEX_State *state_iter;
   struct GNUNET_REGEX_State *new_dfa_state;
   struct GNUNET_REGEX_State *state_contains;
-  struct GNUNET_REGEX_StateSet *tmp;
-  struct GNUNET_REGEX_StateSet *nfa_set;
+  struct GNUNET_REGEX_State *state_iter;
+  struct GNUNET_REGEX_StateSet tmp;
+  struct GNUNET_REGEX_StateSet nfa_set;
 
   for (ctran = dfa_state->transitions_head; NULL != ctran; ctran = ctran->next)
   {
     if (NULL == ctran->label || NULL != ctran->to_state)
       continue;
 
-    tmp = nfa_closure_set_create (nfa, dfa_state->nfa_set, ctran->label);
-    nfa_set = nfa_closure_set_create (nfa, tmp, 0);
-    state_set_clear (tmp);
-    new_dfa_state = dfa_state_create (ctx, nfa_set);
+    nfa_closure_set_create (&tmp, nfa, &dfa_state->nfa_set, ctran->label);
+    nfa_closure_set_create (&nfa_set, nfa, &tmp, NULL);
+    state_set_clear (&tmp);
+
     state_contains = NULL;
     for (state_iter = dfa->states_head; NULL != state_iter;
          state_iter = state_iter->next)
     {
-      if (0 == state_set_compare (state_iter->nfa_set, new_dfa_state->nfa_set))
+      if (0 == state_set_compare (&state_iter->nfa_set, &nfa_set))
+      {
         state_contains = state_iter;
+       break;
+      }
     }
-
     if (NULL == state_contains)
     {
+      new_dfa_state = dfa_state_create (ctx, &nfa_set);
       automaton_add_state (dfa, new_dfa_state);
       ctran->to_state = new_dfa_state;
       construct_dfa_states (ctx, nfa, dfa, new_dfa_state);
@@ -2368,31 +2999,43 @@ construct_dfa_states (struct GNUNET_REGEX_Context *ctx,
     else
     {
       ctran->to_state = state_contains;
-      automaton_destroy_state (new_dfa_state);
+      state_set_clear (&nfa_set);
     }
   }
 }
 
 
 /**
- * Construct DFA for the given 'regex' of length 'len'
- *
- * @param regex regular expression string
- * @param len length of the regular expression
- *
- * @return DFA, needs to be freed using GNUNET_REGEX_destroy_automaton
+ * Construct DFA for the given 'regex' of length 'len'.
+ *
+ * Path compression means, that for example a DFA o -> a -> b -> c -> o will be
+ * compressed to o -> abc -> o. Note that this parameter influences the
+ * non-determinism of states of the resulting NFA in the DHT (number of outgoing
+ * edges with the same label). For example for an application that stores IPv4
+ * addresses as bitstrings it could make sense to limit the path compression to
+ * 4 or 8.
+ *
+ * @param regex regular expression string.
+ * @param len length of the regular expression.
+ * @param max_path_len limit the path compression length to the
+ *        given value. If set to 1, no path compression is applied. Set to 0 for
+ *        maximal possible path compression (generally not desireable).
+ * @return DFA, needs to be freed using GNUNET_REGEX_automaton_destroy.
  */
 struct GNUNET_REGEX_Automaton *
-GNUNET_REGEX_construct_dfa (const char *regex, const size_t len)
+GNUNET_REGEX_construct_dfa (const char *regex, const size_t len,
+                            unsigned int max_path_len)
 {
   struct GNUNET_REGEX_Context ctx;
   struct GNUNET_REGEX_Automaton *dfa;
   struct GNUNET_REGEX_Automaton *nfa;
-  struct GNUNET_REGEX_StateSet *nfa_start_eps_cls;
+  struct GNUNET_REGEX_StateSet nfa_start_eps_cls;
+  struct GNUNET_REGEX_StateSet singleton_set;
 
   GNUNET_REGEX_context_init (&ctx);
 
-  // Create NFA
+  /* Create NFA */
+  // fprintf (stderr, "N");
   nfa = GNUNET_REGEX_construct_nfa (regex, len);
 
   if (NULL == nfa)
@@ -2404,29 +3047,38 @@ GNUNET_REGEX_construct_dfa (const char *regex, const size_t len)
 
   dfa = GNUNET_malloc (sizeof (struct GNUNET_REGEX_Automaton));
   dfa->type = DFA;
-  dfa->state_count = 0;
-  dfa->states_head = NULL;
-  dfa->states_tail = NULL;
   dfa->regex = GNUNET_strdup (regex);
-  dfa->is_multistrided = GNUNET_NO;
 
-  // Create DFA start state from epsilon closure
-  nfa_start_eps_cls = nfa_closure_create (nfa, nfa->start, 0);
-  dfa->start = dfa_state_create (&ctx, nfa_start_eps_cls);
+  /* Create DFA start state from epsilon closure */
+  memset (&singleton_set, 0, sizeof (struct GNUNET_REGEX_StateSet));
+  state_set_append (&singleton_set, nfa->start);
+  nfa_closure_set_create (&nfa_start_eps_cls, nfa, &singleton_set, NULL);
+  state_set_clear (&singleton_set);
+  dfa->start = dfa_state_create (&ctx, &nfa_start_eps_cls);
   automaton_add_state (dfa, dfa->start);
 
+  // fprintf (stderr, "D");
   construct_dfa_states (&ctx, nfa, dfa, dfa->start);
-
   GNUNET_REGEX_automaton_destroy (nfa);
 
-  // Minimize DFA
-  dfa_minimize (&ctx, dfa);
+  /* Minimize DFA */
+  // fprintf (stderr, "M");
+  if (GNUNET_OK != dfa_minimize (&ctx, dfa))
+  {
+    GNUNET_REGEX_automaton_destroy (dfa);
+    return NULL;
+  }
 
-  // Create proofs for all states
-  automaton_create_proofs (dfa);
+  /* Create proofs and hashes for all states */
+  if (GNUNET_OK != automaton_create_proofs (dfa))
+  {
+    GNUNET_REGEX_automaton_destroy (dfa);
+    return NULL;
+  }
 
-  // Add strides to DFA
-  // GNUNET_REGEX_add_multi_strides_to_dfa (&ctx, dfa, 2);
+  /* Compress linear DFA paths */
+  if (1 != max_path_len)
+    dfa_compress_paths (&ctx, dfa, max_path_len);
 
   return dfa;
 }
@@ -2450,11 +3102,11 @@ GNUNET_REGEX_automaton_destroy (struct GNUNET_REGEX_Automaton *a)
   GNUNET_free_non_null (a->regex);
   GNUNET_free_non_null (a->canonical_regex);
 
-  for (s = a->states_head; NULL != s;)
+  for (s = a->states_head; NULL != s; s = next_state)
   {
     next_state = s->next;
+    GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s);
     automaton_destroy_state (s);
-    s = next_state;
   }
 
   GNUNET_free (a);
@@ -2485,7 +3137,7 @@ evaluate_dfa (struct GNUNET_REGEX_Automaton *a, const char *string)
 
   s = a->start;
 
-  // If the string is empty but the starting state is accepting, we accept.
+  /* If the string is empty but the starting state is accepting, we accept. */
   if ((NULL == string || 0 == strlen (string)) && s->accepting)
     return 0;
 
@@ -2518,8 +3170,9 @@ evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
   const char *strp;
   char str[2];
   struct GNUNET_REGEX_State *s;
-  struct GNUNET_REGEX_StateSet *sset;
-  struct GNUNET_REGEX_StateSet *new_sset;
+  struct GNUNET_REGEX_StateSet sset;
+  struct GNUNET_REGEX_StateSet new_sset;
+  struct GNUNET_REGEX_StateSet singleton_set;
   unsigned int i;
   int result;
 
@@ -2530,34 +3183,37 @@ evaluate_nfa (struct GNUNET_REGEX_Automaton *a, const char *string)
     return -1;
   }
 
-  // If the string is empty but the starting state is accepting, we accept.
+  /* If the string is empty but the starting state is accepting, we accept. */
   if ((NULL == string || 0 == strlen (string)) && a->start->accepting)
     return 0;
 
   result = 1;
-  sset = nfa_closure_create (a, a->start, 0);
+  memset (&singleton_set, 0, sizeof (struct GNUNET_REGEX_StateSet));
+  state_set_append (&singleton_set, a->start);
+  nfa_closure_set_create (&sset, a, &singleton_set, NULL);
+  state_set_clear (&singleton_set);
 
   str[1] = '\0';
   for (strp = string; NULL != strp && *strp; strp++)
   {
     str[0] = *strp;
-    new_sset = nfa_closure_set_create (a, sset, str);
-    state_set_clear (sset);
-    sset = nfa_closure_set_create (a, new_sset, 0);
-    state_set_clear (new_sset);
+    nfa_closure_set_create (&new_sset, a, &sset, str);
+    state_set_clear (&sset);
+    nfa_closure_set_create (&sset, a, &new_sset, 0);
+    state_set_clear (&new_sset);
   }
 
-  for (i = 0; i < sset->len; i++)
+  for (i = 0; i < sset.off; i++)
   {
-    s = sset->states[i];
-    if (NULL != s && s->accepting)
+    s = sset.states[i];
+    if ( (NULL != s) && (s->accepting) )
     {
       result = 0;
       break;
     }
   }
 
-  state_set_clear (sset);
+  state_set_clear (&sset);
   return result;
 }
 
@@ -2631,10 +3287,9 @@ GNUNET_REGEX_get_transition_count (struct GNUNET_REGEX_Automaton *a)
   if (NULL == a)
     return 0;
 
-  for (t_count = 0, s = a->states_head; NULL != s; s = s->next)
-  {
+  t_count = 0;
+  for (s = a->states_head; NULL != s; s = s->next)
     t_count += s->transition_count;
-  }
 
   return t_count;
 }
@@ -2657,7 +3312,9 @@ GNUNET_REGEX_get_first_key (const char *input_string, size_t string_len,
 {
   unsigned int size;
 
-  size = string_len < INITIAL_BITS ? string_len : INITIAL_BITS;
+  size =
+      string_len <
+      GNUNET_REGEX_INITIAL_BYTES ? string_len : GNUNET_REGEX_INITIAL_BYTES;
 
   if (NULL == input_string)
   {
@@ -2697,12 +3354,10 @@ GNUNET_REGEX_check_proof (const char *proof, const struct GNUNET_HashCode *key)
 
 
 /**
- * Recursive helper function for iterate_initial_edges. Will call iterator
- * function for each initial state.
+ * Recursive function that calls the iterator for each synthetic start state.
  *
  * @param min_len minimum length of the path in the graph.
  * @param max_len maximum length of the path in the graph.
- * @param cur_len current length of the path already traversed.
  * @param consumed_string string consumed by traversing the graph till this state.
  * @param state current state of the automaton.
  * @param iterator iterator function called for each edge.
@@ -2710,8 +3365,7 @@ GNUNET_REGEX_check_proof (const char *proof, const struct GNUNET_HashCode *key)
  */
 static void
 iterate_initial_edge (const unsigned int min_len, const unsigned int max_len,
-                      unsigned int cur_len, char *consumed_string,
-                      struct GNUNET_REGEX_State *state,
+                      char *consumed_string, struct GNUNET_REGEX_State *state,
                       GNUNET_REGEX_KeyIterator iterator, void *iterator_cls)
 {
   unsigned int i;
@@ -2719,24 +3373,64 @@ iterate_initial_edge (const unsigned int min_len, const unsigned int max_len,
   struct GNUNET_REGEX_Transition *t;
   unsigned int num_edges = state->transition_count;
   struct GNUNET_REGEX_Edge edges[num_edges];
+  struct GNUNET_REGEX_Edge edge[1];
   struct GNUNET_HashCode hash;
+  struct GNUNET_HashCode hash_new;
+
+  unsigned int cur_len;
+
+  if (NULL != consumed_string)
+    cur_len = strlen (consumed_string);
+  else
+    cur_len = 0;
 
-  if (cur_len > min_len && NULL != consumed_string && cur_len <= max_len)
+  if ((cur_len >= min_len || GNUNET_YES == state->accepting) && cur_len > 0 &&
+      NULL != consumed_string)
   {
-    for (i = 0, t = state->transitions_head; NULL != t; t = t->next, i++)
+    if (cur_len <= max_len)
     {
-      edges[i].label = t->label;
-      edges[i].destination = t->to_state->hash;
-    }
+      if (state->proof != NULL && 0 != strcmp (consumed_string, state->proof))
+      {
+        for (i = 0, t = state->transitions_head; NULL != t && i < num_edges;
+             t = t->next, i++)
+        {
+          edges[i].label = t->label;
+          edges[i].destination = t->to_state->hash;
+        }
+        GNUNET_CRYPTO_hash (consumed_string, strlen (consumed_string), &hash);
+        iterator (iterator_cls, &hash, consumed_string, state->accepting,
+                  num_edges, edges);
+      }
 
-    GNUNET_CRYPTO_hash (consumed_string, strlen (consumed_string), &hash);
-    iterator (iterator_cls, &hash, consumed_string, state->accepting, num_edges,
-              edges);
+      if (GNUNET_YES == state->accepting && cur_len > 1 &&
+          state->transition_count < 1 && cur_len < max_len)
+      {
+        /* Special case for regex consisting of just a string that is shorter than
+         * max_len */
+        edge[0].label = &consumed_string[cur_len - 1];
+        edge[0].destination = state->hash;
+        temp = GNUNET_strdup (consumed_string);
+        temp[cur_len - 1] = '\0';
+        GNUNET_CRYPTO_hash (temp, cur_len - 1, &hash_new);
+        iterator (iterator_cls, &hash_new, temp, GNUNET_NO, 1, edge);
+        GNUNET_free (temp);
+      }
+    }
+    else if (max_len < cur_len)
+    {
+      /* Case where the concatenated labels are longer than max_len, then split. */
+      edge[0].label = &consumed_string[max_len];
+      edge[0].destination = state->hash;
+      temp = GNUNET_strdup (consumed_string);
+      temp[max_len] = '\0';
+      GNUNET_CRYPTO_hash (temp, max_len, &hash);
+      iterator (iterator_cls, &hash, temp, GNUNET_NO, 1, edge);
+      GNUNET_free (temp);
+    }
   }
 
   if (cur_len < max_len)
   {
-    cur_len++;
     for (t = state->transitions_head; NULL != t; t = t->next)
     {
       if (NULL != consumed_string)
@@ -2744,8 +3438,8 @@ iterate_initial_edge (const unsigned int min_len, const unsigned int max_len,
       else
         GNUNET_asprintf (&temp, "%s", t->label);
 
-      iterate_initial_edge (min_len, max_len, cur_len, temp, t->to_state,
-                            iterator, iterator_cls);
+      iterate_initial_edge (min_len, max_len, temp, t->to_state, iterator,
+                            iterator_cls);
       GNUNET_free (temp);
     }
   }
@@ -2753,116 +3447,276 @@ iterate_initial_edge (const unsigned int min_len, const unsigned int max_len,
 
 
 /**
- * Iterate over all initial edges that aren't actually part of the automaton.
- * This is needed to find the initial states returned by
- * GNUNET_REGEX_get_first_key. Iteration will start at the first state that has
- * more than one outgoing edge, i.e. the state that branches the graph.
- * For example consider the following graph:
- * a -> b -> c -> d -> ...
- *            \-> e -> ...
- *
- * This function will not iterate over the edges leading to "c", because these
- * will be covered by the iterate_edges function.
+ * Iterate over all edges starting from start state of automaton 'a'. Calling
+ * iterator for each edge.
  *
- * @param a the automaton for which the initial states should be computed.
- * @param initial_len length of the initial state string.
- * @param iterator iterator function called for each edge.
- * @param iterator_cls closure for the iterator function.
+ * @param a automaton.
+ * @param iterator iterator called for each edge.
+ * @param iterator_cls closure.
  */
 void
-iterate_initial_edges (struct GNUNET_REGEX_Automaton *a,
-                       const unsigned int initial_len,
-                       GNUNET_REGEX_KeyIterator iterator, void *iterator_cls)
+GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
+                                GNUNET_REGEX_KeyIterator iterator,
+                                void *iterator_cls)
 {
-  char *consumed_string;
-  char *temp;
   struct GNUNET_REGEX_State *s;
-  unsigned int cur_len;
 
-  if (1 > initial_len)
-    return;
+  for (s = a->states_head; NULL != s; s = s->next)
+  {
+    struct GNUNET_REGEX_Edge edges[s->transition_count];
+    unsigned int num_edges;
 
-  consumed_string = NULL;
-  s = a->start;
-  cur_len = 0;
+    num_edges = state_get_edges (s, edges);
 
-  if (1 == s->transition_count)
-  {
-    do
-    {
-      if (NULL != consumed_string)
-      {
-        temp = consumed_string;
-        GNUNET_asprintf (&consumed_string, "%s%s", consumed_string,
-                         s->transitions_head->label);
-        GNUNET_free (temp);
-      }
-      else
-        GNUNET_asprintf (&consumed_string, "%s", s->transitions_head->label);
+    if ((NULL != s->proof && 0 < strlen (s->proof)) || s->accepting)
+      iterator (iterator_cls, &s->hash, s->proof, s->accepting, num_edges,
+                edges);
 
-      s = s->transitions_head->to_state;
-      cur_len += strlen (s->transitions_head->label);
-    }
-    while (cur_len < initial_len && 1 == s->transition_count);
+    s->marked = GNUNET_NO;
   }
 
-  iterate_initial_edge (cur_len, initial_len, cur_len, consumed_string, s,
-                        iterator, iterator_cls);
-
-  GNUNET_free_non_null (consumed_string);
+  iterate_initial_edge (GNUNET_REGEX_INITIAL_BYTES, GNUNET_REGEX_INITIAL_BYTES,
+                        NULL, a->start, iterator, iterator_cls);
 }
 
 
 /**
- * Iterate over all edges helper function starting from state 's', calling
- * iterator function for each edge.
+ * Create a string with binary IP notation for the given 'addr' in 'str'.
  *
- * @param s state.
- * @param iterator iterator function called for each edge.
- * @param iterator_cls closure.
+ * @param af address family of the given 'addr'.
+ * @param addr address that should be converted to a string.
+ *             struct in_addr * for IPv4 and struct in6_addr * for IPv6.
+ * @param str string that will contain binary notation of 'addr'. Expected
+ *            to be at least 33 bytes long for IPv4 and 129 bytes long for IPv6.
  */
 static void
-iterate_edge (struct GNUNET_REGEX_State *s, GNUNET_REGEX_KeyIterator iterator,
-              void *iterator_cls)
+iptobinstr (const int af, const void *addr, char *str)
 {
-  struct GNUNET_REGEX_Transition *t;
-  struct GNUNET_REGEX_Edge edges[s->transition_count];
-  unsigned int num_edges;
+  int i;
 
-  if (GNUNET_YES != s->marked)
+  switch (af)
   {
-    s->marked = GNUNET_YES;
-
-    num_edges = state_get_edges (s, edges);
+  case AF_INET:
+  {
+    uint32_t b = htonl (((struct in_addr *) addr)->s_addr);
 
-    if ((NULL != s->proof && 0 < strlen (s->proof)) || s->accepting)
-      iterator (iterator_cls, &s->hash, s->proof, s->accepting, num_edges,
-                edges);
+    str[32] = '\0';
+    str += 31;
+    for (i = 31; i >= 0; i--)
+    {
+      *str = (b & 1) + '0';
+      str--;
+      b >>= 1;
+    }
+    break;
+  }
+  case AF_INET6:
+  {
+    struct in6_addr b = *(const struct in6_addr *) addr;
 
-    for (t = s->transitions_head; NULL != t; t = t->next)
-      iterate_edge (t->to_state, iterator, iterator_cls);
+    str[128] = '\0';
+    str += 127;
+    for (i = 127; i >= 0; i--)
+    {
+      *str = (b.s6_addr[i / 8] & 1) + '0';
+      str--;
+      b.s6_addr[i / 8] >>= 1;
+    }
+    break;
+  }
   }
 }
 
 
 /**
- * Iterate over all edges starting from start state of automaton 'a'. Calling
- * iterator for each edge.
+ * Get the ipv4 network prefix from the given 'netmask'.
  *
- * @param a automaton.
- * @param iterator iterator called for each edge.
- * @param iterator_cls closure.
+ * @param netmask netmask for which to get the prefix len.
+ *
+ * @return length of ipv4 prefix for 'netmask'.
+ */
+static unsigned int
+ipv4netmasktoprefixlen (const char *netmask)
+{
+  struct in_addr a;
+  unsigned int len;
+  uint32_t t;
+
+  if (1 != inet_pton (AF_INET, netmask, &a))
+    return 0;
+  len = 32;
+  for (t = htonl (~a.s_addr); 0 != t; t >>= 1)
+    len--;
+  return len;
+}
+
+
+/**
+ * Create a regex in 'rxstr' from the given 'ip' and 'netmask'.
+ *
+ * @param ip IPv4 representation.
+ * @param netmask netmask for the ip.
+ * @param rxstr generated regex, must be at least GNUNET_REGEX_IPV4_REGEXLEN
+ *              bytes long.
  */
 void
-GNUNET_REGEX_iterate_all_edges (struct GNUNET_REGEX_Automaton *a,
-                                GNUNET_REGEX_KeyIterator iterator,
-                                void *iterator_cls)
+GNUNET_REGEX_ipv4toregex (const struct in_addr *ip, const char *netmask,
+                          char *rxstr)
 {
-  struct GNUNET_REGEX_State *s;
+  unsigned int pfxlen;
 
-  for (s = a->states_head; NULL != s; s = s->next)
-    s->marked = GNUNET_NO;
+  pfxlen = ipv4netmasktoprefixlen (netmask);
+  iptobinstr (AF_INET, ip, rxstr);
+  rxstr[pfxlen] = '\0';
+  if (pfxlen < 32)
+    strcat (rxstr, "(0|1)+");
+}
+
+
+/**
+ * Create a regex in 'rxstr' from the given 'ipv6' and 'prefixlen'.
+ *
+ * @param ipv6 IPv6 representation.
+ * @param prefixlen length of the ipv6 prefix.
+ * @param rxstr generated regex, must be at least GNUNET_REGEX_IPV6_REGEXLEN
+ *              bytes long.
+ */
+void
+GNUNET_REGEX_ipv6toregex (const struct in6_addr *ipv6, unsigned int prefixlen,
+                          char *rxstr)
+{
+  iptobinstr (AF_INET6, ipv6, rxstr);
+  rxstr[prefixlen] = '\0';
+  if (prefixlen < 128)
+    strcat (rxstr, "(0|1)+");
+}
+
+
+struct RegexCombineCtx {
+  struct RegexCombineCtx *next;
+  struct RegexCombineCtx *prev;
+
+  struct RegexCombineCtx *head;
+  struct RegexCombineCtx *tail;
+
+  char *s;
+};
+
+
+static char *
+regex_combine (struct RegexCombineCtx *ctx)
+{
+  struct RegexCombineCtx *p;
+  size_t len;
+  char *regex;
+  char *tmp;
+  char *s;
+
+  if (NULL != ctx->s)
+    GNUNET_asprintf (&regex, "%s(", ctx->s);
+  else
+    regex = GNUNET_strdup ("(");
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "prefix: %s\n", regex);
+
+  for (p = ctx->head; NULL != p; p = p->next)
+  {
+    s = regex_combine (p);
+    GNUNET_asprintf (&tmp, "%s%s|", regex, s);
+    GNUNET_free_non_null (s);
+    GNUNET_free_non_null (regex);
+    regex = tmp;
+  }
+  len = strlen (regex);
+  if (1 == len)
+    return GNUNET_strdup ("");
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pre-partial: %s\n", regex);
+  if ('|' == regex[len - 1])
+    regex[len - 1] = ')';
+  if ('(' == regex[len - 1])
+    regex[len - 1] = '\0';
 
-  iterate_initial_edges (a, INITIAL_BITS, iterator, iterator_cls);
-  iterate_edge (a->start, iterator, iterator_cls);
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "partial: %s\n", regex);
+  return regex;
 }
+
+static void
+regex_add (struct RegexCombineCtx *ctx, const char *regex)
+{
+  struct RegexCombineCtx *p;
+  const char *rest;
+
+  rest = &regex[1];
+  for (p = ctx->head; NULL != p; p = p->next)
+  {
+    if (p->s[0] == regex[0])
+    {
+      if (1 == strlen(p->s))
+      {
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "common char %s\n", p->s);
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding %s\n", rest);
+        regex_add (p, rest);
+      }
+      else
+      {
+        struct RegexCombineCtx *new;
+        new = GNUNET_malloc (sizeof (struct RegexCombineCtx));
+        new->s = GNUNET_strdup (&p->s[1]);
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " p has now %s\n", p->s);
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " p will have %.1s\n", p->s);
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " regex is %s\n", regex);
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " new has now %s\n", new->s);
+        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " rest is now %s\n", rest);
+        p->s[1] = '\0'; /* dont realloc */
+        GNUNET_CONTAINER_DLL_insert (p->head, p->tail, new);
+        regex_add (p, rest);
+      }
+      return;
+    }
+  }
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " no  match\n");
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " new state %s\n", regex);
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " under %s\n", ctx->s);
+  p = GNUNET_malloc (sizeof (struct RegexCombineCtx));
+  p->s = GNUNET_strdup (regex);
+  GNUNET_CONTAINER_DLL_insert (ctx->head, ctx->tail, p);
+}
+/*
+static void
+debug (struct RegexCombineCtx *ctx, int lvl)
+{
+  struct RegexCombineCtx *p;
+  unsigned int i;
+
+  for (i = 0; i < lvl; i++) fprintf (stderr, " ");
+  fprintf (stderr, "%s\n", ctx->s);
+
+  for (p = ctx->head; NULL != p; p = p->next)
+  {
+    debug (p, lvl + 2);
+  }
+}*/
+
+char *
+GNUNET_REGEX_combine (char * const regexes[])
+{
+  unsigned int i;
+  char *combined;
+  const char *current;
+  struct RegexCombineCtx ctx;
+
+  memset (&ctx, 0, sizeof (struct RegexCombineCtx));
+  for (i = 0; regexes[i]; i++)
+  {
+    current = regexes[i];
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex %u: %s\n", i, current);
+    regex_add (&ctx, current);
+  }
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\nCombining...\n");
+
+  combined = regex_combine (&ctx);
+
+  return combined;
+}
+
+/* end of regex.c */