/**
   These functions try to determine from environment variables 
   the user's configuraion for terminal encoding and default 
   text encoding.
   This code is mainly intended for CJK encoding detection and 
   works slightly different from the function that detects if 
   the terminal is configured to be in UTF-8 mode.
 */

#include <string.h>

extern char * getenv ();


static
char *
locale_encoding (var1, var2, var3)
  char * var1;
  char * var2;
  char * var3;
{
  char * encoding;
  char * region = (char *) 0;
  char * locale = getenv (var1);
  if (! locale || ! strchr (locale, '.')) {
    if (locale) {
	region = (char *) strrchr (locale, '_');
    }
    locale = getenv (var2);
    if (! locale || ! strchr (locale, '.')) {
	if (locale && ! region) {
		region = (char *) strrchr (locale, '_');
	}
	locale = getenv (var3);
	if (locale && ! region) {
		region = (char *) strrchr (locale, '_');
	}
    }
  }
  if (! locale) {
	if (region) {
		return region;
	} else {
		return "";
	}
  }
  encoding = (char *) strchr (locale, '.');
  if (! encoding) {
	if (region) {
		return region;
	} else {
		return "";
	}
  }
  encoding ++;
  return encoding;
}

char *
locale_terminal_encoding ()
{
  return locale_encoding ("LC_ALL", "LC_CTYPE", "LANG");
}

char *
locale_text_encoding ()
{
  return locale_encoding ("LANG", "LC_ALL", "LC_CTYPE");
}

