/* $Cambridge: hermes/src/prayer/session/utf8_calc.c,v 1.3 2008/09/16 09:59:58 dpc22 Exp $ */

#include "prayer_session.h"

/* utf8_calc_width() ******************************************************
 *
 * Calculate width of UTF-8 byte sequence. Should be able to cope with
 * double width and zero width characters in Far Eastern character sets.
 * Uses c-client routines (utf8_get() and ucs4_width()) for heavy lifting.
 *
 *      s: Input string
 *  bytes: Number of bytes to consider
 *
 * Returns: Number of characters
 *
 *************************************************************************/

unsigned long utf8_calc_width(char *t, unsigned long bytes)
{
    unsigned char c, *s = (unsigned char *)t;
    unsigned long width = 0;
    unsigned long ucs;
    long w;

    while ((bytes > 0) && ((c = *s) != '\0')) {
        if (c < 0x80) {
            width++;
            s++;
            bytes--;
            continue;
        }
        ucs = utf8_get(&s, &bytes);   /* Convert to full 4 byte unicode */
        if (ucs & U8G_ERROR) {
            /* If we can't decode, count as separate characters */
            width++;
            s++;
            bytes--;
            continue;
        }

        if ((w=ucs4_width(ucs)) >= 0)
            width += w;
    }
    return(width);
}

