MODULE HostLang;

	(* THIS IS TEXT COPY OF Lang.odc *)
	(* DO NOT EDIT *)

	(*
		A. V. Shiryaev, 2012.10

		LANG environment variable support
		Dialog.LanguageHook implementation
	*)

	IMPORT Dialog, Libc := LinLibc, Codecs := EncCodecs;

	CONST
		defLang = "";
		defCountry = "";
		defEnc = "ASCII";

	TYPE
		LanguageHook = POINTER TO RECORD (Dialog.LanguageHook) END;

	VAR
		lang-: Dialog.Language;
		enc-: Codecs.Encoding;

	PROCEDURE ParseLang (OUT lang, country, enc: ARRAY OF CHAR);
		VAR env: Libc.PtrSTR;
			i, j: INTEGER;

		PROCEDURE Default;
		BEGIN
			lang := defLang;
			country := defCountry;
			enc := defEnc
		END Default;

		PROCEDURE IsValidEncChar (x: SHORTCHAR): BOOLEAN;
		BEGIN
			RETURN ((x >= 'A') & (x <= 'Z')) OR ((x >= '0') & (x <= '9')) OR (x = '-') OR (x = '_')
				OR ((x >= 'a') & (x <= 'z'))
		END IsValidEncChar;

	BEGIN
		env := Libc.getenv("LANG");
		IF env # NIL THEN
			IF env$ = "C" THEN
				lang := ""; country := ""; enc := "ASCII"
			ELSE
				i := 0;
				WHILE (i < 2) & (env[i] >= 'a') & (env[i] <= 'z') & (i < LEN(lang) - 1) DO
					lang[i] := env[i];
					INC(i)
				END;
				IF (i = 2) & (env[i] = '_') & (i < LEN(lang)) THEN
					lang[i] := 0X;
					INC(i);
					j := 0;
					WHILE (i < 5) & (env[i] >= 'A') & (env[i] <= 'Z') & (j < LEN(country) - 1) DO
						country[j] := env[i];
						INC(j); INC(i)
					END;
					IF (i = 5) & (env[i] = '.') & (j < LEN(country)) THEN
						country[j] := 0X;
						INC(i);
						j := 0;
						WHILE IsValidEncChar(env[i]) & (j < LEN(enc)) DO
							enc[j] := env[i];
							INC(j); INC(i)
						END;
						IF j < LEN(enc) - 1 THEN
							enc[j] := 0X
						ELSE Default
						END
					ELSE Default
					END
				ELSE Default
				END
			END
		ELSE Default
		END
	END ParseLang;

	PROCEDURE (hook: LanguageHook) SetLanguage (
		lang: Dialog.Language; persistent: BOOLEAN; OUT ok: BOOLEAN
	);
	BEGIN
		ok := (lang = "") OR (LEN(lang$) = 2);
(*
		IF ok & persistent THEN HostRegistry.WriteString("language", lang) END
*)
	END SetLanguage;

	PROCEDURE (hook: LanguageHook) GetPersistentLanguage (OUT l: Dialog.Language);
		VAR res: INTEGER; s: ARRAY 32 OF CHAR;
	BEGIN
(*
		HostRegistry.ReadString("language", s, res);
		IF res = 0 THEN
			ASSERT((s = "") OR (LEN(s$) = 2), 100);
			lang := s$
		ELSE lang := ""
		END
*)
		l := lang
	END GetPersistentLanguage;

	PROCEDURE Init;
		VAR
			languageHook: LanguageHook;
			country: ARRAY 3 OF CHAR;
	BEGIN
		ParseLang(lang, country, enc);
		NEW(languageHook); Dialog.SetLanguageHook(languageHook); Dialog.ResetLanguage
	END Init;

BEGIN
	Init
END HostLang.
