#include <glib/gunicode.h>
#include <pango/pango-context.h>
#include <pango/pango-layout.h>
#include <pango/pangocairo.h>
#include <stdio.h>

int main() {
    char tst1[] = "consider the Thai phrase “ทำการบ้าน”, which has three components";
    char tst2[] = "บ้าน”, which has three components";
    //char tst3[] = {0xe0, 0xb8, 0x9a, 0xe0, 0xb9, 0x89, 0xe0, 0xb8, 0xb2, 0xe0, 0xb8, 
    //              0x99, 0xe2, 0x80, 0x9d, 0x20, 0x77, 0x68, 0x69, 0x63, 0x68};
    struct {char *str; unsigned len;} tsts[] = {
        {tst1, sizeof(tst1) - 1},
        {tst2, sizeof(tst2) - 1}
        //, tst3, sizeof(tst3)
    };
    PangoContext *ctx;
    PangoLayout *layout;
    PangoLogAttr *log_attrs = NULL;
    gint n_attrs = -1;
    gint i, t;
    gchar *p, *q;
    gchar const *err;

    for (t = 0; t < G_N_ELEMENTS(tsts); ++t) {
        char *const tst = tsts[t].str;
        unsigned const tst_len = tsts[t].len;

        if (!g_utf8_validate(tst, tst_len, &err)) {
            fprintf(stderr, "bug: tst string not valid utf8\n");
            return 1;
        }

        printf("\n%.*s\n", tst_len, tst);

        {
            PangoFontMap *pfm = pango_cairo_font_map_get_default();
            ctx = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pfm));
            g_object_unref(pfm);
        }
        layout = pango_layout_new(ctx);
        pango_layout_set_text(layout, tst, tst_len);
        pango_layout_get_log_attrs(layout, &log_attrs, &n_attrs);
        p = tst;
        for (i = 0; i < n_attrs; ++i) {
            if (log_attrs[i].is_word_end) {
                putchar(')');
            }
            if (log_attrs[i].is_word_start) {
                putchar('(');
            }
            q = g_utf8_next_char(p);
            printf("%.*s", q - p, p);
            p = q;
        }
        putchar('\n');
    }

    return 0;
}
