#include <string.h>
#include <stdio.h>
#include <glib.h>

gchar *
_gtk_toolbar_elide_underscores (const gchar *original)
{
  gchar *q, *result;
  const gchar *p;
  gboolean last_underscore, last_parenthesis;
  
  if (!original)
    return NULL;

  q = result = g_malloc (strlen (original) + 1);
  last_underscore = FALSE;
  last_parenthesis = FALSE;
  
  for (p = original; *p; p++)
    {
      if (!last_underscore && *p == '_')
	{
	  last_underscore = TRUE;
	  if (last_parenthesis && *(p+2) && (*(p+2) == ')'))
	    {
	      *--q = '\0';
	      p += 2;
	    }
	}
      else
	{
	  last_parenthesis = (*p == '(') ? TRUE : FALSE;
	  last_underscore = FALSE;
	  *q++ = *p;
	}
    }
  
  *q = '\0';
  
  return result;
}

void main()
{
  int i;
  /*  char orig[1024]; */
  char *strings[] =
    {
      "__underscore",
      "_blahblah",
      "foo_bar",
      "dou_ble under__score",
      "something(_C)",
      "something again(_1)",
      "ellip_sis...",
      "ellipsis2(_X)...",
      "bla[_b]",
      "more(_x)bla",
      "morebla2(_x):",
      "(__)joe",
      "(__ )joe",
      "incomplete ((__",
      "incomplete2 (_ ",
      "incomplete3 ( _F)",
      "incomplete4 ( _)",
      "f__u(_x)__n"
    };

  char *results[] =
    {
      "_underscore",
      "blahblah",
      "foobar",
      "double under_score",
      "something",
      "something again",
      "ellipsis...",
      "ellipsis2...",
      "bla[b]",	/* shouldn't remove anything other than parenthesis */
      "morebla",
      "morebla2:",
      "joe",
      "(_ )joe",
      "incomplete ((_",
      "incomplete2 ( ",
      "incomplete3 ( F)",
      "incomplete4 ( )",
      "f_u_n"
    };

  for (i=0; i<(sizeof(strings) / sizeof(strings[0])); i++)
    {
      g_print ("expected='%s', result='%s'\n", results[i],
		      _gtk_toolbar_elide_underscores(strings[i]));
    }

#if 0
  while (1)
    {
      scanf ("%s", orig);
      orig[1023] = '\0';
      g_print ("%s\n", _gtk_toolbar_elide_underscores((const gchar*)orig));
    }
#endif

}
