#include <gtk/gtk.h>
#include <stdlib.h>

enum { PREVIOUS, NEXT };

static gint to_highlight = 0;
GtkWidget *label;

static void
update_highlight (void)
{
  PangoLayout *layout;
  PangoLayoutIter *iter;
  PangoAttrList *attrs;
  PangoAttribute *attr;
  int i;
  int start, end;

  /* Find the character bounds for cluster to_highlight */

  layout = gtk_label_get_layout (GTK_LABEL (label));
  iter = pango_layout_get_iter (layout);

  for (i = 0; i < to_highlight; i++)
    if (!pango_layout_iter_next_char (iter))
      break;

  start = pango_layout_iter_get_index (iter);
  pango_layout_iter_next_char (iter);
  end = pango_layout_iter_get_index (iter);
  pango_layout_iter_free (iter);

  g_print ("%d %d\n", start, end);

  attrs = pango_attr_list_new ();

  if (start != end)
    {
      attr = pango_attr_foreground_new (0x8000, 0, 0);
      attr->start_index = start;
      attr->end_index = end;
      
      pango_attr_list_change (attrs, attr);
      
      attr = pango_attr_background_new (0xffff, 0xffff, 0xffff);
      attr->start_index = start;
      attr->end_index = end;
      
      pango_attr_list_change (attrs, attr);
    }

  gtk_label_set_attributes (GTK_LABEL (label), attrs);
  pango_attr_list_unref (attrs);
}

static void
response (GtkDialog *dialog,
	  int        response_id)
{
  if (response_id == PREVIOUS)
    {
      if (to_highlight > 0)
	to_highlight--;
      update_highlight ();
    }
  else if (response_id == NEXT)
    {
      to_highlight++;
      update_highlight ();
    }
  else 
    gtk_main_quit ();
}

int main (int argc, char **argv)
{
  GtkWidget *dialog;
  char *text;
  GError *err = NULL;

  gtk_init (&argc, &argv);

  dialog = gtk_dialog_new_with_buttons ("Test Clusters", NULL,0,
					"Previous", PREVIOUS,
					"Next", NEXT,
					NULL);

  g_signal_connect (dialog, "response", G_CALLBACK (response), NULL);

  if (argc != 2)
    {
      g_printerr ("Usage testclusters FILE\n");
      exit (1);
    }

  if (!g_file_get_contents (argv[1], &text, NULL, &err))
    {
      g_printerr ("Cannot open %s: %s\n", argv[1], err->message);
      exit (1);
    }

  label = gtk_label_new (text);
  g_free (text);

  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), label, FALSE, FALSE, 0);

  gtk_widget_show_all (dialog);
  update_highlight ();

  gtk_main ();

  return 0;
}
