/*
 *  Copyright (C) 1999 Bruno Haible
 *  This file is placed in the public domain.
 */

#include <string.h>

extern char * getenv ();


int
is_locale_utf8 ()
{
  char * locale;

  /* Determine the current locale the same way as setlocale() does, 
     according to POSIX. */
  locale = getenv ("LC_ALL");
  if (! locale || ! * locale) {
    locale = getenv ("LC_CTYPE");
    if (! locale || ! * locale) {
      locale = getenv ("LANG");
    }
  }
  if (locale && * locale) {
    /* The most general syntax of a locale (not all optional parts recognized
       by all systems) is
       language[_territory][.codeset][@modifier][+special][,[sponsor][_revision]]
       To retrieve the codeset, search the first dot. Stop searching when
       a '@' or '+' or ',' is encountered. */
    char * cp = locale;
    for (; * cp != '\0' && * cp != '@' && * cp != '+' && * cp != ','; cp ++) {
      if (* cp == '.') {
	char * encoding = ++ cp;
	for (; * cp != '\0' && * cp != '@' && * cp != '+' && * cp != ','; cp ++)
		;
	/* The encoding is now contained in the part from encoding to cp. */
	/* Check it for "UTF-8", which is the only official IANA name of
	   UTF-8. Also check for the lowercase-no-dashes version, which is
	   what some SystemV systems use. */
	if ((cp - encoding == 5 && ! strncmp (encoding, "UTF-8", 5))
	    || (cp - encoding == 4 && ! strncmp (encoding, "utf8", 4)))
		return 1; /* it's UTF-8 */
	break; /* not UTF-8 */
      }
    }
  }
  return 0; /* not UTF-8 */
}
