diff -Nura icu/source/common/common.vcproj icu_new/source/common/common.vcproj
--- icu/source/common/common.vcproj	2008-07-01 09:41:12.000000000 +0800
+++ icu_new/source/common/common.vcproj	2018-05-25 19:27:51.633413911 +0800
@@ -1606,7 +1606,7 @@
 				</FileConfiguration>
 			</File>
 			<File
-				RelativePath=".\uloc.c"
+				RelativePath=".\uloc.cpp"
 				>
 			</File>
 			<File
diff -Nura icu/source/common/ucnv_u8.c icu_new/source/common/ucnv_u8.c
--- icu/source/common/ucnv_u8.c	2008-07-01 09:41:12.000000000 +0800
+++ icu_new/source/common/ucnv_u8.c	2018-05-24 10:18:04.594913298 +0800
@@ -23,6 +23,7 @@
 #if !UCONFIG_NO_CONVERSION
 
 #include "unicode/ucnv.h"
+#include "uassert.h"
 #include "ucnv_bld.h"
 #include "ucnv_cnv.h"
 #include "cmemory.h"
@@ -808,22 +809,34 @@
          * Let the standard converter handle edge cases.
          */
         int32_t i;
-
+        const uint8_t *limit=sourceLimit;
         if(count>targetCapacity) {
+            limit-=(count-targetCapacity);
             count=targetCapacity;
         }
 
-        i=0;
-        while(i<3 && i<(count-toULimit)) {
-            b=source[count-oldToULength-i-1];
-            if(U8_IS_TRAIL(b)) {
-                ++i;
-            } else {
-                if(i<utf8_countTrailBytes[b]) {
-                    /* stop converting before the lead byte if there are not enough trail bytes for it */
-                    count-=i+1;
+        // The conversion loop checks count>0 only once per 1/2/3-byte character.
+        // If the buffer ends with a truncated 2- or 3-byte sequence,
+        // then we reduce the count to stop before that,
+        // and collect the remaining bytes after the conversion loop.
+        {
+            // Do not go back into the bytes that will be read for finishing a partial
+            // sequence from the previous buffer.
+            int32_t length=count-toULimit;
+            if(length>0) {
+                uint8_t b1=*(limit-1);
+                if(U8_IS_SINGLE(b1)) {
+                    // common ASCII character
+                } else if(U8_IS_TRAIL(b1) && length>=2) {
+                    uint8_t b2=*(limit-2);
+                    if(0xe0<=b2 && b2<0xf0 && U8_IS_VALID_LEAD3_AND_T1(b2, b1)) {
+                        // truncated 3-byte sequence
+                        count-=2;
+                }
+                } else if(0xc2<=b1 && b1<0xf0) {
+                    // truncated 2- or 3-byte sequence
+                    --count;
                 }
-                break;
             }
         }
     }
@@ -938,7 +951,7 @@
             }
 
             /* copy the legal byte sequence to the target */
-            {
+            if(count>=toULength) {
                 int8_t i;
 
                 for(i=0; i<oldToULength; ++i) {
@@ -949,9 +962,18 @@
                     *target++=*source++;
                 }
                 count-=toULength;
+            } else {
+                // A supplementary character that does not fit into the target.
+                // Let the standard converter handle this.
+                source-=(toULength-oldToULength);
+                pToUArgs->source=(char *)source;
+                pFromUArgs->target=(char *)target;
+                *pErrorCode=U_USING_DEFAULT_WARNING;
+                return;
             }
         }
     }
+    U_ASSERT(count>=0);
 
     if(U_SUCCESS(*pErrorCode) && source<sourceLimit) {
         if(target==(const uint8_t *)pFromUArgs->targetLimit) {
diff -Nura icu/source/common/uloc.c icu_new/source/common/uloc.c
--- icu/source/common/uloc.c	2018-05-23 15:11:33.624557835 +0800
+++ icu_new/source/common/uloc.c	1970-01-01 08:00:00.000000000 +0800
@@ -1,4369 +0,0 @@
-/*
-**********************************************************************
-*   Copyright (C) 1997-2008, International Business Machines
-*   Corporation and others.  All Rights Reserved.
-**********************************************************************
-*
-* File ULOC.CPP
-*
-* Modification History:
-*
-*   Date        Name        Description
-*   04/01/97    aliu        Creation.
-*   08/21/98    stephen     JDK 1.2 sync
-*   12/08/98    rtg         New Locale implementation and C API
-*   03/15/99    damiba      overhaul.
-*   04/06/99    stephen     changed setDefault() to realloc and copy
-*   06/14/99    stephen     Changed calls to ures_open for new params
-*   07/21/99    stephen     Modified setDefault() to propagate to C++
-*   05/14/04    alan        7 years later: refactored, cleaned up, fixed bugs,
-*                           brought canonicalization code into line with spec
-*****************************************************************************/
-
-/*
-   POSIX's locale format, from putil.c: [no spaces]
-
-     ll [ _CC ] [ . MM ] [ @ VV]
-
-     l = lang, C = ctry, M = charmap, V = variant
-*/
-
-#include "unicode/utypes.h"
-#include "unicode/ustring.h"
-#include "unicode/uloc.h"
-#include "unicode/ures.h"
-
-#include "putilimp.h"
-#include "ustr_imp.h"
-#include "ulocimp.h"
-#include "uresimp.h"
-#include "umutex.h"
-#include "cstring.h"
-#include "cmemory.h"
-#include "ucln_cmn.h"
-#include "locmap.h"
-#include "uarrsort.h"
-#include "uenumimp.h"
-#include "uassert.h"
-
-#include <stdio.h> /* for sprintf */
-
-/* ### Declarations **************************************************/
-
-/* Locale stuff from locid.cpp */
-U_CFUNC void locale_set_default(const char *id);
-U_CFUNC const char *locale_get_default(void);
-U_CFUNC int32_t
-locale_getKeywords(const char *localeID,
-            char prev,
-            char *keywords, int32_t keywordCapacity,
-            char *values, int32_t valuesCapacity, int32_t *valLen,
-            UBool valuesToo,
-            UErrorCode *status);
-
-/* ### Constants **************************************************/
-
-/* These strings describe the resources we attempt to load from
- the locale ResourceBundle data file.*/
-static const char _kLanguages[]       = "Languages";
-static const char _kScripts[]         = "Scripts";
-static const char _kCountries[]       = "Countries";
-static const char _kVariants[]        = "Variants";
-static const char _kKeys[]            = "Keys";
-static const char _kTypes[]           = "Types";
-static const char _kIndexLocaleName[] = "res_index";
-static const char _kRootName[]        = "root";
-static const char _kIndexTag[]        = "InstalledLocales";
-static const char _kCurrency[]        = "currency";
-static const char _kCurrencies[]      = "Currencies";
-static char** _installedLocales = NULL;
-static int32_t _installedLocalesCount = 0;
-
-/* ### Data tables **************************************************/
-
-/**
- * Table of language codes, both 2- and 3-letter, with preference
- * given to 2-letter codes where possible.  Includes 3-letter codes
- * that lack a 2-letter equivalent.
- *
- * This list must be in sorted order.  This list is returned directly
- * to the user by some API.
- *
- * This list must be kept in sync with LANGUAGES_3, with corresponding
- * entries matched.
- *
- * This table should be terminated with a NULL entry, followed by a
- * second list, and another NULL entry.  The first list is visible to
- * user code when this array is returned by API.  The second list
- * contains codes we support, but do not expose through user API.
- *
- * Notes
- *
- * Tables updated per http://lcweb.loc.gov/standards/iso639-2/ to
- * include the revisions up to 2001/7/27 *CWB*
- *
- * The 3 character codes are the terminology codes like RFC 3066.  This
- * is compatible with prior ICU codes
- *
- * "in" "iw" "ji" "jw" & "sh" have been withdrawn but are still in the
- * table but now at the end of the table because 3 character codes are
- * duplicates.  This avoids bad searches going from 3 to 2 character
- * codes.
- *
- * The range qaa-qtz is reserved for local use
- */
-static const char * const LANGUAGES[] = {
-    "aa",  "ab",  "ace", "ach", "ada", "ady", "ae",  "af",  "afa",
-    "afh", "ain", "ak",  "akk", "ale", "alg", "alt", "am",  "an",  
-    "ang", "anp", "apa",
-    "ar",  "arc", "arn", "arp", "art", "arw", "as",  "ast",
-    "ath", "aus", "av",  "awa", "ay",  "az",  "ba",  "bad",
-    "bai", "bal", "ban", "bas", "bat", "be",  "bej",
-    "bem", "ber", "bg",  "bh",  "bho", "bi",  "bik", "bin",
-    "bla", "bm",  "bn",  "bnt", "bo",  "br",  "bra", "bs",
-    "btk", "bua", "bug", "byn", "ca",  "cad", "cai", "car", "cau",
-    "cch", "ce",  "ceb", "cel", "ch",  "chb", "chg", "chk", "chm",
-    "chn", "cho", "chp", "chr", "chy", "cmc", "co",  "cop",
-    "cpe", "cpf", "cpp", "cr",  "crh", "crp", "cs",  "csb", "cu",  "cus",
-    "cv",  "cy",  "da",  "dak", "dar", "day", "de",  "del", "den",
-    "dgr", "din", "doi", "dra", "dsb", "dua", "dum", "dv",  "dyu",
-    "dz",  "ee",  "efi", "egy", "eka", "el",  "elx", "en",
-    "enm", "eo",  "es",  "et",  "eu",  "ewo", "fa",
-    "fan", "fat", "ff",  "fi",  "fil", "fiu", "fj",  "fo",  "fon",
-    "fr",  "frm", "fro", "frr", "frs", "fur", "fy",  
-    "ga",  "gaa", "gay", "gba", "gd",  "gem", "gez", "gil", 
-    "gl",  "gmh", "gn",  "goh", "gon", "gor", "got", "grb", 
-    "grc", "gsw", "gu",  "gv", "gwi", 
-    "ha",  "hai", "haw", "he",  "hi",  "hil", "him",
-    "hit", "hmn", "ho",  "hr",  "hsb", "ht",  "hu",  "hup", "hy",  "hz",
-    "ia",  "iba", "id",  "ie",  "ig",  "ii",  "ijo", "ik",
-    "ilo", "inc", "ine", "inh", "io",  "ira", "iro", "is",  "it",
-    "iu",  "ja",  "jbo", "jpr", "jrb", "jv",  "ka",  "kaa", "kab",
-    "kac", "kaj", "kam", "kar", "kaw", "kbd", "kcg", "kfo", "kg",  "kha", "khi",
-    "kho", "ki",  "kj",  "kk",  "kl",  "km",  "kmb", "kn",
-    "ko",  "kok", "kos", "kpe", "kr",  "krc", "krl", "kro", "kru", "ks",
-    "ku",  "kum", "kut", "kv",  "kw",  "ky",  "la",  "lad",
-    "lah", "lam", "lb",  "lez", "lg",  "li",  "ln",  "lo",  "lol",
-    "loz", "lt",  "lu",  "lua", "lui", "lun", "luo", "lus",
-    "lv",  "mad", "mag", "mai", "mak", "man", "map", "mas",
-    "mdf", "mdr", "men", "mg",  "mga", "mh",  "mi",  "mic", "min",
-    "mis", "mk",  "mkh", "ml",  "mn",  "mnc", "mni", "mno",
-    "mo",  "moh", "mos", "mr",  "ms",  "mt",  "mul", "mun",
-    "mus", "mwl", "mwr", "my",  "myn", "myv", "na",  "nah", "nai", "nap",
-    "nb",  "nd",  "nds", "ne",  "new", "ng",  "nia", "nic",
-    "niu", "nl",  "nn",  "no",  "nog", "non", "nqo", "nr",  "nso", "nub",
-    "nv",  "nwc", "ny",  "nym", "nyn", "nyo", "nzi", "oc",  "oj",
-    "om",  "or",  "os",  "osa", "ota", "oto", "pa",  "paa",
-    "pag", "pal", "pam", "pap", "pau", "peo", "phi", "phn",
-    "pi",  "pl",  "pon", "pra", "pro", "ps",  "pt",  "qu",
-    "raj", "rap", "rar", "rm",  "rn",  "ro",  "roa", "rom",
-    "ru",  "rup", "rw",  "sa",  "sad", "sah", "sai", "sal", "sam",
-    "sas", "sat", "sc",  "scn", "sco", "sd",  "se",  "sel", "sem",
-    "sg",  "sga", "sgn", "shn", "si",  "sid", "sio", "sit",
-    "sk",  "sl",  "sla", "sm",  "sma", "smi", "smj", "smn",
-    "sms", "sn",  "snk", "so",  "sog", "son", "sq",  "sr",
-    "srn", "srr", "ss",  "ssa", "st",  "su",  "suk", "sus", "sux",
-    "sv",  "sw",  "syc", "syr", "ta",  "tai", "te",  "tem", "ter",
-    "tet", "tg",  "th",  "ti",  "tig", "tiv", "tk",  "tkl",
-    "tl",  "tlh", "tli", "tmh", "tn",  "to",  "tog", "tpi", "tr",
-    "ts",  "tsi", "tt",  "tum", "tup", "tut", "tvl", "tw",
-    "ty",  "tyv", "udm", "ug",  "uga", "uk",  "umb", "und", "ur",
-    "uz",  "vai", "ve",  "vi",  "vo",  "vot", "wa",  "wak",
-    "wal", "war", "was", "wen", "wo",  "xal", "xh",  "yao", "yap",
-    "yi",  "yo",  "ypk", "za",  "zap", "zbl", "zen", "zh",  "znd",
-    "zu",  "zun", "zxx", "zza",
-NULL,
-    "in",  "iw",  "ji",  "jw",  "sh",    /* obsolete language codes */
-NULL
-};
-static const char* const DEPRECATED_LANGUAGES[]={
-    "in", "iw", "ji", "jw", NULL, NULL
-};
-static const char* const REPLACEMENT_LANGUAGES[]={
-    "id", "he", "yi", "jv", NULL, NULL
-};
-
-/**
- * Table of 3-letter language codes.
- *
- * This is a lookup table used to convert 3-letter language codes to
- * their 2-letter equivalent, where possible.  It must be kept in sync
- * with LANGUAGES.  For all valid i, LANGUAGES[i] must refer to the
- * same language as LANGUAGES_3[i].  The commented-out lines are
- * copied from LANGUAGES to make eyeballing this baby easier.
- *
- * Where a 3-letter language code has no 2-letter equivalent, the
- * 3-letter code occupies both LANGUAGES[i] and LANGUAGES_3[i].
- *
- * This table should be terminated with a NULL entry, followed by a
- * second list, and another NULL entry.  The two lists correspond to
- * the two lists in LANGUAGES.
- */
-static const char * const LANGUAGES_3[] = {
-/*  "aa",  "ab",  "ace", "ach", "ada", "ady", "ae",  "af",  "afa",    */
-    "aar", "abk", "ace", "ach", "ada", "ady", "ave", "afr", "afa",
-/*  "afh", "ain", "ak",  "akk", "ale", "alg", "alt", "am",  "an",  "ang", "anp", "apa",    */
-    "afh", "ain", "aka", "akk", "ale", "alg", "alt", "amh", "arg", "ang", "anp", "apa",
-/*  "ar",  "arc", "arn", "arp", "art", "arw", "as",  "ast",    */
-    "ara", "arc", "arn", "arp", "art", "arw", "asm", "ast",
-/*  "ath", "aus", "av",  "awa", "ay",  "az",  "ba",  "bad",    */
-    "ath", "aus", "ava", "awa", "aym", "aze", "bak", "bad",
-/*  "bai", "bal", "ban", "bas", "bat", "be",  "bej",    */
-    "bai", "bal", "ban", "bas", "bat", "bel", "bej",
-/*  "bem", "ber", "bg",  "bh",  "bho", "bi",  "bik", "bin",    */
-    "bem", "ber", "bul", "bih", "bho", "bis", "bik", "bin",
-/*  "bla", "bm",  "bn",  "bnt", "bo",  "br",  "bra", "bs",     */
-    "bla", "bam", "ben", "bnt", "bod", "bre", "bra", "bos",
-/*  "btk", "bua", "bug", "byn", "ca",  "cad", "cai", "car", "cau",    */
-    "btk", "bua", "bug", "byn", "cat", "cad", "cai", "car", "cau",
-/*  "cch", "ce",  "ceb", "cel", "ch",  "chb", "chg", "chk", "chm",    */
-    "cch", "che", "ceb", "cel", "cha", "chb", "chg", "chk", "chm",
-/*  "chn", "cho", "chp", "chr", "chy", "cmc", "co",  "cop",    */
-    "chn", "cho", "chp", "chr", "chy", "cmc", "cos", "cop",
-/*  "cpe", "cpf", "cpp", "cr",  "crh", "crp", "cs",  "csb", "cu",  "cus",    */
-    "cpe", "cpf", "cpp", "cre", "crh", "crp", "ces", "csb", "chu", "cus",
-/*  "cv",  "cy",  "da",  "dak", "dar", "day", "de",  "del", "den",    */
-    "chv", "cym", "dan", "dak", "dar", "day", "deu", "del", "den",
-/*  "dgr", "din", "doi", "dra", "dsb", "dua", "dum", "dv",  "dyu",    */
-    "dgr", "din", "doi", "dra", "dsb", "dua", "dum", "div", "dyu",
-/*  "dz",  "ee",  "efi", "egy", "eka", "el",  "elx", "en",     */
-    "dzo", "ewe", "efi", "egy", "eka", "ell", "elx", "eng",
-/*  "enm", "eo",  "es",  "et",  "eu",  "ewo", "fa",     */
-    "enm", "epo", "spa", "est", "eus", "ewo", "fas",
-/*  "fan", "fat", "ff",  "fi",  "fil", "fiu", "fj",  "fo",  "fon",    */
-    "fan", "fat", "ful", "fin", "fil", "fiu", "fij", "fao", "fon",
-/*  "fr",  "frm", "fro", "frr", "frs", "fur", "fy",  "ga",  "gaa", "gay",    */
-    "fra", "frm", "fro", "frr", "frs", "fur", "fry", "gle", "gaa", "gay",
-/*  "gba", "gd",  "gem", "gez", "gil", "gl",  "gmh", "gn",     */
-    "gba", "gla", "gem", "gez", "gil", "glg", "gmh", "grn",
-/*  "goh", "gon", "gor", "got", "grb", "grc", "gsw", "gu",  "gv",     */
-    "goh", "gon", "gor", "got", "grb", "grc", "gsw", "guj", "glv",
-/*  "gwi", "ha",  "hai", "haw", "he",  "hi",  "hil", "him",    */
-    "gwi", "hau", "hai", "haw", "heb", "hin", "hil", "him",
-/*  "hit", "hmn", "ho",  "hr",  "hsb", "ht",  "hu",  "hup", "hy",  "hz",     */
-    "hit", "hmn", "hmo", "hrv", "hsb", "hat", "hun", "hup", "hye", "her",
-/*  "ia",  "iba", "id",  "ie",  "ig",  "ii",  "ijo", "ik",     */
-    "ina", "iba", "ind", "ile", "ibo", "iii", "ijo", "ipk",
-/*  "ilo", "inc", "ine", "inh", "io",  "ira", "iro", "is",  "it",      */
-    "ilo", "inc", "ine", "inh", "ido", "ira", "iro", "isl", "ita",
-/*  "iu",  "ja",  "jbo", "jpr", "jrb", "jv",  "ka",  "kaa", "kab",   */
-    "iku", "jpn", "jbo", "jpr", "jrb", "jav", "kat", "kaa", "kab",
-/*  "kac", "kaj", "kam", "kar", "kaw", "kbd", "kcg", "kfo", "kg",  "kha", "khi",*/
-    "kac", "kaj", "kam", "kar", "kaw", "kbd", "kcg", "kfo", "kg",  "kha", "khi",
-/*  "kho", "ki",  "kj",  "kk",  "kl",  "km",  "kmb", "kn",     */
-    "kho", "kik", "kua", "kaz", "kal", "khm", "kmb", "kan",
-/*  "ko",  "kok", "kos", "kpe", "kr",  "krc", "krl", "kro", "kru", "ks",     */
-    "kor", "kok", "kos", "kpe", "kau", "krc", "krl", "kro", "kru", "kas",
-/*  "ku",  "kum", "kut", "kv",  "kw",  "ky",  "la",  "lad",    */
-    "kur", "kum", "kut", "kom", "cor", "kir", "lat", "lad",
-/*  "lah", "lam", "lb",  "lez", "lg",  "li",  "ln",  "lo",  "lol",    */
-    "lah", "lam", "ltz", "lez", "lug", "lim", "lin", "lao", "lol",
-/*  "loz", "lt",  "lu",  "lua", "lui", "lun", "luo", "lus",    */
-    "loz", "lit", "lub", "lua", "lui", "lun", "luo", "lus",
-/*  "lv",  "mad", "mag", "mai", "mak", "man", "map", "mas",    */
-    "lav", "mad", "mag", "mai", "mak", "man", "map", "mas",
-/*  "mdf", "mdr", "men", "mg",  "mga", "mh",  "mi",  "mic", "min",    */
-    "mdf", "mdr", "men", "mlg", "mga", "mah", "mri", "mic", "min",
-/*  "mis", "mk",  "mkh", "ml",  "mn",  "mnc", "mni", "mno",    */
-    "mis", "mkd", "mkh", "mal", "mon", "mnc", "mni", "mno",
-/*  "mo",  "moh", "mos", "mr",  "ms",  "mt",  "mul", "mun",    */
-    "mol", "moh", "mos", "mar", "msa", "mlt", "mul", "mun",
-/*  "mus", "mwl", "mwr", "my",  "myn", "myv", "na",  "nah", "nai", "nap",    */
-    "mus", "mwl", "mwr", "mya", "myn", "myv", "nau", "nah", "nai", "nap",
-/*  "nb",  "nd",  "nds", "ne",  "new", "ng",  "nia", "nic",    */
-    "nob", "nde", "nds", "nep", "new", "ndo", "nia", "nic",
-/*  "niu", "nl",  "nn",  "no",  "nog", "non", "nqo", "nr",  "nso", "nub",    */
-    "niu", "nld", "nno", "nor", "nog", "non", "nqo", "nbl", "nso", "nub",
-/*  "nv",  "nwc", "ny",  "nym", "nyn", "nyo", "nzi", "oc",  "oj",     */
-    "nav", "nwc", "nya", "nym", "nyn", "nyo", "nzi", "oci", "oji",
-/*  "om",  "or",  "os",  "osa", "ota", "oto", "pa",  "paa",    */
-    "orm", "ori", "oss", "osa", "ota", "oto", "pan", "paa",
-/*  "pag", "pal", "pam", "pap", "pau", "peo", "phi", "phn",    */
-    "pag", "pal", "pam", "pap", "pau", "peo", "phi", "phn",
-/*  "pi",  "pl",  "pon", "pra", "pro", "ps",  "pt",  "qu",     */
-    "pli", "pol", "pon", "pra", "pro", "pus", "por", "que",
-/*  "raj", "rap", "rar", "rm",  "rn",  "ro",  "roa", "rom",    */
-    "raj", "rap", "rar", "roh", "run", "ron", "roa", "rom",
-/*  "ru",  "rup", "rw",  "sa",  "sad", "sah", "sai", "sal", "sam",    */
-    "rus", "rup", "kin", "san", "sad", "sah", "sai", "sal", "sam",
-/*  "sas", "sat", "sc",  "scn", "sco", "sd",  "se",  "sel", "sem",    */
-    "sas", "sat", "srd", "scn", "sco", "snd", "sme", "sel", "sem",
-/*  "sg",  "sga", "sgn", "shn", "si",  "sid", "sio", "sit",    */
-    "sag", "sga", "sgn", "shn", "sin", "sid", "sio", "sit",
-/*  "sk",  "sl",  "sla", "sm",  "sma", "smi", "smj", "smn",    */
-    "slk", "slv", "sla", "smo", "sma", "smi", "smj", "smn",
-/*  "sms", "sn",  "snk", "so",  "sog", "son", "sq",  "sr",     */
-    "sms", "sna", "snk", "som", "sog", "son", "sqi", "srp",
-/*  "srn", "srr", "ss",  "ssa", "st",  "su",  "suk", "sus", "sux",    */
-    "srn", "srr", "ssw", "ssa", "sot", "sun", "suk", "sus", "sux",
-/*  "sv",  "sw",  "syc", "syr", "ta",  "tai", "te",  "tem", "ter",    */
-    "swe", "swa", "syc", "syr", "tam", "tai", "tel", "tem", "ter",
-/*  "tet", "tg",  "th",  "ti",  "tig", "tiv", "tk",  "tkl",    */
-    "tet", "tgk", "tha", "tir", "tig", "tiv", "tuk", "tkl",
-/*  "tl",  "tlh", "tli", "tmh", "tn",  "to",  "tog", "tpi", "tr",     */
-    "tgl", "tlh", "tli", "tmh", "tsn", "ton", "tog", "tpi", "tur",
-/*  "ts",  "tsi", "tt",  "tum", "tup", "tut", "tvl", "tw",     */
-    "tso", "tsi", "tat", "tum", "tup", "tut", "tvl", "twi",
-/*  "ty",  "tyv", "udm", "ug",  "uga", "uk",  "umb", "und", "ur",     */
-    "tah", "tyv", "udm", "uig", "uga", "ukr", "umb", "und", "urd",
-/*  "uz",  "vai", "ve",  "vi",  "vo",  "vot", "wa",  "wak",    */
-    "uzb", "vai", "ven", "vie", "vol", "vot", "wln", "wak",
-/*  "wal", "war", "was", "wen", "wo",  "xal", "xh",  "yao", "yap",    */
-    "wal", "war", "was", "wen", "wol", "xal", "xho", "yao", "yap",
-/*  "yi",  "yo",  "ypk", "za",  "zap", "zbl", "zen", "zh",  "znd",    */
-    "yid", "yor", "ypk", "zha", "zap", "zbl", "zen", "zho", "znd",
-/*  "zu",  "zun", "zxx", "zza",                                         */
-    "zul", "zun", "zxx", "zza",
-NULL,
-/*  "in",  "iw",  "ji",  "jw",  "sh",                          */
-    "ind", "heb", "yid", "jaw", "srp",
-NULL
-};
-
-/**
- * Table of 2-letter country codes.
- *
- * This list must be in sorted order.  This list is returned directly
- * to the user by some API.
- *
- * This list must be kept in sync with COUNTRIES_3, with corresponding
- * entries matched.
- *
- * This table should be terminated with a NULL entry, followed by a
- * second list, and another NULL entry.  The first list is visible to
- * user code when this array is returned by API.  The second list
- * contains codes we support, but do not expose through user API.
- *
- * Notes:
- *
- * ZR(ZAR) is now CD(COD) and FX(FXX) is PS(PSE) as per
- * http://www.evertype.com/standards/iso3166/iso3166-1-en.html added
- * new codes keeping the old ones for compatibility updated to include
- * 1999/12/03 revisions *CWB*
- *
- * RO(ROM) is now RO(ROU) according to
- * http://www.iso.org/iso/en/prods-services/iso3166ma/03updates-on-iso-3166/nlv3e-rou.html
- */
-static const char * const COUNTRIES[] = {
-    "AD",  "AE",  "AF",  "AG",  "AI",  "AL",  "AM",  "AN",
-    "AO",  "AQ",  "AR",  "AS",  "AT",  "AU",  "AW",  "AX",  "AZ",
-    "BA",  "BB",  "BD",  "BE",  "BF",  "BG",  "BH",  "BI",
-    "BJ",  "BL",  "BM",  "BN",  "BO",  "BR",  "BS",  "BT",  "BV",
-    "BW",  "BY",  "BZ",  "CA",  "CC",  "CD",  "CF",  "CG",
-    "CH",  "CI",  "CK",  "CL",  "CM",  "CN",  "CO",  "CR",
-    "CU",  "CV",  "CX",  "CY",  "CZ",  "DE",  "DJ",  "DK",
-    "DM",  "DO",  "DZ",  "EC",  "EE",  "EG",  "EH",  "ER",
-    "ES",  "ET",  "FI",  "FJ",  "FK",  "FM",  "FO",  "FR",
-    "GA",  "GB",  "GD",  "GE",  "GF",  "GG",  "GH",  "GI",  "GL",
-    "GM",  "GN",  "GP",  "GQ",  "GR",  "GS",  "GT",  "GU",
-    "GW",  "GY",  "HK",  "HM",  "HN",  "HR",  "HT",  "HU",
-    "ID",  "IE",  "IL",  "IM",  "IN",  "IO",  "IQ",  "IR",  "IS",
-    "IT",  "JE",  "JM",  "JO",  "JP",  "KE",  "KG",  "KH",  "KI",
-    "KM",  "KN",  "KP",  "KR",  "KW",  "KY",  "KZ",  "LA",
-    "LB",  "LC",  "LI",  "LK",  "LR",  "LS",  "LT",  "LU",
-    "LV",  "LY",  "MA",  "MC",  "MD",  "ME",  "MF",  "MG",  "MH",  "MK",
-    "ML",  "MM",  "MN",  "MO",  "MP",  "MQ",  "MR",  "MS",
-    "MT",  "MU",  "MV",  "MW",  "MX",  "MY",  "MZ",  "NA",
-    "NC",  "NE",  "NF",  "NG",  "NI",  "NL",  "NO",  "NP",
-    "NR",  "NU",  "NZ",  "OM",  "PA",  "PE",  "PF",  "PG",
-    "PH",  "PK",  "PL",  "PM",  "PN",  "PR",  "PS",  "PT",
-    "PW",  "PY",  "QA",  "RE",  "RO",  "RS",  "RU",  "RW",  "SA",
-    "SB",  "SC",  "SD",  "SE",  "SG",  "SH",  "SI",  "SJ",
-    "SK",  "SL",  "SM",  "SN",  "SO",  "SR",  "ST",  "SV",
-    "SY",  "SZ",  "TC",  "TD",  "TF",  "TG",  "TH",  "TJ",
-    "TK",  "TL",  "TM",  "TN",  "TO",  "TR",  "TT",  "TV",
-    "TW",  "TZ",  "UA",  "UG",  "UM",  "US",  "UY",  "UZ",
-    "VA",  "VC",  "VE",  "VG",  "VI",  "VN",  "VU",  "WF",
-    "WS",  "YE",  "YT",  "ZA",  "ZM",  "ZW",
-NULL,
-    "FX",  "CS",  "RO",  "TP",  "YU",  "ZR",   /* obsolete country codes */
-NULL
-};
-
-static const char* const DEPRECATED_COUNTRIES[] ={
-    "BU", "CS", "DY", "FX", "HV", "NH", "RH", "TP", "YU", "ZR", NULL, NULL /* deprecated country list */
-};
-static const char* const REPLACEMENT_COUNTRIES[] = {
-/*  "BU", "CS", "DY", "FX", "HV", "NH", "RH", "TP", "YU", "ZR" */
-    "MM", "RS", "BJ", "FR", "BF", "VU", "ZW", "TL", "RS", "CD", NULL, NULL  /* replacement country codes */      
-};
-    
-/**
- * Table of 3-letter country codes.
- *
- * This is a lookup table used to convert 3-letter country codes to
- * their 2-letter equivalent.  It must be kept in sync with COUNTRIES.
- * For all valid i, COUNTRIES[i] must refer to the same country as
- * COUNTRIES_3[i].  The commented-out lines are copied from COUNTRIES
- * to make eyeballing this baby easier.
- *
- * This table should be terminated with a NULL entry, followed by a
- * second list, and another NULL entry.  The two lists correspond to
- * the two lists in COUNTRIES.
- */
-static const char * const COUNTRIES_3[] = {
-/*  "AD",  "AE",  "AF",  "AG",  "AI",  "AL",  "AM",  "AN",     */
-    "AND", "ARE", "AFG", "ATG", "AIA", "ALB", "ARM", "ANT",
-/*  "AO",  "AQ",  "AR",  "AS",  "AT",  "AU",  "AW",  "AX",  "AZ",     */
-    "AGO", "ATA", "ARG", "ASM", "AUT", "AUS", "ABW", "ALA", "AZE",
-/*  "BA",  "BB",  "BD",  "BE",  "BF",  "BG",  "BH",  "BI",     */
-    "BIH", "BRB", "BGD", "BEL", "BFA", "BGR", "BHR", "BDI",
-/*  "BJ",  "BL",  "BM",  "BN",  "BO",  "BR",  "BS",  "BT",  "BV",     */
-    "BEN", "BLM", "BMU", "BRN", "BOL", "BRA", "BHS", "BTN", "BVT",
-/*  "BW",  "BY",  "BZ",  "CA",  "CC",  "CD",  "CF",  "CG",     */
-    "BWA", "BLR", "BLZ", "CAN", "CCK", "COD", "CAF", "COG",
-/*  "CH",  "CI",  "CK",  "CL",  "CM",  "CN",  "CO",  "CR",     */
-    "CHE", "CIV", "COK", "CHL", "CMR", "CHN", "COL", "CRI",
-/*  "CU",  "CV",  "CX",  "CY",  "CZ",  "DE",  "DJ",  "DK",     */
-    "CUB", "CPV", "CXR", "CYP", "CZE", "DEU", "DJI", "DNK",
-/*  "DM",  "DO",  "DZ",  "EC",  "EE",  "EG",  "EH",  "ER",     */
-    "DMA", "DOM", "DZA", "ECU", "EST", "EGY", "ESH", "ERI",
-/*  "ES",  "ET",  "FI",  "FJ",  "FK",  "FM",  "FO",  "FR",     */
-    "ESP", "ETH", "FIN", "FJI", "FLK", "FSM", "FRO", "FRA",
-/*  "GA",  "GB",  "GD",  "GE",  "GF",  "GG",  "GH",  "GI",  "GL",     */
-    "GAB", "GBR", "GRD", "GEO", "GUF", "GGY", "GHA", "GIB", "GRL",
-/*  "GM",  "GN",  "GP",  "GQ",  "GR",  "GS",  "GT",  "GU",     */
-    "GMB", "GIN", "GLP", "GNQ", "GRC", "SGS", "GTM", "GUM",
-/*  "GW",  "GY",  "HK",  "HM",  "HN",  "HR",  "HT",  "HU",     */
-    "GNB", "GUY", "HKG", "HMD", "HND", "HRV", "HTI", "HUN",
-/*  "ID",  "IE",  "IL",  "IM",  "IN",  "IO",  "IQ",  "IR",  "IS" */
-    "IDN", "IRL", "ISR", "IMN", "IND", "IOT", "IRQ", "IRN", "ISL",
-/*  "IT",  "JE",  "JM",  "JO",  "JP",  "KE",  "KG",  "KH",  "KI",     */
-    "ITA", "JEY", "JAM", "JOR", "JPN", "KEN", "KGZ", "KHM", "KIR",
-/*  "KM",  "KN",  "KP",  "KR",  "KW",  "KY",  "KZ",  "LA",     */
-    "COM", "KNA", "PRK", "KOR", "KWT", "CYM", "KAZ", "LAO",
-/*  "LB",  "LC",  "LI",  "LK",  "LR",  "LS",  "LT",  "LU",     */
-    "LBN", "LCA", "LIE", "LKA", "LBR", "LSO", "LTU", "LUX",
-/*  "LV",  "LY",  "MA",  "MC",  "MD",  "ME",  "MF",  "MG",  "MH",  "MK",     */
-    "LVA", "LBY", "MAR", "MCO", "MDA", "MNE", "MAF", "MDG", "MHL", "MKD",
-/*  "ML",  "MM",  "MN",  "MO",  "MP",  "MQ",  "MR",  "MS",     */
-    "MLI", "MMR", "MNG", "MAC", "MNP", "MTQ", "MRT", "MSR",
-/*  "MT",  "MU",  "MV",  "MW",  "MX",  "MY",  "MZ",  "NA",     */
-    "MLT", "MUS", "MDV", "MWI", "MEX", "MYS", "MOZ", "NAM",
-/*  "NC",  "NE",  "NF",  "NG",  "NI",  "NL",  "NO",  "NP",     */
-    "NCL", "NER", "NFK", "NGA", "NIC", "NLD", "NOR", "NPL",
-/*  "NR",  "NU",  "NZ",  "OM",  "PA",  "PE",  "PF",  "PG",     */
-    "NRU", "NIU", "NZL", "OMN", "PAN", "PER", "PYF", "PNG",
-/*  "PH",  "PK",  "PL",  "PM",  "PN",  "PR",  "PS",  "PT",     */
-    "PHL", "PAK", "POL", "SPM", "PCN", "PRI", "PSE", "PRT",
-/*  "PW",  "PY",  "QA",  "RE",  "RO",  "RS",  "RU",  "RW",  "SA",     */
-    "PLW", "PRY", "QAT", "REU", "ROU", "SRB", "RUS", "RWA", "SAU",
-/*  "SB",  "SC",  "SD",  "SE",  "SG",  "SH",  "SI",  "SJ",     */
-    "SLB", "SYC", "SDN", "SWE", "SGP", "SHN", "SVN", "SJM",
-/*  "SK",  "SL",  "SM",  "SN",  "SO",  "SR",  "ST",  "SV",     */
-    "SVK", "SLE", "SMR", "SEN", "SOM", "SUR", "STP", "SLV",
-/*  "SY",  "SZ",  "TC",  "TD",  "TF",  "TG",  "TH",  "TJ",     */
-    "SYR", "SWZ", "TCA", "TCD", "ATF", "TGO", "THA", "TJK",
-/*  "TK",  "TL",  "TM",  "TN",  "TO",  "TR",  "TT",  "TV",     */
-    "TKL", "TLS", "TKM", "TUN", "TON", "TUR", "TTO", "TUV",
-/*  "TW",  "TZ",  "UA",  "UG",  "UM",  "US",  "UY",  "UZ",     */
-    "TWN", "TZA", "UKR", "UGA", "UMI", "USA", "URY", "UZB",
-/*  "VA",  "VC",  "VE",  "VG",  "VI",  "VN",  "VU",  "WF",     */
-    "VAT", "VCT", "VEN", "VGB", "VIR", "VNM", "VUT", "WLF",
-/*  "WS",  "YE",  "YT",  "ZA",  "ZM",  "ZW",          */
-    "WSM", "YEM", "MYT", "ZAF", "ZMB", "ZWE",
-NULL,
-/*  "FX",  "CS",  "RO",  "TP",  "YU",  "ZR",   */
-    "FXX", "SCG", "ROM", "TMP", "YUG", "ZAR",
-NULL
-};
-
-typedef struct CanonicalizationMap {
-    const char *id;          /* input ID */
-    const char *canonicalID; /* canonicalized output ID */
-    const char *keyword;     /* keyword, or NULL if none */
-    const char *value;       /* keyword value, or NULL if kw==NULL */
-} CanonicalizationMap;
-
-/**
- * A map to canonicalize locale IDs.  This handles a variety of
- * different semantic kinds of transformations.
- */
-static const CanonicalizationMap CANONICALIZE_MAP[] = {
-    { "",               "en_US_POSIX", NULL, NULL }, /* .NET name */
-    { "C",              "en_US_POSIX", NULL, NULL }, /* POSIX name */
-    { "posix",          "en_US_POSIX", NULL, NULL }, /* POSIX name (alias of C) */
-    { "art_LOJBAN",     "jbo", NULL, NULL }, /* registered name */
-    { "az_AZ_CYRL",     "az_Cyrl_AZ", NULL, NULL }, /* .NET name */
-    { "az_AZ_LATN",     "az_Latn_AZ", NULL, NULL }, /* .NET name */
-    { "ca_ES_PREEURO",  "ca_ES", "currency", "ESP" },
-    { "cel_GAULISH",    "cel__GAULISH", NULL, NULL }, /* registered name */
-    { "de_1901",        "de__1901", NULL, NULL }, /* registered name */
-    { "de_1906",        "de__1906", NULL, NULL }, /* registered name */
-    { "de__PHONEBOOK",  "de", "collation", "phonebook" }, /* Old ICU name */
-    { "de_AT_PREEURO",  "de_AT", "currency", "ATS" },
-    { "de_DE_PREEURO",  "de_DE", "currency", "DEM" },
-    { "de_LU_PREEURO",  "de_LU", "currency", "LUF" },
-    { "el_GR_PREEURO",  "el_GR", "currency", "GRD" },
-    { "en_BOONT",       "en__BOONT", NULL, NULL }, /* registered name */
-    { "en_SCOUSE",      "en__SCOUSE", NULL, NULL }, /* registered name */
-    { "en_BE_PREEURO",  "en_BE", "currency", "BEF" },
-    { "en_IE_PREEURO",  "en_IE", "currency", "IEP" },
-    { "es__TRADITIONAL", "es", "collation", "traditional" }, /* Old ICU name */
-    { "es_ES_PREEURO",  "es_ES", "currency", "ESP" },
-    { "eu_ES_PREEURO",  "eu_ES", "currency", "ESP" },
-    { "fi_FI_PREEURO",  "fi_FI", "currency", "FIM" },
-    { "fr_BE_PREEURO",  "fr_BE", "currency", "BEF" },
-    { "fr_FR_PREEURO",  "fr_FR", "currency", "FRF" },
-    { "fr_LU_PREEURO",  "fr_LU", "currency", "LUF" },
-    { "ga_IE_PREEURO",  "ga_IE", "currency", "IEP" },
-    { "gl_ES_PREEURO",  "gl_ES", "currency", "ESP" },
-    { "hi__DIRECT",     "hi", "collation", "direct" }, /* Old ICU name */
-    { "it_IT_PREEURO",  "it_IT", "currency", "ITL" },
-    { "ja_JP_TRADITIONAL", "ja_JP", "calendar", "japanese" }, /* Old ICU name */
-    { "nb_NO_NY",       "nn_NO", NULL, NULL },  /* "markus said this was ok" :-) */
-    { "nl_BE_PREEURO",  "nl_BE", "currency", "BEF" },
-    { "nl_NL_PREEURO",  "nl_NL", "currency", "NLG" },
-    { "pt_PT_PREEURO",  "pt_PT", "currency", "PTE" },
-    { "sl_ROZAJ",       "sl__ROZAJ", NULL, NULL }, /* registered name */
-    { "sr_SP_CYRL",     "sr_Cyrl_RS", NULL, NULL }, /* .NET name */
-    { "sr_SP_LATN",     "sr_Latn_RS", NULL, NULL }, /* .NET name */
-    { "sr_YU_CYRILLIC", "sr_Cyrl_RS", NULL, NULL }, /* Linux name */
-    { "th_TH_TRADITIONAL", "th_TH", "calendar", "buddhist" }, /* Old ICU name */
-    { "uz_UZ_CYRILLIC", "uz_Cyrl_UZ", NULL, NULL }, /* Linux name */
-    { "uz_UZ_CYRL",     "uz_Cyrl_UZ", NULL, NULL }, /* .NET name */
-    { "uz_UZ_LATN",     "uz_Latn_UZ", NULL, NULL }, /* .NET name */
-    { "zh_CHS",         "zh_Hans", NULL, NULL }, /* .NET name */
-    { "zh_CHT",         "zh_Hant", NULL, NULL }, /* .NET name */
-    { "zh_GAN",         "zh__GAN", NULL, NULL }, /* registered name */
-    { "zh_GUOYU",       "zh", NULL, NULL }, /* registered name */
-    { "zh_HAKKA",       "zh__HAKKA", NULL, NULL }, /* registered name */
-    { "zh_MIN",         "zh__MIN", NULL, NULL }, /* registered name */
-    { "zh_MIN_NAN",     "zh__MINNAN", NULL, NULL }, /* registered name */
-    { "zh_WUU",         "zh__WUU", NULL, NULL }, /* registered name */
-    { "zh_XIANG",       "zh__XIANG", NULL, NULL }, /* registered name */
-    { "zh_YUE",         "zh__YUE", NULL, NULL }, /* registered name */
-};
-
-typedef struct VariantMap {
-    const char *variant;          /* input ID */
-    const char *keyword;     /* keyword, or NULL if none */
-    const char *value;       /* keyword value, or NULL if kw==NULL */
-} VariantMap;
-
-static const VariantMap VARIANT_MAP[] = {
-    { "EURO",   "currency", "EUR" },
-    { "PINYIN", "collation", "pinyin" }, /* Solaris variant */
-    { "STROKE", "collation", "stroke" }  /* Solaris variant */
-};
-
-/* ### Keywords **************************************************/
-
-#define ULOC_KEYWORD_BUFFER_LEN 25
-#define ULOC_MAX_NO_KEYWORDS 25
-
-static const char * 
-locale_getKeywordsStart(const char *localeID) {
-    const char *result = NULL;
-    if((result = uprv_strchr(localeID, '@')) != NULL) {
-        return result;
-    }
-#if (U_CHARSET_FAMILY == U_EBCDIC_FAMILY)
-    else {
-        /* We do this because the @ sign is variant, and the @ sign used on one
-        EBCDIC machine won't be compiled the same way on other EBCDIC based
-        machines. */
-        static const uint8_t ebcdicSigns[] = { 0x7C, 0x44, 0x66, 0x80, 0xAC, 0xAE, 0xAF, 0xB5, 0xEC, 0xEF, 0x00 };
-        const uint8_t *charToFind = ebcdicSigns;
-        while(*charToFind) {
-            if((result = uprv_strchr(localeID, *charToFind)) != NULL) {
-                return result;
-            }
-            charToFind++;
-        }
-    }
-#endif
-    return NULL;
-}
-
-/**
- * @param buf buffer of size [ULOC_KEYWORD_BUFFER_LEN]
- * @param keywordName incoming name to be canonicalized
- * @param status return status (keyword too long)
- * @return length of the keyword name
- */
-static int32_t locale_canonKeywordName(char *buf, const char *keywordName, UErrorCode *status)
-{
-  int32_t i;
-  int32_t keywordNameLen = (int32_t)uprv_strlen(keywordName);
-  
-  if(keywordNameLen >= ULOC_KEYWORD_BUFFER_LEN) {
-    /* keyword name too long for internal buffer */
-    *status = U_INTERNAL_PROGRAM_ERROR;
-          return 0;
-  }
-  
-  /* normalize the keyword name */
-  for(i = 0; i < keywordNameLen; i++) {
-    buf[i] = uprv_tolower(keywordName[i]);
-  }
-  buf[i] = 0;
-    
-  return keywordNameLen;
-}
-
-typedef struct {
-    char keyword[ULOC_KEYWORD_BUFFER_LEN];
-    int32_t keywordLen;
-    const char *valueStart;
-    int32_t valueLen;
-} KeywordStruct;
-
-static int32_t U_CALLCONV
-compareKeywordStructs(const void *context, const void *left, const void *right) {
-    const char* leftString = ((const KeywordStruct *)left)->keyword;
-    const char* rightString = ((const KeywordStruct *)right)->keyword;
-    return uprv_strcmp(leftString, rightString);
-}
-
-/**
- * Both addKeyword and addValue must already be in canonical form.
- * Either both addKeyword and addValue are NULL, or neither is NULL.
- * If they are not NULL they must be zero terminated.
- * If addKeyword is not NULL is must have length small enough to fit in KeywordStruct.keyword.
- */
-static int32_t
-_getKeywords(const char *localeID,
-             char prev,
-             char *keywords, int32_t keywordCapacity,
-             char *values, int32_t valuesCapacity, int32_t *valLen,
-             UBool valuesToo,
-             const char* addKeyword,
-             const char* addValue,
-             UErrorCode *status)
-{
-    KeywordStruct keywordList[ULOC_MAX_NO_KEYWORDS];
-    
-    int32_t maxKeywords = ULOC_MAX_NO_KEYWORDS;
-    int32_t numKeywords = 0;
-    const char* pos = localeID;
-    const char* equalSign = NULL;
-    const char* semicolon = NULL;
-    int32_t i = 0, j, n;
-    int32_t keywordsLen = 0;
-    int32_t valuesLen = 0;
-
-    if(prev == '@') { /* start of keyword definition */
-        /* we will grab pairs, trim spaces, lowercase keywords, sort and return */
-        do {
-            UBool duplicate = FALSE;
-            /* skip leading spaces */
-            while(*pos == ' ') {
-                pos++;
-            }
-            if (!*pos) { /* handle trailing "; " */
-                break;
-            }
-            if(numKeywords == maxKeywords) {
-                *status = U_INTERNAL_PROGRAM_ERROR;
-                return 0;
-            }
-            equalSign = uprv_strchr(pos, '=');
-            semicolon = uprv_strchr(pos, ';');
-            /* lack of '=' [foo@currency] is illegal */
-            /* ';' before '=' [foo@currency;collation=pinyin] is illegal */
-            if(!equalSign || (semicolon && semicolon<equalSign)) {
-                *status = U_INVALID_FORMAT_ERROR;
-                return 0;
-            }
-            /* need to normalize both keyword and keyword name */
-            if(equalSign - pos >= ULOC_KEYWORD_BUFFER_LEN) {
-                /* keyword name too long for internal buffer */
-                *status = U_INTERNAL_PROGRAM_ERROR;
-                return 0;
-            }
-            for(i = 0, n = 0; i < equalSign - pos; ++i) {
-                if (pos[i] != ' ') {
-                    keywordList[numKeywords].keyword[n++] = uprv_tolower(pos[i]);
-                }
-            }
-            keywordList[numKeywords].keyword[n] = 0;
-            keywordList[numKeywords].keywordLen = n;
-            /* now grab the value part. First we skip the '=' */
-            equalSign++;
-            /* then we leading spaces */
-            while(*equalSign == ' ') {
-                equalSign++;
-            }
-            keywordList[numKeywords].valueStart = equalSign;
-            
-            pos = semicolon;
-            i = 0;
-            if(pos) {
-                while(*(pos - i - 1) == ' ') {
-                    i++;
-                }
-                keywordList[numKeywords].valueLen = (int32_t)(pos - equalSign - i);
-                pos++;
-            } else {
-                i = (int32_t)uprv_strlen(equalSign);
-                while(equalSign[i-1] == ' ') {
-                    i--;
-                }
-                keywordList[numKeywords].valueLen = i;
-            }
-            /* If this is a duplicate keyword, then ignore it */
-            for (j=0; j<numKeywords; ++j) {
-                if (uprv_strcmp(keywordList[j].keyword, keywordList[numKeywords].keyword) == 0) {
-                    duplicate = TRUE;
-                    break;
-                }
-            }
-            if (!duplicate) {
-                ++numKeywords;
-            }
-        } while(pos);
-
-        /* Handle addKeyword/addValue. */
-        if (addKeyword != NULL) {
-            UBool duplicate = FALSE;
-            U_ASSERT(addValue != NULL);
-            /* Search for duplicate; if found, do nothing. Explicit keyword
-               overrides addKeyword. */
-            for (j=0; j<numKeywords; ++j) {
-                if (uprv_strcmp(keywordList[j].keyword, addKeyword) == 0) {
-                    duplicate = TRUE;
-                    break;
-                }
-            }
-            if (!duplicate) {
-                if (numKeywords == maxKeywords) {
-                    *status = U_INTERNAL_PROGRAM_ERROR;
-                    return 0;
-                }
-                uprv_strcpy(keywordList[numKeywords].keyword, addKeyword);
-                keywordList[numKeywords].keywordLen = (int32_t)uprv_strlen(addKeyword);
-                keywordList[numKeywords].valueStart = addValue;
-                keywordList[numKeywords].valueLen = (int32_t)uprv_strlen(addValue);
-                ++numKeywords;
-            }
-        } else {
-            U_ASSERT(addValue == NULL);
-        }
-
-        /* now we have a list of keywords */
-        /* we need to sort it */
-        uprv_sortArray(keywordList, numKeywords, sizeof(KeywordStruct), compareKeywordStructs, NULL, FALSE, status);
-        
-        /* Now construct the keyword part */
-        for(i = 0; i < numKeywords; i++) {
-            if(keywordsLen + keywordList[i].keywordLen + 1< keywordCapacity) {
-                uprv_strcpy(keywords+keywordsLen, keywordList[i].keyword);
-                if(valuesToo) {
-                    keywords[keywordsLen + keywordList[i].keywordLen] = '=';
-                } else {
-                    keywords[keywordsLen + keywordList[i].keywordLen] = 0;
-                }
-            }
-            keywordsLen += keywordList[i].keywordLen + 1;
-            if(valuesToo) {
-                if(keywordsLen + keywordList[i].valueLen < keywordCapacity) {
-                    uprv_strncpy(keywords+keywordsLen, keywordList[i].valueStart, keywordList[i].valueLen);
-                }
-                keywordsLen += keywordList[i].valueLen;
-                
-                if(i < numKeywords - 1) {
-                    if(keywordsLen < keywordCapacity) {       
-                        keywords[keywordsLen] = ';';
-                    }
-                    keywordsLen++;
-                }
-            }
-            if(values) {
-                if(valuesLen + keywordList[i].valueLen + 1< valuesCapacity) {
-                    uprv_strcpy(values+valuesLen, keywordList[i].valueStart);
-                    values[valuesLen + keywordList[i].valueLen] = 0;
-                }
-                valuesLen += keywordList[i].valueLen + 1;
-            }
-        }
-        if(values) {
-            values[valuesLen] = 0;
-            if(valLen) {
-                *valLen = valuesLen;
-            }
-        }
-        return u_terminateChars(keywords, keywordCapacity, keywordsLen, status);   
-    } else {
-        return 0;
-    }
-}
-
-U_CFUNC int32_t
-locale_getKeywords(const char *localeID,
-                   char prev,
-                   char *keywords, int32_t keywordCapacity,
-                   char *values, int32_t valuesCapacity, int32_t *valLen,
-                   UBool valuesToo,
-                   UErrorCode *status) {
-    return _getKeywords(localeID, prev, keywords, keywordCapacity,
-                        values, valuesCapacity, valLen, valuesToo,
-                        NULL, NULL, status);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getKeywordValue(const char* localeID,
-                     const char* keywordName,
-                     char* buffer, int32_t bufferCapacity,
-                     UErrorCode* status)
-{ 
-    const char* nextSeparator = NULL;
-    char keywordNameBuffer[ULOC_KEYWORD_BUFFER_LEN];
-    char localeKeywordNameBuffer[ULOC_KEYWORD_BUFFER_LEN];
-    int32_t i = 0;
-    int32_t result = 0;
-
-    if(status && U_SUCCESS(*status) && localeID) {
-    
-      const char* startSearchHere = uprv_strchr(localeID, '@'); /* TODO: REVISIT: shouldn't this be locale_getKeywordsStart ? */
-      if(startSearchHere == NULL) {
-          /* no keywords, return at once */
-          return 0;
-      }
-
-      locale_canonKeywordName(keywordNameBuffer, keywordName, status);
-      if(U_FAILURE(*status)) {
-        return 0;
-      }
-    
-      /* find the first keyword */
-      while(startSearchHere) {
-          startSearchHere++;
-          /* skip leading spaces (allowed?) */
-          while(*startSearchHere == ' ') {
-              startSearchHere++;
-          }
-          nextSeparator = uprv_strchr(startSearchHere, '=');
-          /* need to normalize both keyword and keyword name */
-          if(!nextSeparator) {
-              break;
-          }
-          if(nextSeparator - startSearchHere >= ULOC_KEYWORD_BUFFER_LEN) {
-              /* keyword name too long for internal buffer */
-              *status = U_INTERNAL_PROGRAM_ERROR;
-              return 0;
-          }
-          for(i = 0; i < nextSeparator - startSearchHere; i++) {
-              localeKeywordNameBuffer[i] = uprv_tolower(startSearchHere[i]);
-          }
-          /* trim trailing spaces */
-          while(startSearchHere[i-1] == ' ') {
-              i--;
-          }
-          localeKeywordNameBuffer[i] = 0;
-        
-          startSearchHere = uprv_strchr(nextSeparator, ';');
-        
-          if(uprv_strcmp(keywordNameBuffer, localeKeywordNameBuffer) == 0) {
-              nextSeparator++;
-              while(*nextSeparator == ' ') {
-                  nextSeparator++;
-              }
-              /* we actually found the keyword. Copy the value */
-              if(startSearchHere && startSearchHere - nextSeparator < bufferCapacity) {
-                  while(*(startSearchHere-1) == ' ') {
-                      startSearchHere--;
-                  }
-                  uprv_strncpy(buffer, nextSeparator, startSearchHere - nextSeparator);
-                  result = u_terminateChars(buffer, bufferCapacity, (int32_t)(startSearchHere - nextSeparator), status);
-              } else if(!startSearchHere && (int32_t)uprv_strlen(nextSeparator) < bufferCapacity) { /* last item in string */
-                  i = (int32_t)uprv_strlen(nextSeparator);
-                  while(nextSeparator[i - 1] == ' ') {
-                      i--;
-                  }
-                  uprv_strncpy(buffer, nextSeparator, i);
-                  result = u_terminateChars(buffer, bufferCapacity, i, status);
-              } else {
-                  /* give a bigger buffer, please */
-                  *status = U_BUFFER_OVERFLOW_ERROR;
-                  if(startSearchHere) {
-                      result = (int32_t)(startSearchHere - nextSeparator);
-                  } else {
-                      result = (int32_t)uprv_strlen(nextSeparator); 
-                  }
-              }
-              return result;
-          }
-      }
-    }
-    return 0;
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_setKeywordValue(const char* keywordName,
-                     const char* keywordValue,
-                     char* buffer, int32_t bufferCapacity,
-                     UErrorCode* status)
-{
-    /* TODO: sorting. removal. */
-    int32_t keywordNameLen;
-    int32_t keywordValueLen;
-    int32_t bufLen;
-    int32_t needLen = 0;
-    int32_t foundValueLen;
-    int32_t keywordAtEnd = 0; /* is the keyword at the end of the string? */
-    char keywordNameBuffer[ULOC_KEYWORD_BUFFER_LEN];
-    char localeKeywordNameBuffer[ULOC_KEYWORD_BUFFER_LEN];
-    int32_t i = 0;
-    int32_t rc;
-    char* nextSeparator = NULL;
-    char* nextEqualsign = NULL;
-    char* startSearchHere = NULL;
-    char* keywordStart = NULL;
-    char *insertHere = NULL;
-    if(U_FAILURE(*status)) { 
-        return -1; 
-    }
-    if(bufferCapacity>1) {
-        bufLen = (int32_t)uprv_strlen(buffer);
-    } else {
-        *status = U_ILLEGAL_ARGUMENT_ERROR;
-        return 0;
-    }
-    if(bufferCapacity<bufLen) {
-        /* The capacity is less than the length?! Is this NULL terminated? */
-        *status = U_ILLEGAL_ARGUMENT_ERROR;
-        return 0;
-    }
-    if(keywordValue && !*keywordValue) { 
-        keywordValue = NULL;
-    }
-    if(keywordValue) {
-        keywordValueLen = (int32_t)uprv_strlen(keywordValue);
-    } else { 
-        keywordValueLen = 0;
-    }
-    keywordNameLen = locale_canonKeywordName(keywordNameBuffer, keywordName, status);
-    if(U_FAILURE(*status)) {
-        return 0;
-    }
-    startSearchHere = (char*)locale_getKeywordsStart(buffer);
-    if(startSearchHere == NULL || (startSearchHere[1]==0)) {
-        if(!keywordValue) { /* no keywords = nothing to remove */
-            return bufLen; 
-        }
-
-        needLen = bufLen+1+keywordNameLen+1+keywordValueLen;
-        if(startSearchHere) { /* had a single @ */ 
-            needLen--; /* already had the @ */
-            /* startSearchHere points at the @ */
-        } else {
-            startSearchHere=buffer+bufLen;
-        }
-        if(needLen >= bufferCapacity) {
-            *status = U_BUFFER_OVERFLOW_ERROR;
-            return needLen; /* no change */
-        }
-        *startSearchHere = '@';
-        startSearchHere++;
-        uprv_strcpy(startSearchHere, keywordNameBuffer);
-        startSearchHere += keywordNameLen;
-        *startSearchHere = '=';
-        startSearchHere++;
-        uprv_strcpy(startSearchHere, keywordValue);
-        startSearchHere+=keywordValueLen;
-        return needLen;
-    } /* end shortcut - no @ */
-    
-    keywordStart = startSearchHere;
-    /* search for keyword */
-    while(keywordStart) {
-        keywordStart++;
-        /* skip leading spaces (allowed?) */
-        while(*keywordStart == ' ') {
-            keywordStart++;
-        }
-        nextEqualsign = uprv_strchr(keywordStart, '=');
-        /* need to normalize both keyword and keyword name */
-        if(!nextEqualsign) {
-            break;
-        }
-        if(nextEqualsign - keywordStart >= ULOC_KEYWORD_BUFFER_LEN) {
-            /* keyword name too long for internal buffer */
-            *status = U_INTERNAL_PROGRAM_ERROR;
-            return 0;
-        }
-        for(i = 0; i < nextEqualsign - keywordStart; i++) {
-            localeKeywordNameBuffer[i] = uprv_tolower(keywordStart[i]);
-        }
-        /* trim trailing spaces */
-        while(keywordStart[i-1] == ' ') {
-            i--;
-        }
-        localeKeywordNameBuffer[i] = 0;
-
-        nextSeparator = uprv_strchr(nextEqualsign, ';');
-        rc = uprv_strcmp(keywordNameBuffer, localeKeywordNameBuffer);
-        if(rc == 0) {
-            nextEqualsign++;
-            while(*nextEqualsign == ' ') {
-                nextEqualsign++;
-            }
-            /* we actually found the keyword. Change the value */
-            if (nextSeparator) {
-                keywordAtEnd = 0;
-                foundValueLen = (int32_t)(nextSeparator - nextEqualsign);
-            } else {
-                keywordAtEnd = 1;
-                foundValueLen = (int32_t)uprv_strlen(nextEqualsign);
-            }
-            if(keywordValue) { /* adding a value - not removing */
-              if(foundValueLen == keywordValueLen) {
-                uprv_strncpy(nextEqualsign, keywordValue, keywordValueLen);
-                return bufLen; /* no change in size */
-              } else if(foundValueLen > keywordValueLen) {
-                int32_t delta = foundValueLen - keywordValueLen;
-                if(nextSeparator) { /* RH side */
-                  uprv_memmove(nextSeparator - delta, nextSeparator, bufLen-(nextSeparator-buffer));
-                }
-                uprv_strncpy(nextEqualsign, keywordValue, keywordValueLen);
-                bufLen -= delta;
-                buffer[bufLen]=0;
-                return bufLen;
-              } else { /* FVL < KVL */
-                int32_t delta = keywordValueLen - foundValueLen;
-                if((bufLen+delta) >= bufferCapacity) {
-                  *status = U_BUFFER_OVERFLOW_ERROR;
-                  return bufLen+delta;
-                }
-                if(nextSeparator) { /* RH side */
-                  uprv_memmove(nextSeparator+delta,nextSeparator, bufLen-(nextSeparator-buffer));
-                }
-                uprv_strncpy(nextEqualsign, keywordValue, keywordValueLen);
-                bufLen += delta;
-                buffer[bufLen]=0;
-                return bufLen;
-              }
-            } else { /* removing a keyword */
-              if(keywordAtEnd) {
-                /* zero out the ';' or '@' just before startSearchhere */
-                keywordStart[-1] = 0;
-                return (int32_t)((keywordStart-buffer)-1); /* (string length without keyword) minus separator */
-              } else {
-                uprv_memmove(keywordStart, nextSeparator+1, bufLen-((nextSeparator+1)-buffer));
-                keywordStart[bufLen-((nextSeparator+1)-buffer)]=0;
-                return (int32_t)(bufLen-((nextSeparator+1)-keywordStart));
-              }
-            }
-        } else if(rc<0){ /* end match keyword */
-          /* could insert at this location. */
-          insertHere = keywordStart;
-        }
-        keywordStart = nextSeparator;
-    } /* end loop searching */
-    
-    if(!keywordValue) {
-      return bufLen; /* removal of non-extant keyword - no change */
-    }
-
-    /* we know there is at least one keyword. */
-    needLen = bufLen+1+keywordNameLen+1+keywordValueLen;
-    if(needLen >= bufferCapacity) {
-        *status = U_BUFFER_OVERFLOW_ERROR;
-        return needLen; /* no change */
-    }
-    
-    if(insertHere) {
-      uprv_memmove(insertHere+(1+keywordNameLen+1+keywordValueLen), insertHere, bufLen-(insertHere-buffer));
-      keywordStart = insertHere;
-    } else {
-      keywordStart = buffer+bufLen;
-      *keywordStart = ';';
-      keywordStart++;
-    }
-    uprv_strncpy(keywordStart, keywordNameBuffer, keywordNameLen);
-    keywordStart += keywordNameLen;
-    *keywordStart = '=';
-    keywordStart++;
-    uprv_strncpy(keywordStart, keywordValue, keywordValueLen); /* terminates. */
-    keywordStart+=keywordValueLen;
-    if(insertHere) {
-      *keywordStart = ';';
-      keywordStart++;
-    }
-    buffer[needLen]=0;
-    return needLen;
-}
-
-/* ### ID parsing implementation **************************************************/
-
-/*returns TRUE if a is an ID separator FALSE otherwise*/
-#define _isIDSeparator(a) (a == '_' || a == '-')
-
-#define _isPrefixLetter(a) ((a=='x')||(a=='X')||(a=='i')||(a=='I'))
-
-/*returns TRUE if one of the special prefixes is here (s=string)
-  'x-' or 'i-' */
-#define _isIDPrefix(s) (_isPrefixLetter(s[0])&&_isIDSeparator(s[1]))
-
-/* Dot terminates it because of POSIX form  where dot precedes the codepage
- * except for variant
- */
-#define _isTerminator(a)  ((a==0)||(a=='.')||(a=='@'))
-
-static char* _strnchr(const char* str, int32_t len, char c) {
-    U_ASSERT(str != 0 && len >= 0);
-    while (len-- != 0) {
-        char d = *str;
-        if (d == c) {
-            return (char*) str;
-        } else if (d == 0) {
-            break;
-        }
-        ++str;
-    }
-    return NULL;
-}
-
-/**
- * Lookup 'key' in the array 'list'.  The array 'list' should contain
- * a NULL entry, followed by more entries, and a second NULL entry.
- *
- * The 'list' param should be LANGUAGES, LANGUAGES_3, COUNTRIES, or
- * COUNTRIES_3.
- */
-static int16_t _findIndex(const char* const* list, const char* key)
-{
-    const char* const* anchor = list;
-    int32_t pass = 0;
-
-    /* Make two passes through two NULL-terminated arrays at 'list' */
-    while (pass++ < 2) {
-        while (*list) {
-            if (uprv_strcmp(key, *list) == 0) {
-                return (int16_t)(list - anchor);
-            }
-            list++;
-        }
-        ++list;     /* skip final NULL *CWB*/
-    }
-    return -1;
-}
-
-/* count the length of src while copying it to dest; return strlen(src) */
-static U_INLINE int32_t
-_copyCount(char *dest, int32_t destCapacity, const char *src) {
-    const char *anchor;
-    char c;
-
-    anchor=src;
-    for(;;) {
-        if((c=*src)==0) {
-            return (int32_t)(src-anchor);
-        }
-        if(destCapacity<=0) {
-            return (int32_t)((src-anchor)+uprv_strlen(src));
-        }
-        ++src;
-        *dest++=c;
-        --destCapacity;
-    }
-}
-
-static const char* 
-uloc_getCurrentCountryID(const char* oldID){
-    int32_t offset = _findIndex(DEPRECATED_COUNTRIES, oldID);
-    if (offset >= 0) {
-        return REPLACEMENT_COUNTRIES[offset];
-    }
-    return oldID;
-}
-static const char* 
-uloc_getCurrentLanguageID(const char* oldID){
-    int32_t offset = _findIndex(DEPRECATED_LANGUAGES, oldID);
-    if (offset >= 0) {
-        return REPLACEMENT_LANGUAGES[offset];
-    }
-    return oldID;        
-}
-/*
- * the internal functions _getLanguage(), _getCountry(), _getVariant()
- * avoid duplicating code to handle the earlier locale ID pieces
- * in the functions for the later ones by
- * setting the *pEnd pointer to where they stopped parsing
- *
- * TODO try to use this in Locale
- */
-static int32_t
-_getLanguage(const char *localeID,
-             char *language, int32_t languageCapacity,
-             const char **pEnd) {
-    int32_t i=0;
-    int32_t offset;
-    char lang[4]={ 0, 0, 0, 0 }; /* temporary buffer to hold language code for searching */
-
-    /* if it starts with i- or x- then copy that prefix */
-    if(_isIDPrefix(localeID)) {
-        if(i<languageCapacity) {
-            language[i]=(char)uprv_tolower(*localeID);
-        }
-        if(i<languageCapacity) {
-            language[i+1]='-';
-        }
-        i+=2;
-        localeID+=2;
-    }
-    
-    /* copy the language as far as possible and count its length */
-    while(!_isTerminator(*localeID) && !_isIDSeparator(*localeID)) {
-        if(i<languageCapacity) {
-            language[i]=(char)uprv_tolower(*localeID);
-        }
-        if(i<3) {
-            lang[i]=(char)uprv_tolower(*localeID);
-        }
-        i++;
-        localeID++;
-    }
-
-    if(i==3) {
-        /* convert 3 character code to 2 character code if possible *CWB*/
-        offset=_findIndex(LANGUAGES_3, lang);
-        if(offset>=0) {
-            i=_copyCount(language, languageCapacity, LANGUAGES[offset]);
-        }
-    }
-
-    if(pEnd!=NULL) {
-        *pEnd=localeID;
-    }
-    return i;
-}
-
-static int32_t
-_getScript(const char *localeID,
-            char *script, int32_t scriptCapacity,
-            const char **pEnd)
-{
-    int32_t idLen = 0;
-
-    if (pEnd != NULL) {
-        *pEnd = localeID;
-    }
-
-    /* copy the second item as far as possible and count its length */
-    while(!_isTerminator(localeID[idLen]) && !_isIDSeparator(localeID[idLen])) {
-        idLen++;
-    }
-
-    /* If it's exactly 4 characters long, then it's a script and not a country. */
-    if (idLen == 4) {
-        int32_t i;
-        if (pEnd != NULL) {
-            *pEnd = localeID+idLen;
-        }
-        if(idLen > scriptCapacity) {
-            idLen = scriptCapacity;
-        }
-        if (idLen >= 1) {
-            script[0]=(char)uprv_toupper(*(localeID++));
-        }
-        for (i = 1; i < idLen; i++) {
-            script[i]=(char)uprv_tolower(*(localeID++));
-        }
-    }
-    else {
-        idLen = 0;
-    }
-    return idLen;
-}
-
-static int32_t
-_getCountry(const char *localeID,
-            char *country, int32_t countryCapacity,
-            const char **pEnd)
-{
-    int32_t i=0;
-    char cnty[ULOC_COUNTRY_CAPACITY]={ 0, 0, 0, 0 };
-    int32_t offset;
-
-    /* copy the country as far as possible and count its length */
-    while(!_isTerminator(*localeID) && !_isIDSeparator(*localeID)) {
-        if(i<countryCapacity) {
-            country[i]=(char)uprv_toupper(*localeID);
-        }
-        if(i<(ULOC_COUNTRY_CAPACITY-1)) {   /*CWB*/
-            cnty[i]=(char)uprv_toupper(*localeID);
-        }
-        i++;
-        localeID++;
-    }
-
-    /* convert 3 character code to 2 character code if possible *CWB*/
-    if(i==3) {
-        offset=_findIndex(COUNTRIES_3, cnty);
-        if(offset>=0) {
-            i=_copyCount(country, countryCapacity, COUNTRIES[offset]);
-        }
-    }
-
-    if(pEnd!=NULL) {
-        *pEnd=localeID;
-    }
-    return i;
-}
-
-/**
- * @param needSeparator if true, then add leading '_' if any variants
- * are added to 'variant'
- */
-static int32_t
-_getVariantEx(const char *localeID,
-              char prev,
-              char *variant, int32_t variantCapacity,
-              UBool needSeparator) {
-    int32_t i=0;
-
-    /* get one or more variant tags and separate them with '_' */
-    if(_isIDSeparator(prev)) {
-        /* get a variant string after a '-' or '_' */
-        while(!_isTerminator(*localeID)) {
-            if (needSeparator) {
-                if (i<variantCapacity) {
-                    variant[i] = '_';
-                }
-                ++i;
-                needSeparator = FALSE;
-            }
-            if(i<variantCapacity) {
-                variant[i]=(char)uprv_toupper(*localeID);
-                if(variant[i]=='-') {
-                    variant[i]='_';
-                }
-            }
-            i++;
-            localeID++;
-        }
-    }
-
-    /* if there is no variant tag after a '-' or '_' then look for '@' */
-    if(i==0) {
-        if(prev=='@') {
-            /* keep localeID */
-        } else if((localeID=locale_getKeywordsStart(localeID))!=NULL) {
-            ++localeID; /* point after the '@' */
-        } else {
-            return 0;
-        }
-        while(!_isTerminator(*localeID)) {
-            if (needSeparator) {
-                if (i<variantCapacity) {
-                    variant[i] = '_';
-                }
-                ++i;
-                needSeparator = FALSE;
-            }
-            if(i<variantCapacity) {
-                variant[i]=(char)uprv_toupper(*localeID);
-                if(variant[i]=='-' || variant[i]==',') {
-                    variant[i]='_';
-                }
-            }
-            i++;
-            localeID++;
-        }
-    }
-    
-    return i;
-}
-
-static int32_t
-_getVariant(const char *localeID,
-            char prev,
-            char *variant, int32_t variantCapacity) {
-    return _getVariantEx(localeID, prev, variant, variantCapacity, FALSE);
-}
-
-/**
- * Delete ALL instances of a variant from the given list of one or
- * more variants.  Example: "FOO_EURO_BAR_EURO" => "FOO_BAR".
- * @param variants the source string of one or more variants,
- * separated by '_'.  This will be MODIFIED IN PLACE.  Not zero
- * terminated; if it is, trailing zero will NOT be maintained.
- * @param variantsLen length of variants
- * @param toDelete variant to delete, without separators, e.g.  "EURO"
- * or "PREEURO"; not zero terminated
- * @param toDeleteLen length of toDelete
- * @return number of characters deleted from variants
- */
-static int32_t
-_deleteVariant(char* variants, int32_t variantsLen,
-               const char* toDelete, int32_t toDeleteLen)
-{
-    int32_t delta = 0; /* number of chars deleted */
-    for (;;) {
-        UBool flag = FALSE;
-        if (variantsLen < toDeleteLen) {
-            return delta;
-        }
-        if (uprv_strncmp(variants, toDelete, toDeleteLen) == 0 &&
-            (variantsLen == toDeleteLen ||
-             (flag=(variants[toDeleteLen] == '_'))))
-        {
-            int32_t d = toDeleteLen + (flag?1:0);
-            variantsLen -= d;
-            delta += d;
-            if (variantsLen > 0) {
-                uprv_memmove(variants, variants+d, variantsLen);
-            }
-        } else {
-            char* p = _strnchr(variants, variantsLen, '_');
-            if (p == NULL) {
-                return delta;
-            }
-            ++p;
-            variantsLen -= (int32_t)(p - variants);
-            variants = p;
-        }
-    }
-}
-
-/* Keyword enumeration */
-
-typedef struct UKeywordsContext {
-    char* keywords;
-    char* current;
-} UKeywordsContext;
-
-static void U_CALLCONV
-uloc_kw_closeKeywords(UEnumeration *enumerator) {
-    uprv_free(((UKeywordsContext *)enumerator->context)->keywords);
-    uprv_free(enumerator->context);
-    uprv_free(enumerator);
-}
-
-static int32_t U_CALLCONV
-uloc_kw_countKeywords(UEnumeration *en, UErrorCode *status) {
-    char *kw = ((UKeywordsContext *)en->context)->keywords;
-    int32_t result = 0;
-    while(*kw) {
-        result++;
-        kw += uprv_strlen(kw)+1;
-    }
-    return result;
-}
-
-static const char* U_CALLCONV 
-uloc_kw_nextKeyword(UEnumeration* en,
-                    int32_t* resultLength,
-                    UErrorCode* status) {
-    const char* result = ((UKeywordsContext *)en->context)->current;
-    int32_t len = 0;
-    if(*result) {
-        len = (int32_t)uprv_strlen(((UKeywordsContext *)en->context)->current);
-        ((UKeywordsContext *)en->context)->current += len+1;
-    } else {
-        result = NULL;
-    }
-    if (resultLength) {
-        *resultLength = len;
-    }
-    return result;
-}
-
-static void U_CALLCONV 
-uloc_kw_resetKeywords(UEnumeration* en, 
-                      UErrorCode* status) {
-    ((UKeywordsContext *)en->context)->current = ((UKeywordsContext *)en->context)->keywords;
-}
-
-static const UEnumeration gKeywordsEnum = {
-    NULL,
-    NULL,
-    uloc_kw_closeKeywords,
-    uloc_kw_countKeywords,
-    uenum_unextDefault,
-    uloc_kw_nextKeyword,
-    uloc_kw_resetKeywords
-};
-
-U_CAPI UEnumeration* U_EXPORT2
-uloc_openKeywordList(const char *keywordList, int32_t keywordListSize, UErrorCode* status)
-{
-    UKeywordsContext *myContext = NULL;
-    UEnumeration *result = NULL;
-
-    if(U_FAILURE(*status)) {
-        return NULL;
-    }
-    result = (UEnumeration *)uprv_malloc(sizeof(UEnumeration));
-    /* Null pointer test */
-    if (result == NULL) {
-        *status = U_MEMORY_ALLOCATION_ERROR;
-        return NULL;
-    }
-    uprv_memcpy(result, &gKeywordsEnum, sizeof(UEnumeration));
-    myContext = uprv_malloc(sizeof(UKeywordsContext));
-    if (myContext == NULL) {
-        *status = U_MEMORY_ALLOCATION_ERROR;
-        uprv_free(result);
-        return NULL;
-    }
-    myContext->keywords = (char *)uprv_malloc(keywordListSize+1);
-    uprv_memcpy(myContext->keywords, keywordList, keywordListSize);
-    myContext->keywords[keywordListSize] = 0;
-    myContext->current = myContext->keywords;
-    result->context = myContext;
-    return result;
-}
-
-U_CAPI UEnumeration* U_EXPORT2
-uloc_openKeywords(const char* localeID,
-                        UErrorCode* status) 
-{
-    int32_t i=0;
-    char keywords[256];
-    int32_t keywordsCapacity = 256;
-    if(status==NULL || U_FAILURE(*status)) {
-        return 0;
-    }
-    
-    if(localeID==NULL) {
-        localeID=uloc_getDefault();
-    }
-
-    /* Skip the language */
-    _getLanguage(localeID, NULL, 0, &localeID);
-    if(_isIDSeparator(*localeID)) {
-        const char *scriptID;
-        /* Skip the script if available */
-        _getScript(localeID+1, NULL, 0, &scriptID);
-        if(scriptID != localeID+1) {
-            /* Found optional script */
-            localeID = scriptID;
-        }
-        /* Skip the Country */
-        if (_isIDSeparator(*localeID)) {
-            _getCountry(localeID+1, NULL, 0, &localeID);
-            if(_isIDSeparator(*localeID)) {
-                _getVariant(localeID+1, *localeID, NULL, 0);
-            }
-        }
-    }
-
-    /* keywords are located after '@' */
-    if((localeID = locale_getKeywordsStart(localeID)) != NULL) {
-        i=locale_getKeywords(localeID+1, '@', keywords, keywordsCapacity, NULL, 0, NULL, FALSE, status);
-    }
-
-    if(i) {
-        return uloc_openKeywordList(keywords, i, status);
-    } else {
-        return NULL;
-    }
-}
-
-
-/* bit-flags for 'options' parameter of _canonicalize */
-#define _ULOC_STRIP_KEYWORDS 0x2
-#define _ULOC_CANONICALIZE   0x1
-
-#define OPTION_SET(options, mask) ((options & mask) != 0)
-
-static const char i_default[] = {'i', '-', 'd', 'e', 'f', 'a', 'u', 'l', 't'};
-#define I_DEFAULT_LENGTH (sizeof i_default / sizeof i_default[0])
-
-/**
- * Canonicalize the given localeID, to level 1 or to level 2,
- * depending on the options.  To specify level 1, pass in options=0.
- * To specify level 2, pass in options=_ULOC_CANONICALIZE.
- *
- * This is the code underlying uloc_getName and uloc_canonicalize.
- */
-static int32_t
-_canonicalize(const char* localeID,
-              char* result,
-              int32_t resultCapacity,
-              uint32_t options,
-              UErrorCode* err) {
-    int32_t j, len, fieldCount=0, scriptSize=0, variantSize=0, nameCapacity;
-    char localeBuffer[ULOC_FULLNAME_CAPACITY];
-    const char* origLocaleID;
-    const char* keywordAssign = NULL;
-    const char* separatorIndicator = NULL;
-    const char* addKeyword = NULL;
-    const char* addValue = NULL;
-    char* name;
-    char* variant = NULL; /* pointer into name, or NULL */
-
-    if (U_FAILURE(*err)) {
-        return 0;
-    }
-    
-    if (localeID==NULL) {
-        localeID=uloc_getDefault();
-    }
-    origLocaleID=localeID;
-
-    /* if we are doing a full canonicalization, then put results in
-       localeBuffer, if necessary; otherwise send them to result. */
-    if (OPTION_SET(options, _ULOC_CANONICALIZE) &&
-        (result == NULL || resultCapacity <  sizeof(localeBuffer))) {
-        name = localeBuffer;
-        nameCapacity = sizeof(localeBuffer);
-    } else {
-        name = result;
-        nameCapacity = resultCapacity;
-    }
-
-    /* get all pieces, one after another, and separate with '_' */
-    len=_getLanguage(localeID, name, nameCapacity, &localeID);
-
-    if(len == I_DEFAULT_LENGTH && uprv_strncmp(origLocaleID, i_default, len) == 0) {
-        const char *d = uloc_getDefault();
-        
-        len = uprv_strlen(d);
-
-        if (name != NULL) {
-            uprv_strncpy(name, d, len);
-        }
-    } else if(_isIDSeparator(*localeID)) {
-        const char *scriptID;
-
-        ++fieldCount;
-        if(len<nameCapacity) {
-            name[len]='_';
-        }
-        ++len;
-
-        scriptSize=_getScript(localeID+1, name+len, nameCapacity-len, &scriptID);
-        if(scriptSize > 0) {
-            /* Found optional script */
-            localeID = scriptID;
-            ++fieldCount;
-            len+=scriptSize;
-            if (_isIDSeparator(*localeID)) {
-                /* If there is something else, then we add the _ */
-                if(len<nameCapacity) {
-                    name[len]='_';
-                }
-                ++len;
-            }
-        }
-
-        if (_isIDSeparator(*localeID)) {
-            len+=_getCountry(localeID+1, name+len, nameCapacity-len, &localeID);
-            if(_isIDSeparator(*localeID)) {
-                ++fieldCount;
-                if(len<nameCapacity) {
-                    name[len]='_';
-                }
-                ++len;
-                variantSize = _getVariant(localeID+1, *localeID, name+len, nameCapacity-len);
-                if (variantSize > 0) {
-                    variant = name+len;
-                    len += variantSize;
-                    localeID += variantSize + 1; /* skip '_' and variant */
-                }
-            }
-        }
-    }
-
-    /* Copy POSIX-style charset specifier, if any [mr.utf8] */
-    if (!OPTION_SET(options, _ULOC_CANONICALIZE) && *localeID == '.') {
-        UBool done = FALSE;
-        do {
-            char c = *localeID;
-            switch (c) {
-            case 0:
-            case '@':
-                done = TRUE;
-                break;
-            default:
-                if (len<nameCapacity) {
-                    name[len] = c;
-                }
-                ++len;
-                ++localeID;
-                break;
-            }
-        } while (!done);
-    }
-
-    /* Scan ahead to next '@' and determine if it is followed by '=' and/or ';'
-       After this, localeID either points to '@' or is NULL */
-    if ((localeID=locale_getKeywordsStart(localeID))!=NULL) {
-        keywordAssign = uprv_strchr(localeID, '=');
-        separatorIndicator = uprv_strchr(localeID, ';');
-    }
-
-    /* Copy POSIX-style variant, if any [mr@FOO] */
-    if (!OPTION_SET(options, _ULOC_CANONICALIZE) &&
-        localeID != NULL && keywordAssign == NULL) {
-        for (;;) {
-            char c = *localeID;
-            if (c == 0) {
-                break;
-            }
-            if (len<nameCapacity) {
-                name[len] = c;
-            }
-            ++len;
-            ++localeID;
-        }
-    }
-
-    if (OPTION_SET(options, _ULOC_CANONICALIZE)) {
-        /* Handle @FOO variant if @ is present and not followed by = */
-        if (localeID!=NULL && keywordAssign==NULL) {
-            int32_t posixVariantSize;
-            /* Add missing '_' if needed */
-            if (fieldCount < 2 || (fieldCount < 3 && scriptSize > 0)) {
-                do {
-                    if(len<nameCapacity) {
-                        name[len]='_';
-                    }
-                    ++len;
-                    ++fieldCount;
-                } while(fieldCount<2);
-            }
-            posixVariantSize = _getVariantEx(localeID+1, '@', name+len, nameCapacity-len,
-                                             (UBool)(variantSize > 0));
-            if (posixVariantSize > 0) {
-                if (variant == NULL) {
-                    variant = name+len;
-                }
-                len += posixVariantSize;
-                variantSize += posixVariantSize;
-            }
-        }
-
-        /* Handle generic variants first */
-        if (variant) {
-            for (j=0; j<(int32_t)(sizeof(VARIANT_MAP)/sizeof(VARIANT_MAP[0])); j++) {
-                const char* variantToCompare = VARIANT_MAP[j].variant;
-                int32_t n = (int32_t)uprv_strlen(variantToCompare);
-                int32_t variantLen = _deleteVariant(variant, uprv_min(variantSize, (nameCapacity-len)), variantToCompare, n);
-                len -= variantLen;
-                if (variantLen > 0) {
-                    if (len > 0 && name[len-1] == '_') { /* delete trailing '_' */
-                        --len;
-                    }
-                    addKeyword = VARIANT_MAP[j].keyword;
-                    addValue = VARIANT_MAP[j].value;
-                    break;
-                }
-            }
-            if (len > 0 && len <= nameCapacity && name[len-1] == '_') { /* delete trailing '_' */
-                --len;
-            }
-        }
-
-        /* Look up the ID in the canonicalization map */
-        for (j=0; j<(int32_t)(sizeof(CANONICALIZE_MAP)/sizeof(CANONICALIZE_MAP[0])); j++) {
-            const char* id = CANONICALIZE_MAP[j].id;
-            int32_t n = (int32_t)uprv_strlen(id);
-            if (len == n && uprv_strncmp(name, id, n) == 0) {
-                if (n == 0 && localeID != NULL) {
-                    break; /* Don't remap "" if keywords present */
-                }
-                len = _copyCount(name, nameCapacity, CANONICALIZE_MAP[j].canonicalID);
-                if (CANONICALIZE_MAP[j].keyword) {
-                    addKeyword = CANONICALIZE_MAP[j].keyword;
-                    addValue = CANONICALIZE_MAP[j].value;
-                }
-                break;
-            }
-        }
-    }
-
-    if (!OPTION_SET(options, _ULOC_STRIP_KEYWORDS)) {
-        if (localeID!=NULL && keywordAssign!=NULL &&
-            (!separatorIndicator || separatorIndicator > keywordAssign)) {
-            if(len<nameCapacity) {
-                name[len]='@';
-            }
-            ++len;
-            ++fieldCount;
-            len += _getKeywords(localeID+1, '@', name+len, nameCapacity-len, NULL, 0, NULL, TRUE,
-                                addKeyword, addValue, err);
-        } else if (addKeyword != NULL) {
-            U_ASSERT(addValue != NULL);
-            /* inelegant but works -- later make _getKeywords do this? */
-            len += _copyCount(name+len, nameCapacity-len, "@");
-            len += _copyCount(name+len, nameCapacity-len, addKeyword);
-            len += _copyCount(name+len, nameCapacity-len, "=");
-            len += _copyCount(name+len, nameCapacity-len, addValue);
-        }
-    }
-
-    if (U_SUCCESS(*err) && result != NULL && name == localeBuffer) {
-        uprv_strncpy(result, localeBuffer, (len > resultCapacity) ? resultCapacity : len);
-    }
-
-    return u_terminateChars(result, resultCapacity, len, err);
-}
-
-/* ### ID parsing API **************************************************/
-
-U_CAPI int32_t  U_EXPORT2
-uloc_getParent(const char*    localeID,
-               char* parent,
-               int32_t parentCapacity,
-               UErrorCode* err)
-{
-    const char *lastUnderscore;
-    int32_t i;
-    
-    if (U_FAILURE(*err))
-        return 0;
-    
-    if (localeID == NULL)
-        localeID = uloc_getDefault();
-
-    lastUnderscore=uprv_strrchr(localeID, '_');
-    if(lastUnderscore!=NULL) {
-        i=(int32_t)(lastUnderscore-localeID);
-    } else {
-        i=0;
-    }
-
-    if(i>0 && parent != localeID) {
-        uprv_memcpy(parent, localeID, uprv_min(i, parentCapacity));
-    }
-    return u_terminateChars(parent, parentCapacity, i, err);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getLanguage(const char*    localeID,
-         char* language,
-         int32_t languageCapacity,
-         UErrorCode* err)
-{
-    /* uloc_getLanguage will return a 2 character iso-639 code if one exists. *CWB*/
-    int32_t i=0;
-
-    if (err==NULL || U_FAILURE(*err)) {
-        return 0;
-    }
-    
-    if(localeID==NULL) {
-        localeID=uloc_getDefault();
-    }
-
-    i=_getLanguage(localeID, language, languageCapacity, NULL);
-    return u_terminateChars(language, languageCapacity, i, err);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getScript(const char*    localeID,
-         char* script,
-         int32_t scriptCapacity,
-         UErrorCode* err)
-{
-    int32_t i=0;
-
-    if(err==NULL || U_FAILURE(*err)) {
-        return 0;
-    }
-
-    if(localeID==NULL) {
-        localeID=uloc_getDefault();
-    }
-
-    /* skip the language */
-    _getLanguage(localeID, NULL, 0, &localeID);
-    if(_isIDSeparator(*localeID)) {
-        i=_getScript(localeID+1, script, scriptCapacity, NULL);
-    }
-    return u_terminateChars(script, scriptCapacity, i, err);
-}
-
-U_CAPI int32_t  U_EXPORT2
-uloc_getCountry(const char* localeID,
-            char* country,
-            int32_t countryCapacity,
-            UErrorCode* err) 
-{
-    int32_t i=0;
-
-    if(err==NULL || U_FAILURE(*err)) {
-        return 0;
-    }
-
-    if(localeID==NULL) {
-        localeID=uloc_getDefault();
-    }
-
-    /* Skip the language */
-    _getLanguage(localeID, NULL, 0, &localeID);
-    if(_isIDSeparator(*localeID)) {
-        const char *scriptID;
-        /* Skip the script if available */
-        _getScript(localeID+1, NULL, 0, &scriptID);
-        if(scriptID != localeID+1) {
-            /* Found optional script */
-            localeID = scriptID;
-        }
-        if(_isIDSeparator(*localeID)) {
-            i=_getCountry(localeID+1, country, countryCapacity, NULL);
-        }
-    }
-    return u_terminateChars(country, countryCapacity, i, err);
-}
-
-U_CAPI int32_t  U_EXPORT2
-uloc_getVariant(const char* localeID,
-                char* variant,
-                int32_t variantCapacity,
-                UErrorCode* err) 
-{
-    int32_t i=0;
-    
-    if(err==NULL || U_FAILURE(*err)) {
-        return 0;
-    }
-    
-    if(localeID==NULL) {
-        localeID=uloc_getDefault();
-    }
-    
-    /* Skip the language */
-    _getLanguage(localeID, NULL, 0, &localeID);
-    if(_isIDSeparator(*localeID)) {
-        const char *scriptID;
-        /* Skip the script if available */
-        _getScript(localeID+1, NULL, 0, &scriptID);
-        if(scriptID != localeID+1) {
-            /* Found optional script */
-            localeID = scriptID;
-        }
-        /* Skip the Country */
-        if (_isIDSeparator(*localeID)) {
-            _getCountry(localeID+1, NULL, 0, &localeID);
-            if(_isIDSeparator(*localeID)) {
-                i=_getVariant(localeID+1, *localeID, variant, variantCapacity);
-            }
-        }
-    }
-    
-    /* removed by weiv. We don't want to handle POSIX variants anymore. Use canonicalization function */
-    /* if we do not have a variant tag yet then try a POSIX variant after '@' */
-/*
-    if(!haveVariant && (localeID=uprv_strrchr(localeID, '@'))!=NULL) {
-        i=_getVariant(localeID+1, '@', variant, variantCapacity);
-    }
-*/
-    return u_terminateChars(variant, variantCapacity, i, err);
-}
-
-U_CAPI int32_t  U_EXPORT2
-uloc_getName(const char* localeID,
-             char* name,
-             int32_t nameCapacity,
-             UErrorCode* err)  
-{
-    return _canonicalize(localeID, name, nameCapacity, 0, err);
-}
-
-U_CAPI int32_t  U_EXPORT2
-uloc_getBaseName(const char* localeID,
-                 char* name,
-                 int32_t nameCapacity,
-                 UErrorCode* err)  
-{
-    return _canonicalize(localeID, name, nameCapacity, _ULOC_STRIP_KEYWORDS, err);
-}
-
-U_CAPI int32_t  U_EXPORT2
-uloc_canonicalize(const char* localeID,
-                  char* name,
-                  int32_t nameCapacity,
-                  UErrorCode* err)  
-{
-    return _canonicalize(localeID, name, nameCapacity, _ULOC_CANONICALIZE, err);
-}
-  
-U_CAPI const char*  U_EXPORT2
-uloc_getISO3Language(const char* localeID) 
-{
-    int16_t offset;
-    char lang[ULOC_LANG_CAPACITY];
-    UErrorCode err = U_ZERO_ERROR;
-    
-    if (localeID == NULL)
-    {
-        localeID = uloc_getDefault();
-    }
-    uloc_getLanguage(localeID, lang, ULOC_LANG_CAPACITY, &err);
-    if (U_FAILURE(err))
-        return "";
-    offset = _findIndex(LANGUAGES, lang);
-    if (offset < 0)
-        return "";
-    return LANGUAGES_3[offset];
-}
-
-U_CAPI const char*  U_EXPORT2
-uloc_getISO3Country(const char* localeID) 
-{
-    int16_t offset;
-    char cntry[ULOC_LANG_CAPACITY];
-    UErrorCode err = U_ZERO_ERROR;
-    
-    if (localeID == NULL)
-    {
-        localeID = uloc_getDefault();
-    }
-    uloc_getCountry(localeID, cntry, ULOC_LANG_CAPACITY, &err);
-    if (U_FAILURE(err))
-        return "";
-    offset = _findIndex(COUNTRIES, cntry);
-    if (offset < 0)
-        return "";
-    
-    return COUNTRIES_3[offset];
-}
-
-U_CAPI uint32_t  U_EXPORT2
-uloc_getLCID(const char* localeID) 
-{
-    UErrorCode status = U_ZERO_ERROR;
-    char       langID[ULOC_FULLNAME_CAPACITY];
-
-    uloc_getLanguage(localeID, langID, sizeof(langID), &status);
-    if (U_FAILURE(status)) {
-        return 0;
-    }
-
-    return uprv_convertToLCID(langID, localeID, &status);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getLocaleForLCID(uint32_t hostid, char *locale, int32_t localeCapacity,
-                UErrorCode *status)
-{
-    int32_t length;
-    const char *posix = uprv_convertToPosix(hostid, status);
-    if (U_FAILURE(*status) || posix == NULL) {
-        return 0;
-    }
-    length = (int32_t)uprv_strlen(posix);
-    if (length+1 > localeCapacity) {
-        *status = U_BUFFER_OVERFLOW_ERROR;
-    }
-    else {
-        uprv_strcpy(locale, posix);
-    }
-    return length;
-}
-
-/* ### Default locale **************************************************/
-
-U_CAPI const char*  U_EXPORT2
-uloc_getDefault()
-{
-    return locale_get_default();
-}
-
-U_CAPI void  U_EXPORT2
-uloc_setDefault(const char*   newDefaultLocale,
-             UErrorCode* err) 
-{
-    if (U_FAILURE(*err))
-        return;
-    /* the error code isn't currently used for anything by this function*/
-    
-    /* propagate change to C++ */
-    locale_set_default(newDefaultLocale);
-}
-
-/* ### Display name **************************************************/
-
-/*
- * Lookup a resource bundle table item with fallback on the table level.
- * Regular resource bundle lookups perform fallback to parent locale bundles
- * and eventually the root bundle, but only for top-level items.
- * This function takes the name of a top-level table and of an item in that table
- * and performs a lookup of both, falling back until a bundle contains a table
- * with this item.
- *
- * Note: Only the opening of entire bundles falls back through the default locale
- * before root. Once a bundle is open, item lookups do not go through the
- * default locale because that would result in a mix of languages that is
- * unpredictable to the programmer and most likely useless.
- */
-static const UChar *
-_res_getTableStringWithFallback(const char *path, const char *locale,
-                              const char *tableKey, const char *subTableKey,
-                              const char *itemKey,
-                              int32_t *pLength,
-                              UErrorCode *pErrorCode)
-{
-/*    char localeBuffer[ULOC_FULLNAME_CAPACITY*4];*/
-    UResourceBundle *rb=NULL, table, subTable;
-    const UChar *item=NULL;
-    UErrorCode errorCode;
-    char explicitFallbackName[ULOC_FULLNAME_CAPACITY] = {0};
-
-    /*
-     * open the bundle for the current locale
-     * this falls back through the locale's chain to root
-     */
-    errorCode=U_ZERO_ERROR;
-    rb=ures_open(path, locale, &errorCode);
-    if(U_FAILURE(errorCode)) {
-        /* total failure, not even root could be opened */
-        *pErrorCode=errorCode;
-        return NULL;
-    } else if(errorCode==U_USING_DEFAULT_WARNING ||
-                (errorCode==U_USING_FALLBACK_WARNING && *pErrorCode!=U_USING_DEFAULT_WARNING)
-    ) {
-        /* set the "strongest" error code (success->fallback->default->failure) */
-        *pErrorCode=errorCode;
-    }
-
-    for(;;){
-        ures_initStackObject(&table);
-        ures_initStackObject(&subTable);
-        ures_getByKeyWithFallback(rb, tableKey, &table, &errorCode);
-        if (subTableKey != NULL) {
-            /*
-            ures_getByKeyWithFallback(&table,subTableKey, &subTable, &errorCode);
-            item = ures_getStringByKeyWithFallback(&subTable, itemKey, pLength, &errorCode);
-            if(U_FAILURE(errorCode)){
-                *pErrorCode = errorCode;
-            }
-            
-            break;*/
-            
-            ures_getByKeyWithFallback(&table,subTableKey, &table, &errorCode);
-        }
-        if(U_SUCCESS(errorCode)){
-            item = ures_getStringByKeyWithFallback(&table, itemKey, pLength, &errorCode);
-            if(U_FAILURE(errorCode)){
-                const char* replacement = NULL;
-                *pErrorCode = errorCode; /*save the errorCode*/
-                errorCode = U_ZERO_ERROR;
-                /* may be a deprecated code */
-                if(uprv_strcmp(tableKey, "Countries")==0){
-                    replacement =  uloc_getCurrentCountryID(itemKey);
-                }else if(uprv_strcmp(tableKey, "Languages")==0){
-                    replacement =  uloc_getCurrentLanguageID(itemKey);
-                }
-                /*pointer comparison is ok since uloc_getCurrentCountryID & uloc_getCurrentLanguageID return the key itself is replacement is not found*/
-                if(replacement!=NULL && itemKey != replacement){
-                    item = ures_getStringByKeyWithFallback(&table, replacement, pLength, &errorCode);
-                    if(U_SUCCESS(errorCode)){
-                        *pErrorCode = errorCode;
-                        break;
-                    }
-                }
-            }else{
-                break;
-            }
-        }
-        
-        if(U_FAILURE(errorCode)){    
-
-            /* still can't figure out ?.. try the fallback mechanism */
-            int32_t len = 0;
-            const UChar* fallbackLocale =  NULL;
-            *pErrorCode = errorCode;
-            errorCode = U_ZERO_ERROR;
-
-            fallbackLocale = ures_getStringByKeyWithFallback(&table, "Fallback", &len, &errorCode);
-            if(U_FAILURE(errorCode)){
-               *pErrorCode = errorCode;
-                break;
-            }
-            
-            u_UCharsToChars(fallbackLocale, explicitFallbackName, len);
-            
-            /* guard against recursive fallback */
-            if(uprv_strcmp(explicitFallbackName, locale)==0){
-                *pErrorCode = U_INTERNAL_PROGRAM_ERROR;
-                break;
-            }
-            ures_close(rb);
-            rb = ures_open(NULL, explicitFallbackName, &errorCode);
-            if(U_FAILURE(errorCode)){
-                *pErrorCode = errorCode;
-                break;
-            }
-            /* succeeded in opening the fallback bundle .. continue and try to fetch the item */
-        }else{
-            break;
-        }
-    }
-    /* done with the locale string - ready to close table and rb */
-    ures_close(&subTable);
-    ures_close(&table);
-    ures_close(rb);
-    return item;
-}
-
-static int32_t
-_getStringOrCopyKey(const char *path, const char *locale,
-                    const char *tableKey, 
-                    const char* subTableKey,
-                    const char *itemKey,
-                    const char *substitute,
-                    UChar *dest, int32_t destCapacity,
-                    UErrorCode *pErrorCode) {
-    const UChar *s = NULL;
-    int32_t length = 0;
-
-    if(itemKey==NULL) {
-        /* top-level item: normal resource bundle access */
-        UResourceBundle *rb;
-
-        rb=ures_open(path, locale, pErrorCode);
-        if(U_SUCCESS(*pErrorCode)) {
-            s=ures_getStringByKey(rb, tableKey, &length, pErrorCode);
-            /* see comment about closing rb near "return item;" in _res_getTableStringWithFallback() */
-            ures_close(rb);
-        }
-    } else {
-        /* second-level item, use special fallback */
-        s=_res_getTableStringWithFallback(path, locale,
-                                           tableKey, 
-                                           subTableKey,
-                                           itemKey,
-                                           &length,
-                                           pErrorCode);
-    }
-    if(U_SUCCESS(*pErrorCode)) {
-        int32_t copyLength=uprv_min(length, destCapacity);
-        if(copyLength>0 && s != NULL) {
-            u_memcpy(dest, s, copyLength);
-        }
-    } else {
-        /* no string from a resource bundle: convert the substitute */
-        length=(int32_t)uprv_strlen(substitute);
-        u_charsToUChars(substitute, dest, uprv_min(length, destCapacity));
-        *pErrorCode=U_USING_DEFAULT_WARNING;
-    }
-
-    return u_terminateUChars(dest, destCapacity, length, pErrorCode);
-}
-
-static int32_t
-_getDisplayNameForComponent(const char *locale,
-                            const char *displayLocale,
-                            UChar *dest, int32_t destCapacity,
-                            int32_t (*getter)(const char *, char *, int32_t, UErrorCode *),
-                            const char *tag,
-                            UErrorCode *pErrorCode) {
-    char localeBuffer[ULOC_FULLNAME_CAPACITY*4];
-    int32_t length;
-    UErrorCode localStatus;
-
-    /* argument checking */
-    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
-        return 0;
-    }
-
-    if(destCapacity<0 || (destCapacity>0 && dest==NULL)) {
-        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
-        return 0;
-    }
-
-    localStatus = U_ZERO_ERROR;
-    length=(*getter)(locale, localeBuffer, sizeof(localeBuffer), &localStatus);
-    if(U_FAILURE(localStatus) || localStatus==U_STRING_NOT_TERMINATED_WARNING) {
-        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
-        return 0;
-    }
-    if(length==0) {
-        return u_terminateUChars(dest, destCapacity, 0, pErrorCode);
-    }
-
-    return _getStringOrCopyKey(NULL, displayLocale,
-                               tag, NULL, localeBuffer,
-                               localeBuffer, 
-                               dest, destCapacity,
-                               pErrorCode);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getDisplayLanguage(const char *locale,
-                        const char *displayLocale,
-                        UChar *dest, int32_t destCapacity,
-                        UErrorCode *pErrorCode) {
-    return _getDisplayNameForComponent(locale, displayLocale, dest, destCapacity,
-                uloc_getLanguage, _kLanguages, pErrorCode);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getDisplayScript(const char* locale,
-                      const char* displayLocale,
-                      UChar *dest, int32_t destCapacity,
-                      UErrorCode *pErrorCode)
-{
-    return _getDisplayNameForComponent(locale, displayLocale, dest, destCapacity,
-                uloc_getScript, _kScripts, pErrorCode);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getDisplayCountry(const char *locale,
-                       const char *displayLocale,
-                       UChar *dest, int32_t destCapacity,
-                       UErrorCode *pErrorCode) {
-    return _getDisplayNameForComponent(locale, displayLocale, dest, destCapacity,
-                uloc_getCountry, _kCountries, pErrorCode);
-}
-
-/*
- * TODO separate variant1_variant2_variant3...
- * by getting each tag's display string and concatenating them with ", "
- * in between - similar to uloc_getDisplayName()
- */
-U_CAPI int32_t U_EXPORT2
-uloc_getDisplayVariant(const char *locale,
-                       const char *displayLocale,
-                       UChar *dest, int32_t destCapacity,
-                       UErrorCode *pErrorCode) {
-    return _getDisplayNameForComponent(locale, displayLocale, dest, destCapacity,
-                uloc_getVariant, _kVariants, pErrorCode);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getDisplayName(const char *locale,
-                    const char *displayLocale,
-                    UChar *dest, int32_t destCapacity,
-                    UErrorCode *pErrorCode)
-{
-    int32_t length, length2, length3 = 0;
-    UBool hasLanguage, hasScript, hasCountry, hasVariant, hasKeywords;
-    UEnumeration* keywordEnum = NULL;
-    int32_t keywordCount = 0;
-    const char *keyword = NULL;
-    int32_t keywordLen = 0;
-    char keywordValue[256];
-    int32_t keywordValueLen = 0;
-
-    /* argument checking */
-    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
-        return 0;
-    }
-
-    if(destCapacity<0 || (destCapacity>0 && dest==NULL)) {
-        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
-        return 0;
-    }
-
-    /*
-     * if there is a language, then write "language (country, variant)"
-     * otherwise write "country, variant"
-     */
-
-    /* write the language */
-    length=uloc_getDisplayLanguage(locale, displayLocale,
-                                   dest, destCapacity,
-                                   pErrorCode);
-    hasLanguage= length>0;
-
-    if(hasLanguage) {
-        /* append " (" */
-        if(length<destCapacity) {
-            dest[length]=0x20;
-        }
-        ++length;
-        if(length<destCapacity) {
-            dest[length]=0x28;
-        }
-        ++length;
-    }
-
-    if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
-        /* keep preflighting */
-        *pErrorCode=U_ZERO_ERROR;
-    }
-
-    /* append the script */
-    if(length<destCapacity) {
-        length2=uloc_getDisplayScript(locale, displayLocale,
-                                       dest+length, destCapacity-length,
-                                       pErrorCode);
-    } else {
-        length2=uloc_getDisplayScript(locale, displayLocale,
-                                       NULL, 0,
-                                       pErrorCode);
-    }
-    hasScript= length2>0;
-    length+=length2;
-
-    if(hasScript) {
-        /* append ", " */
-        if(length<destCapacity) {
-            dest[length]=0x2c;
-        }
-        ++length;
-        if(length<destCapacity) {
-            dest[length]=0x20;
-        }
-        ++length;
-    }
-
-    if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
-        /* keep preflighting */
-        *pErrorCode=U_ZERO_ERROR;
-    }
-
-    /* append the country */
-    if(length<destCapacity) {
-        length2=uloc_getDisplayCountry(locale, displayLocale,
-                                       dest+length, destCapacity-length,
-                                       pErrorCode);
-    } else {
-        length2=uloc_getDisplayCountry(locale, displayLocale,
-                                       NULL, 0,
-                                       pErrorCode);
-    }
-    hasCountry= length2>0;
-    length+=length2;
-
-    if(hasCountry) {
-        /* append ", " */
-        if(length<destCapacity) {
-            dest[length]=0x2c;
-        }
-        ++length;
-        if(length<destCapacity) {
-            dest[length]=0x20;
-        }
-        ++length;
-    }
-
-    if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
-        /* keep preflighting */
-        *pErrorCode=U_ZERO_ERROR;
-    }
-
-    /* append the variant */
-    if(length<destCapacity) {
-        length2=uloc_getDisplayVariant(locale, displayLocale,
-                                       dest+length, destCapacity-length,
-                                       pErrorCode);
-    } else {
-        length2=uloc_getDisplayVariant(locale, displayLocale,
-                                       NULL, 0,
-                                       pErrorCode);
-    }
-    hasVariant= length2>0;
-    length+=length2;
-
-    if(hasVariant) {
-        /* append ", " */
-        if(length<destCapacity) {
-            dest[length]=0x2c;
-        }
-        ++length;
-        if(length<destCapacity) {
-            dest[length]=0x20;
-        }
-        ++length;
-    }
-
-    keywordEnum = uloc_openKeywords(locale, pErrorCode);
-    
-    for(keywordCount = uenum_count(keywordEnum, pErrorCode); keywordCount > 0 ; keywordCount--){
-          if(U_FAILURE(*pErrorCode)){
-              break;
-          }
-          /* the uenum_next returns NUL terminated string */
-          keyword = uenum_next(keywordEnum, &keywordLen, pErrorCode);
-          if(length + length3 < destCapacity) {
-            length3 += uloc_getDisplayKeyword(keyword, displayLocale, dest+length+length3, destCapacity-length-length3, pErrorCode);
-          } else {
-            length3 += uloc_getDisplayKeyword(keyword, displayLocale, NULL, 0, pErrorCode);
-          }
-          if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
-              /* keep preflighting */
-              *pErrorCode=U_ZERO_ERROR;
-          }
-          keywordValueLen = uloc_getKeywordValue(locale, keyword, keywordValue, 256, pErrorCode);
-          if(keywordValueLen) {
-            if(length + length3 < destCapacity) {
-              dest[length + length3] = 0x3D;
-            }
-            length3++;
-            if(length + length3 < destCapacity) {
-              length3 += uloc_getDisplayKeywordValue(locale, keyword, displayLocale, dest+length+length3, destCapacity-length-length3, pErrorCode);
-            } else {
-              length3 += uloc_getDisplayKeywordValue(locale, keyword, displayLocale, NULL, 0, pErrorCode);
-            }
-            if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
-                /* keep preflighting */
-                *pErrorCode=U_ZERO_ERROR;
-            }
-          }
-          if(keywordCount > 1) {
-            if(length + length3 + 1 < destCapacity && keywordCount) {
-              dest[length + length3]=0x2c;
-              dest[length + length3+1]=0x20;
-            }
-            length3++; /* ',' */
-            length3++; /* ' ' */ 
-          }
-    }
-    uenum_close(keywordEnum);
-
-    hasKeywords = length3 > 0;
-    length += length3;
-
-
-
-    if ((hasScript && !hasCountry)
-        || ((hasScript || hasCountry) && !hasVariant && !hasKeywords)
-        || ((hasScript || hasCountry || hasVariant) && !hasKeywords)
-        || (hasLanguage && !hasScript && !hasCountry && !hasVariant && !hasKeywords))
-    {
-        /* remove ", " or " (" */
-        length-=2;
-    }
-
-    if (hasLanguage && (hasScript || hasCountry || hasVariant || hasKeywords)) {
-        /* append ")" */
-        if(length<destCapacity) {
-            dest[length]=0x29;
-        }
-        ++length;
-    }
-
-    if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
-        /* keep preflighting */
-        *pErrorCode=U_ZERO_ERROR;
-    }
-
-    return u_terminateUChars(dest, destCapacity, length, pErrorCode);
-}
-
-U_CAPI int32_t U_EXPORT2
-uloc_getDisplayKeyword(const char* keyword,
-                       const char* displayLocale,
-                       UChar* dest,
-                       int32_t destCapacity,
-                       UErrorCode* status){
-
-    /* argument checking */
-    if(status==NULL || U_FAILURE(*status)) {
-        return 0;
-    }
-
-    if(destCapacity<0 || (destCapacity>0 && dest==NULL)) {
-        *status=U_ILLEGAL_ARGUMENT_ERROR;
-        return 0;
-    }
-
-
-    /* pass itemKey=NULL to look for a top-level item */
-    return _getStringOrCopyKey(NULL, displayLocale,
-                               _kKeys, NULL, 
-                               keyword, 
-                               keyword,      
-                               dest, destCapacity,
-                               status);
-
-}
-
-
-#define UCURRENCY_DISPLAY_NAME_INDEX 1
-
-U_CAPI int32_t U_EXPORT2
-uloc_getDisplayKeywordValue(   const char* locale,
-                               const char* keyword,
-                               const char* displayLocale,
-                               UChar* dest,
-                               int32_t destCapacity,
-                               UErrorCode* status){
-
-
-    char keywordValue[ULOC_FULLNAME_CAPACITY*4];
-    int32_t capacity = ULOC_FULLNAME_CAPACITY*4;
-    int32_t keywordValueLen =0;
-
-    /* argument checking */
-    if(status==NULL || U_FAILURE(*status)) {
-        return 0;
-    }
-
-    if(destCapacity<0 || (destCapacity>0 && dest==NULL)) {
-        *status=U_ILLEGAL_ARGUMENT_ERROR;
-        return 0;
-    }
-
-    /* get the keyword value */
-    keywordValue[0]=0;
-    keywordValueLen = uloc_getKeywordValue(locale, keyword, keywordValue, capacity, status);
-
-    /* 
-     * if the keyword is equal to currency .. then to get the display name 
-     * we need to do the fallback ourselves
-     */
-    if(uprv_stricmp(keyword, _kCurrency)==0){
-
-        int32_t dispNameLen = 0;
-        const UChar *dispName = NULL;
-        
-        UResourceBundle *bundle     = ures_open(NULL, displayLocale, status);
-        UResourceBundle *currencies = ures_getByKey(bundle, _kCurrencies, NULL, status);
-        UResourceBundle *currency   = ures_getByKeyWithFallback(currencies, keywordValue, NULL, status);
-        
-        dispName = ures_getStringByIndex(currency, UCURRENCY_DISPLAY_NAME_INDEX, &dispNameLen, status);
-        
-        /*close the bundles */
-        ures_close(currency);
-        ures_close(currencies);
-        ures_close(bundle);
-        
-        if(U_FAILURE(*status)){
-            if(*status == U_MISSING_RESOURCE_ERROR){
-                /* we just want to write the value over if nothing is available */
-                *status = U_USING_DEFAULT_WARNING;
-            }else{
-                return 0;
-            }
-        }
-
-        /* now copy the dispName over if not NULL */
-        if(dispName != NULL){
-            if(dispNameLen <= destCapacity){
-                uprv_memcpy(dest, dispName, dispNameLen * U_SIZEOF_UCHAR);
-                return u_terminateUChars(dest, destCapacity, dispNameLen, status);
-            }else{
-                *status = U_BUFFER_OVERFLOW_ERROR;
-                return dispNameLen;
-            }
-        }else{
-            /* we have not found the display name for the value .. just copy over */
-            if(keywordValueLen <= destCapacity){
-                u_charsToUChars(keywordValue, dest, keywordValueLen);
-                return u_terminateUChars(dest, destCapacity, keywordValueLen, status);
-            }else{
-                 *status = U_BUFFER_OVERFLOW_ERROR;
-                return keywordValueLen;
-            }
-        }
-
-        
-    }else{
-
-        return _getStringOrCopyKey(NULL, displayLocale,
-                                   _kTypes, keyword, 
-                                   keywordValue,
-                                   keywordValue,
-                                   dest, destCapacity,
-                                   status);
-    }
-}
-
-/* ### Get available **************************************************/
-
-static UBool U_CALLCONV uloc_cleanup(void) {
-    char ** temp;
-
-    if (_installedLocales) {
-        temp = _installedLocales;
-        _installedLocales = NULL;
-
-        _installedLocalesCount = 0;
-
-        uprv_free(temp);
-    }
-    return TRUE;
-}
-
-static void _load_installedLocales()
-{
-    UBool   localesLoaded;
-
-    UMTX_CHECK(NULL, _installedLocales != NULL, localesLoaded);
-    
-    if (localesLoaded == FALSE) {
-        UResourceBundle *index = NULL;
-        UResourceBundle installed;
-        UErrorCode status = U_ZERO_ERROR;
-        char ** temp;
-        int32_t i = 0;
-        int32_t localeCount;
-        
-        ures_initStackObject(&installed);
-        index = ures_openDirect(NULL, _kIndexLocaleName, &status);
-        ures_getByKey(index, _kIndexTag, &installed, &status);
-        
-        if(U_SUCCESS(status)) {
-            localeCount = ures_getSize(&installed);
-            temp = (char **) uprv_malloc(sizeof(char*) * (localeCount+1));
-            /* Check for null pointer */
-            if (temp != NULL) {
-                ures_resetIterator(&installed);
-                while(ures_hasNext(&installed)) {
-                    ures_getNextString(&installed, NULL, (const char **)&temp[i++], &status);
-                }
-                temp[i] = NULL;
-
-                umtx_lock(NULL);
-                if (_installedLocales == NULL)
-                {
-                    _installedLocales = temp;
-                    _installedLocalesCount = localeCount;
-                    temp = NULL;
-                    ucln_common_registerCleanup(UCLN_COMMON_ULOC, uloc_cleanup);
-                } 
-                umtx_unlock(NULL);
-
-                uprv_free(temp);
-            }
-        }
-        ures_close(&installed);
-        ures_close(index);
-    }
-}
-
-U_CAPI const char* U_EXPORT2
-uloc_getAvailable(int32_t offset) 
-{
-    
-    _load_installedLocales();
-    
-    if (offset > _installedLocalesCount)
-        return NULL;
-    return _installedLocales[offset];
-}
-
-U_CAPI int32_t  U_EXPORT2
-uloc_countAvailable()
-{
-    _load_installedLocales();
-    return _installedLocalesCount;
-}
-
-/**
- * Returns a list of all language codes defined in ISO 639.  This is a pointer
- * to an array of pointers to arrays of char.  All of these pointers are owned
- * by ICU-- do not delete them, and do not write through them.  The array is
- * terminated with a null pointer.
- */
-U_CAPI const char* const*  U_EXPORT2
-uloc_getISOLanguages() 
-{
-    return LANGUAGES;
-}
-
-/**
- * Returns a list of all 2-letter country codes defined in ISO 639.  This is a
- * pointer to an array of pointers to arrays of char.  All of these pointers are
- * owned by ICU-- do not delete them, and do not write through them.  The array is
- * terminated with a null pointer.
- */
-U_CAPI const char* const*  U_EXPORT2
-uloc_getISOCountries() 
-{
-    return COUNTRIES;
-}
-
-
-/* this function to be moved into cstring.c later */
-static char gDecimal = 0;
-
-static /* U_CAPI */
-double
-/* U_EXPORT2 */
-_uloc_strtod(const char *start, char **end) {
-    char *decimal;
-    char *myEnd;
-    char buf[30];
-    double rv;
-    if (!gDecimal) {
-        char rep[5];
-        /* For machines that decide to change the decimal on you,
-        and try to be too smart with localization.
-        This normally should be just a '.'. */
-        sprintf(rep, "%+1.1f", 1.0);
-        gDecimal = rep[2];
-    }
-
-    if(gDecimal == '.') {
-        return uprv_strtod(start, end); /* fall through to OS */
-    } else {
-        uprv_strncpy(buf, start, 29);
-        buf[29]=0;
-        decimal = uprv_strchr(buf, '.');
-        if(decimal) {
-            *decimal = gDecimal;
-        } else {
-            return uprv_strtod(start, end); /* no decimal point */
-        }
-        rv = uprv_strtod(buf, &myEnd);
-        if(end) {
-            *end = (char*)(start+(myEnd-buf)); /* cast away const (to follow uprv_strtod API.) */
-        }
-        return rv;
-    }
-}
-
-typedef struct { 
-    float q;
-    int32_t dummy;  /* to avoid uninitialized memory copy from qsort */
-    char *locale;
-} _acceptLangItem;
-
-static int32_t U_CALLCONV
-uloc_acceptLanguageCompare(const void *context, const void *a, const void *b)
-{
-    const _acceptLangItem *aa = (const _acceptLangItem*)a;
-    const _acceptLangItem *bb = (const _acceptLangItem*)b;
-
-    int32_t rc = 0;
-    if(bb->q < aa->q) {
-        rc = -1;  /* A > B */
-    } else if(bb->q > aa->q) {
-        rc = 1;   /* A < B */
-    } else {
-        rc = 0;   /* A = B */
-    }
-
-    if(rc==0) {
-        rc = uprv_stricmp(aa->locale, bb->locale);
-    }
-
-#if defined(ULOC_DEBUG)
-    /*  fprintf(stderr, "a:[%s:%g], b:[%s:%g] -> %d\n", 
-    aa->locale, aa->q, 
-    bb->locale, bb->q,
-    rc);*/
-#endif
-
-    return rc;
-}
-
-static ULayoutType
-_uloc_getOrientationHelper(const char* localeId,
-                           const char* key,
-                           UErrorCode *status)
-{
-    ULayoutType result = ULOC_LAYOUT_UNKNOWN;
-
-    if (!U_FAILURE(*status)) {
-        int32_t length = 0;
-        char localeBuffer[ULOC_FULLNAME_CAPACITY];
-
-        uloc_canonicalize(localeId, localeBuffer, sizeof(localeBuffer), status);
-
-        if (!U_FAILURE(*status)) {
-            const UChar* const value =
-                _res_getTableStringWithFallback(
-                    NULL,
-                    localeBuffer,
-                    "layout",
-                    NULL,
-                    key,
-                    &length,
-                    status);
-
-            if (!U_FAILURE(*status) && length != 0) {
-                switch(value[0])
-                {
-                case 0x0062: /* 'b' */
-                    result = ULOC_LAYOUT_BTT;
-                    break;
-                case 0x006C: /* 'l' */
-                    result = ULOC_LAYOUT_LTR;
-                    break;
-                case 0x0072: /* 'r' */
-                    result = ULOC_LAYOUT_RTL;
-                    break;
-                case 0x0074: /* 't' */
-                    result = ULOC_LAYOUT_TTB;
-                    break;
-                default:
-                    *status = U_INTERNAL_PROGRAM_ERROR;
-                    break;
-                }
-            }
-        }
-    }
-
-    return result;
-}
-
-U_DRAFT ULayoutType U_EXPORT2
-uloc_getCharacterOrientation(const char* localeId,
-                             UErrorCode *status)
-{
-    return _uloc_getOrientationHelper(localeId, "characters", status);
-}
-
-/**
- * Get the layout line orientation for the specified locale.
- * 
- * @param localeID locale name
- * @param status Error status
- * @return an enum indicating the layout orientation for lines.
- * @draft ICU 4.0
- */
-U_DRAFT ULayoutType U_EXPORT2
-uloc_getLineOrientation(const char* localeId,
-                        UErrorCode *status)
-{
-    return _uloc_getOrientationHelper(localeId, "lines", status);
-}
-
-/* 
-mt-mt, ja;q=0.76, en-us;q=0.95, en;q=0.92, en-gb;q=0.89, fr;q=0.87, iu-ca;q=0.84, iu;q=0.82, ja-jp;q=0.79, mt;q=0.97, de-de;q=0.74, de;q=0.71, es;q=0.68, it-it;q=0.66, it;q=0.63, vi-vn;q=0.61, vi;q=0.58, nl-nl;q=0.55, nl;q=0.53
-*/
-
-U_CAPI int32_t U_EXPORT2
-uloc_acceptLanguageFromHTTP(char *result, int32_t resultAvailable, UAcceptResult *outResult,
-                            const char *httpAcceptLanguage,
-                            UEnumeration* availableLocales,
-                            UErrorCode *status)
-{
-    _acceptLangItem *j;
-    _acceptLangItem smallBuffer[30];
-    char **strs;
-    char tmp[ULOC_FULLNAME_CAPACITY +1];
-    int32_t n = 0;
-    const char *itemEnd;
-    const char *paramEnd;
-    const char *s;
-    const char *t;
-    int32_t res;
-    int32_t i;
-    int32_t l = (int32_t)uprv_strlen(httpAcceptLanguage);
-    int32_t jSize;
-    char *tempstr; /* Use for null pointer check */
-
-    j = smallBuffer;
-    jSize = sizeof(smallBuffer)/sizeof(smallBuffer[0]);
-    if(U_FAILURE(*status)) {
-        return -1;
-    }
-
-    for(s=httpAcceptLanguage;s&&*s;) {
-        while(isspace(*s)) /* eat space at the beginning */
-            s++;
-        itemEnd=uprv_strchr(s,',');
-        paramEnd=uprv_strchr(s,';');
-        if(!itemEnd) {
-            itemEnd = httpAcceptLanguage+l; /* end of string */
-        }
-        if(paramEnd && paramEnd<itemEnd) { 
-            /* semicolon (;) is closer than end (,) */
-            t = paramEnd+1;
-            if(*t=='q') {
-                t++;
-            }
-            while(isspace(*t)) {
-                t++;
-            }
-            if(*t=='=') {
-                t++;
-            }
-            while(isspace(*t)) {
-                t++;
-            }
-            j[n].q = (float)_uloc_strtod(t,NULL);
-        } else {
-            /* no semicolon - it's 1.0 */
-            j[n].q = 1.0f;
-            paramEnd = itemEnd;
-        }
-        j[n].dummy=0;
-        /* eat spaces prior to semi */
-        for(t=(paramEnd-1);(paramEnd>s)&&isspace(*t);t--)
-            ;
-        /* Check for null pointer from uprv_strndup */
-        tempstr = uprv_strndup(s,(int32_t)((t+1)-s));
-        if (tempstr == NULL) {
-            *status = U_MEMORY_ALLOCATION_ERROR;
-            return -1;
-        }
-        j[n].locale = tempstr;
-        uloc_canonicalize(j[n].locale,tmp,sizeof(tmp)/sizeof(tmp[0]),status);
-        if(strcmp(j[n].locale,tmp)) {
-            uprv_free(j[n].locale);
-            j[n].locale=uprv_strdup(tmp);
-        }
-#if defined(ULOC_DEBUG)
-        /*fprintf(stderr,"%d: s <%s> q <%g>\n", n, j[n].locale, j[n].q);*/
-#endif
-        n++;
-        s = itemEnd;
-        while(*s==',') { /* eat duplicate commas */
-            s++;
-        }
-        if(n>=jSize) {
-            if(j==smallBuffer) {  /* overflowed the small buffer. */
-                j = uprv_malloc(sizeof(j[0])*(jSize*2));
-                if(j!=NULL) {
-                    uprv_memcpy(j,smallBuffer,sizeof(j[0])*jSize);
-                }
-#if defined(ULOC_DEBUG)
-                fprintf(stderr,"malloced at size %d\n", jSize);
-#endif
-            } else {
-                j = uprv_realloc(j, sizeof(j[0])*jSize*2);
-#if defined(ULOC_DEBUG)
-                fprintf(stderr,"re-alloced at size %d\n", jSize);
-#endif
-            }
-            jSize *= 2;
-            if(j==NULL) {
-                *status = U_MEMORY_ALLOCATION_ERROR;
-                return -1;
-            }
-        }
-    }
-    uprv_sortArray(j, n, sizeof(j[0]), uloc_acceptLanguageCompare, NULL, TRUE, status);
-    if(U_FAILURE(*status)) {
-        if(j != smallBuffer) {
-#if defined(ULOC_DEBUG)
-            fprintf(stderr,"freeing j %p\n", j);
-#endif
-            uprv_free(j);
-        }
-        return -1;
-    }
-    strs = uprv_malloc((size_t)(sizeof(strs[0])*n));
-    /* Check for null pointer */
-    if (strs == NULL) {
-        uprv_free(j); /* Free to avoid memory leak */
-        *status = U_MEMORY_ALLOCATION_ERROR;
-        return -1;
-    }
-    for(i=0;i<n;i++) {
-#if defined(ULOC_DEBUG)
-        /*fprintf(stderr,"%d: s <%s> q <%g>\n", i, j[i].locale, j[i].q);*/
-#endif
-        strs[i]=j[i].locale;
-    }
-    res =  uloc_acceptLanguage(result, resultAvailable, outResult, 
-        (const char**)strs, n, availableLocales, status);
-    for(i=0;i<n;i++) {
-        uprv_free(strs[i]);
-    }
-    uprv_free(strs);
-    if(j != smallBuffer) {
-#if defined(ULOC_DEBUG)
-        fprintf(stderr,"freeing j %p\n", j);
-#endif
-        uprv_free(j);
-    }
-    return res;
-}
-
-
-U_CAPI int32_t U_EXPORT2
-uloc_acceptLanguage(char *result, int32_t resultAvailable, 
-                    UAcceptResult *outResult, const char **acceptList,
-                    int32_t acceptListCount,
-                    UEnumeration* availableLocales,
-                    UErrorCode *status)
-{
-    int32_t i,j;
-    int32_t len;
-    int32_t maxLen=0;
-    char tmp[ULOC_FULLNAME_CAPACITY+1];
-    const char *l;
-    char **fallbackList;
-    if(U_FAILURE(*status)) {
-        return -1;
-    }
-    fallbackList = uprv_malloc((size_t)(sizeof(fallbackList[0])*acceptListCount));
-    if(fallbackList==NULL) {
-        *status = U_MEMORY_ALLOCATION_ERROR;
-        return -1;
-    }
-    for(i=0;i<acceptListCount;i++) {
-#if defined(ULOC_DEBUG)
-        fprintf(stderr,"%02d: %s\n", i, acceptList[i]);
-#endif
-        while((l=uenum_next(availableLocales, NULL, status))) {
-#if defined(ULOC_DEBUG)
-            fprintf(stderr,"  %s\n", l);
-#endif
-            len = (int32_t)uprv_strlen(l);
-            if(!uprv_strcmp(acceptList[i], l)) {
-                if(outResult) { 
-                    *outResult = ULOC_ACCEPT_VALID;
-                }
-#if defined(ULOC_DEBUG)
-                fprintf(stderr, "MATCH! %s\n", l);
-#endif
-                if(len>0) {
-                    uprv_strncpy(result, l, uprv_min(len, resultAvailable));
-                }
-                for(j=0;j<i;j++) {
-                    uprv_free(fallbackList[j]);
-                }
-                uprv_free(fallbackList);
-                return u_terminateChars(result, resultAvailable, len, status);   
-            }
-            if(len>maxLen) {
-                maxLen = len;
-            }
-        }
-        uenum_reset(availableLocales, status);    
-        /* save off parent info */
-        if(uloc_getParent(acceptList[i], tmp, sizeof(tmp)/sizeof(tmp[0]), status)!=0) {
-            fallbackList[i] = uprv_strdup(tmp);
-        } else {
-            fallbackList[i]=0;
-        }
-    }
-
-    for(maxLen--;maxLen>0;maxLen--) {
-        for(i=0;i<acceptListCount;i++) {
-            if(fallbackList[i] && ((int32_t)uprv_strlen(fallbackList[i])==maxLen)) {
-#if defined(ULOC_DEBUG)
-                fprintf(stderr,"Try: [%s]", fallbackList[i]);
-#endif
-                while((l=uenum_next(availableLocales, NULL, status))) {
-#if defined(ULOC_DEBUG)
-                    fprintf(stderr,"  %s\n", l);
-#endif
-                    len = (int32_t)uprv_strlen(l);
-                    if(!uprv_strcmp(fallbackList[i], l)) {
-                        if(outResult) { 
-                            *outResult = ULOC_ACCEPT_FALLBACK;
-                        }
-#if defined(ULOC_DEBUG)
-                        fprintf(stderr, "fallback MATCH! %s\n", l);
-#endif
-                        if(len>0) {
-                            uprv_strncpy(result, l, uprv_min(len, resultAvailable));
-                        }
-                        for(j=0;j<acceptListCount;j++) {
-                            uprv_free(fallbackList[j]);
-                        }
-                        uprv_free(fallbackList);
-                        return u_terminateChars(result, resultAvailable, len, status);
-                    }
-                }
-                uenum_reset(availableLocales, status);    
-
-                if(uloc_getParent(fallbackList[i], tmp, sizeof(tmp)/sizeof(tmp[0]), status)!=0) {
-                    uprv_free(fallbackList[i]);
-                    fallbackList[i] = uprv_strdup(tmp);
-                } else {
-                    uprv_free(fallbackList[i]);
-                    fallbackList[i]=0;
-                }
-            }
-        }
-        if(outResult) { 
-            *outResult = ULOC_ACCEPT_FAILED;
-        }
-    }
-    for(i=0;i<acceptListCount;i++) {
-        uprv_free(fallbackList[i]);
-    }
-    uprv_free(fallbackList);
-    return -1;
-}
-
-
-/**
- * This function looks for the localeID in the likelySubtags resource.
- *
- * @param localeID The tag to find.
- * @param buffer A buffer to hold the matching entry
- * @param bufferLength The length of the output buffer
- * @return A pointer to "buffer" if found, or a null pointer if not.
- */
-static const char*  U_CALLCONV
-findLikelySubtags(const char* localeID,
-                  char* buffer,
-                  int32_t bufferLength,
-                  UErrorCode* err) {
-    const char* result = NULL;
-
-    if (!U_FAILURE(*err)) {
-        int32_t resLen = 0;
-        const UChar* s = NULL;
-        UResourceBundle* subtags = ures_openDirect(NULL, "likelySubtags", err);
-        if (!U_FAILURE(*err)) {
-            s = ures_getStringByKey(subtags, localeID, &resLen, err);
-
-            if (U_FAILURE(*err)) {
-                /*
-                 * If a resource is missing, it's not really an error, it's
-                 * just that we don't have any data for that particular locale ID.
-                 */
-                if (*err == U_MISSING_RESOURCE_ERROR) {
-                    *err = U_ZERO_ERROR;
-                }
-            }
-            else if (resLen >= bufferLength) {
-                /* The buffer should never overflow. */
-                *err = U_INTERNAL_PROGRAM_ERROR;
-            }
-            else {
-                u_UCharsToChars(s, buffer, resLen + 1);
-                result = buffer;
-            }
-
-            ures_close(subtags);
-        }
-    }
-
-    return result;
-}
-
-/**
- * Append a tag to a buffer, adding the separator if necessary.  The buffer
- * must be large enough to contain the resulting tag plus any separator
- * necessary. The tag must not be a zero-length string.
- *
- * @param tag The tag to add.
- * @param tagLength The length of the tag.
- * @param buffer The output buffer.
- * @param bufferLength The length of the output buffer.  This is an input/ouput parameter.
- **/
-static void U_CALLCONV
-appendTag(
-    const char* tag,
-    int32_t tagLength,
-    char* buffer,
-    int32_t* bufferLength) {
-
-    if (*bufferLength > 0) {
-        buffer[*bufferLength] = '_';
-        ++(*bufferLength);
-    }
-
-    uprv_memmove(
-        &buffer[*bufferLength],
-        tag,
-        tagLength);
-
-    *bufferLength += tagLength;
-}
-
-/**
- * These are the canonical strings for unknown languages, scripts and regions.
- **/
-static const char* const unknownLanguage = "und";
-static const char* const unknownScript = "Zzzz";
-static const char* const unknownRegion = "ZZ";
-
-/**
- * Create a tag string from the supplied parameters.  The lang, script and region
- * parameters may be NULL pointers. If they are, their corresponding length parameters
- * must be less than or equal to 0.
- *
- * If any of the language, script or region parameters are empty, and the alternateTags
- * parameter is not NULL, it will be parsed for potential language, script and region tags
- * to be used when constructing the new tag.  If the alternateTags parameter is NULL, or
- * it contains no language tag, the default tag for the unknown language is used.
- *
- * If the length of the new string exceeds the capacity of the output buffer, 
- * the function copies as many bytes to the output buffer as it can, and returns
- * the error U_BUFFER_OVERFLOW_ERROR.
- *
- * If an illegal argument is provided, the function returns the error
- * U_ILLEGAL_ARGUMENT_ERROR.
- *
- * Note that this function can return the warning U_STRING_NOT_TERMINATED_WARNING if
- * the tag string fits in the output buffer, but the null terminator doesn't.
- *
- * @param lang The language tag to use.
- * @param langLength The length of the language tag.
- * @param script The script tag to use.
- * @param scriptLength The length of the script tag.
- * @param region The region tag to use.
- * @param regionLength The length of the region tag.
- * @param trailing Any trailing data to append to the new tag.
- * @param trailingLength The length of the trailing data.
- * @param alternateTags A string containing any alternate tags.
- * @param tag The output buffer.
- * @param tagCapacity The capacity of the output buffer.
- * @param err A pointer to a UErrorCode for error reporting.
- * @return The length of the tag string, which may be greater than tagCapacity, or -1 on error.
- **/
-static int32_t U_CALLCONV
-createTagStringWithAlternates(
-    const char* lang,
-    int32_t langLength,
-    const char* script,
-    int32_t scriptLength,
-    const char* region,
-    int32_t regionLength,
-    const char* trailing,
-    int32_t trailingLength,
-    const char* alternateTags,
-    char* tag,
-    int32_t tagCapacity,
-    UErrorCode* err) {
-
-    if (U_FAILURE(*err)) {
-        goto error;
-    }
-    else if (tag == NULL ||
-             tagCapacity <= 0 ||
-             langLength >= ULOC_LANG_CAPACITY ||
-             scriptLength >= ULOC_SCRIPT_CAPACITY ||
-             regionLength >= ULOC_COUNTRY_CAPACITY) {
-        goto error;
-    }
-    else {
-        /**
-         * ULOC_FULLNAME_CAPACITY will provide enough capacity
-         * that we can build a string that contains the language,
-         * script and region code without worrying about overrunning
-         * the user-supplied buffer.
-         **/
-        char tagBuffer[ULOC_FULLNAME_CAPACITY];
-        int32_t tagLength = 0;
-        int32_t capacityRemaining = tagCapacity;
-        UBool regionAppended = FALSE;
-
-        if (langLength > 0) {
-            appendTag(
-                lang,
-                langLength,
-                tagBuffer,
-                &tagLength);
-        }
-        else if (alternateTags == NULL) {
-            /*
-             * Append the value for an unknown language, if
-             * we found no language.
-             */
-            appendTag(
-                unknownLanguage,
-                uprv_strlen(unknownLanguage),
-                tagBuffer,
-                &tagLength);
-        }
-        else {
-            /*
-             * Parse the alternateTags string for the language.
-             */
-            char alternateLang[ULOC_LANG_CAPACITY];
-            int32_t alternateLangLength = sizeof(alternateLang);
-
-            alternateLangLength =
-                uloc_getLanguage(
-                    alternateTags,
-                    alternateLang,
-                    alternateLangLength,
-                    err);
-            if(U_FAILURE(*err) ||
-                alternateLangLength >= ULOC_LANG_CAPACITY) {
-                goto error;
-            }
-            else if (alternateLangLength == 0) {
-                /*
-                 * Append the value for an unknown language, if
-                 * we found no language.
-                 */
-                appendTag(
-                    unknownLanguage,
-                    uprv_strlen(unknownLanguage),
-                    tagBuffer,
-                    &tagLength);
-            }
-            else {
-                appendTag(
-                    alternateLang,
-                    alternateLangLength,
-                    tagBuffer,
-                    &tagLength);
-            }
-        }
-
-        if (scriptLength > 0) {
-            appendTag(
-                script,
-                scriptLength,
-                tagBuffer,
-                &tagLength);
-        }
-        else if (alternateTags != NULL) {
-            /*
-             * Parse the alternateTags string for the script.
-             */
-            char alternateScript[ULOC_SCRIPT_CAPACITY];
-
-            const int32_t alternateScriptLength =
-                uloc_getScript(
-                    alternateTags,
-                    alternateScript,
-                    sizeof(alternateScript),
-                    err);
-
-            if (U_FAILURE(*err) ||
-                alternateScriptLength >= ULOC_SCRIPT_CAPACITY) {
-                goto error;
-            }
-            else if (alternateScriptLength > 0) {
-                appendTag(
-                    alternateScript,
-                    alternateScriptLength,
-                    tagBuffer,
-                    &tagLength);
-            }
-        }
-
-        if (regionLength > 0) {
-            appendTag(
-                region,
-                regionLength,
-                tagBuffer,
-                &tagLength);
-
-            regionAppended = TRUE;
-        }
-        else if (alternateTags != NULL) {
-            /*
-             * Parse the alternateTags string for the region.
-             */
-            char alternateRegion[ULOC_COUNTRY_CAPACITY];
-
-            const int32_t alternateRegionLength =
-                uloc_getCountry(
-                    alternateTags,
-                    alternateRegion,
-                    sizeof(alternateRegion),
-                    err);
-            if (U_FAILURE(*err) ||
-                alternateRegionLength >= ULOC_COUNTRY_CAPACITY) {
-                goto error;
-            }
-            else if (alternateRegionLength > 0) {
-                appendTag(
-                    alternateRegion,
-                    alternateRegionLength,
-                    tagBuffer,
-                    &tagLength);
-
-                regionAppended = TRUE;
-            }
-        }
-
-        {
-            const int32_t toCopy =
-                tagLength >= tagCapacity ? tagCapacity : tagLength;
-
-            /**
-             * Copy the partial tag from our internal buffer to the supplied
-             * target.
-             **/
-            uprv_memcpy(
-                tag,
-                tagBuffer,
-                toCopy);
-
-            capacityRemaining -= toCopy;
-        }
-
-        if (trailingLength > 0) {
-            if (capacityRemaining > 0 && !regionAppended) {
-                tag[tagLength++] = '_';
-                --capacityRemaining;
-            }
-
-            if (capacityRemaining > 0) {
-                /*
-                 * Copy the trailing data into the supplied buffer.  Use uprv_memmove, since we
-                 * don't know if the user-supplied buffers overlap.
-                 */
-                const int32_t toCopy =
-                    trailingLength >= capacityRemaining ? capacityRemaining : trailingLength;
-
-                uprv_memmove(
-                    &tag[tagLength],
-                    trailing,
-                    toCopy);
-            }
-        }
-
-        tagLength += trailingLength;
-
-        return u_terminateChars(
-                    tag,
-                    tagCapacity,
-                    tagLength,
-                    err);
-    }
-
-error:
-
-    /**
-     * An overflow indicates the locale ID passed in
-     * is ill-formed.  If we got here, and there was
-     * no previous error, it's an implicit overflow.
-     **/
-    if (*err ==  U_BUFFER_OVERFLOW_ERROR ||
-        U_SUCCESS(*err)) {
-        *err = U_ILLEGAL_ARGUMENT_ERROR;
-    }
-
-    return -1;
-}
-
-/**
- * Create a tag string from the supplied parameters.  The lang, script and region
- * parameters may be NULL pointers. If they are, their corresponding length parameters
- * must be less than or equal to 0.  If the lang parameter is an empty string, the
- * default value for an unknown language is written to the output buffer.
- *
- * If the length of the new string exceeds the capacity of the output buffer, 
- * the function copies as many bytes to the output buffer as it can, and returns
- * the error U_BUFFER_OVERFLOW_ERROR.
- *
- * If an illegal argument is provided, the function returns the error
- * U_ILLEGAL_ARGUMENT_ERROR.
- *
- * @param lang The language tag to use.
- * @param langLength The length of the language tag.
- * @param script The script tag to use.
- * @param scriptLength The length of the script tag.
- * @param region The region tag to use.
- * @param regionLength The length of the region tag.
- * @param trailing Any trailing data to append to the new tag.
- * @param trailingLength The length of the trailing data.
- * @param tag The output buffer.
- * @param tagCapacity The capacity of the output buffer.
- * @param err A pointer to a UErrorCode for error reporting.
- * @return The length of the tag string, which may be greater than tagCapacity.
- **/
-static int32_t U_CALLCONV
-createTagString(
-    const char* lang,
-    int32_t langLength,
-    const char* script,
-    int32_t scriptLength,
-    const char* region,
-    int32_t regionLength,
-    const char* trailing,
-    int32_t trailingLength,
-    char* tag,
-    int32_t tagCapacity,
-    UErrorCode* err)
-{
-    return createTagStringWithAlternates(
-                lang,
-                langLength,
-                script,
-                scriptLength,
-                region,
-                regionLength,
-                trailing,
-                trailingLength,
-                NULL,
-                tag,
-                tagCapacity,
-                err);
-}
-
-/**
- * Parse the language, script, and region subtags from a tag string, and copy the
- * results into the corresponding output parameters. The buffers are null-terminated,
- * unless overflow occurs.
- *
- * The langLength, scriptLength, and regionLength parameters are input/output
- * parameters, and must contain the capacity of their corresponding buffers on
- * input.  On output, they will contain the actual length of the buffers, not
- * including the null terminator.
- *
- * If the length of any of the output subtags exceeds the capacity of the corresponding
- * buffer, the function copies as many bytes to the output buffer as it can, and returns
- * the error U_BUFFER_OVERFLOW_ERROR.  It will not parse any more subtags once overflow
- * occurs.
- *
- * If an illegal argument is provided, the function returns the error
- * U_ILLEGAL_ARGUMENT_ERROR.
- *
- * @param localeID The locale ID to parse.
- * @param lang The language tag buffer.
- * @param langLength The length of the language tag.
- * @param script The script tag buffer.
- * @param scriptLength The length of the script tag.
- * @param region The region tag buffer.
- * @param regionLength The length of the region tag.
- * @param err A pointer to a UErrorCode for error reporting.
- * @return The number of chars of the localeID parameter consumed.
- **/
-static int32_t U_CALLCONV
-parseTagString(
-    const char* localeID,
-    char* lang,
-    int32_t* langLength,
-    char* script,
-    int32_t* scriptLength,
-    char* region,
-    int32_t* regionLength,
-    UErrorCode* err)
-{
-    const char* position = localeID;
-    int32_t subtagLength = 0;
-
-    if(U_FAILURE(*err) ||
-       localeID == NULL ||
-       lang == NULL ||
-       langLength == NULL ||
-       script == NULL ||
-       scriptLength == NULL ||
-       region == NULL ||
-       regionLength == NULL) {
-        goto error;
-    }
-
-    subtagLength = _getLanguage(position, lang, *langLength, &position);
-    u_terminateChars(lang, *langLength, subtagLength, err);
-
-    /*
-     * Note that we explicit consider U_STRING_NOT_TERMINATED_WARNING
-     * to be an error, because it indicates the user-supplied tag is
-     * not well-formed.
-     */
-    if(*err != U_ZERO_ERROR) {
-        goto error;
-    }
-
-    *langLength = subtagLength;
-
-    /*
-     * If no language was present, use the value of unknownLanguage
-     * instead.  Otherwise, move past any separator.
-     */
-    if (*langLength == 0) {
-        uprv_strcpy(
-            lang,
-            unknownLanguage);
-        *langLength = uprv_strlen(lang);
-    }
-    else if (_isIDSeparator(*position)) {
-        ++position;
-    }
-
-    subtagLength = _getScript(position, script, *scriptLength, &position);
-    u_terminateChars(script, *scriptLength, subtagLength, err);
-
-    if(*err != U_ZERO_ERROR) {
-        goto error;
-    }
-
-    *scriptLength = subtagLength;
-
-    if (*scriptLength > 0) {
-        if (uprv_strnicmp(script, unknownScript, *scriptLength) == 0) {
-            /**
-             * If the script part is the "unknown" script, then don't return it.
-             **/
-            *scriptLength = 0;
-        }
-
-        /*
-         * Move past any separator.
-         */
-        if (_isIDSeparator(*position)) {
-            ++position;
-        }    
-    }
-
-    subtagLength = _getCountry(position, region, *regionLength, &position);
-    u_terminateChars(region, *regionLength, subtagLength, err);
-
-    if(*err != U_ZERO_ERROR) {
-        goto error;
-    }
-
-    *regionLength = subtagLength;
-
-    if (*regionLength > 0) {
-        if (uprv_strnicmp(region, unknownRegion, *regionLength) == 0) {
-            /**
-             * If the region part is the "unknown" region, then don't return it.
-             **/
-            *regionLength = 0;
-        }
-    }
-
-exit:
-
-    return (int32_t)(position - localeID);
-
-error:
-
-    /**
-     * If we get here, we have no explicit error, it's the result of an
-     * illegal argument.
-     **/
-    if (!U_FAILURE(*err)) {
-        *err = U_ILLEGAL_ARGUMENT_ERROR;
-    }
-
-    goto exit;
-}
-
-static int32_t U_CALLCONV
-createLikelySubtagsString(
-    const char* lang,
-    int32_t langLength,
-    const char* script,
-    int32_t scriptLength,
-    const char* region,
-    int32_t regionLength,
-    const char* variants,
-    int32_t variantsLength,
-    char* tag,
-    int32_t tagCapacity,
-    UErrorCode* err)
-{
-    /**
-     * ULOC_FULLNAME_CAPACITY will provide enough capacity
-     * that we can build a string that contains the language,
-     * script and region code without worrying about overrunning
-     * the user-supplied buffer.
-     **/
-    char tagBuffer[ULOC_FULLNAME_CAPACITY];
-    char likelySubtagsBuffer[ULOC_FULLNAME_CAPACITY];
-    int32_t tagBufferLength = 0;
-
-    if(U_FAILURE(*err)) {
-        goto error;
-    }
-
-    /**
-     * Try the language with the script and region first.
-     **/
-    if (scriptLength > 0 && regionLength > 0) {
-
-        const char* likelySubtags = NULL;
-
-        tagBufferLength = createTagString(
-            lang,
-            langLength,
-            script,
-            scriptLength,
-            region,
-            regionLength,
-            NULL,
-            0,
-            tagBuffer,
-            sizeof(tagBuffer),
-            err);
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-
-        likelySubtags =
-            findLikelySubtags(
-                tagBuffer,
-                likelySubtagsBuffer,
-                sizeof(likelySubtagsBuffer),
-                err);
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-
-        if (likelySubtags != NULL) {
-            /* Always use the language tag from the
-               maximal string, since it may be more
-               specific than the one provided. */
-            return createTagStringWithAlternates(
-                        NULL,
-                        0,
-                        NULL,
-                        0,
-                        NULL,
-                        0,
-                        variants,
-                        variantsLength,
-                        likelySubtags,
-                        tag,
-                        tagCapacity,
-                        err);
-        }
-    }
-
-    /**
-     * Try the language with just the script.
-     **/
-    if (scriptLength > 0) {
-
-        const char* likelySubtags = NULL;
-
-        tagBufferLength = createTagString(
-            lang,
-            langLength,
-            script,
-            scriptLength,
-            NULL,
-            0,
-            NULL,
-            0,
-            tagBuffer,
-            sizeof(tagBuffer),
-            err);
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-
-        likelySubtags =
-            findLikelySubtags(
-                tagBuffer,
-                likelySubtagsBuffer,
-                sizeof(likelySubtagsBuffer),
-                err);
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-
-        if (likelySubtags != NULL) {
-            /* Always use the language tag from the
-               maximal string, since it may be more
-               specific than the one provided. */
-            return createTagStringWithAlternates(
-                        NULL,
-                        0,
-                        NULL,
-                        0,
-                        region,
-                        regionLength,
-                        variants,
-                        variantsLength,
-                        likelySubtags,
-                        tag,
-                        tagCapacity,
-                        err);
-        }
-    }
-
-    /**
-     * Try the language with just the region.
-     **/
-    if (regionLength > 0) {
-
-        const char* likelySubtags = NULL;
-
-        createTagString(
-            lang,
-            langLength,
-            NULL,
-            0,
-            region,
-            regionLength,
-            NULL,
-            0,
-            tagBuffer,
-            sizeof(tagBuffer),
-            err);
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-
-        likelySubtags =
-            findLikelySubtags(
-                tagBuffer,
-                likelySubtagsBuffer,
-                sizeof(likelySubtagsBuffer),
-                err);
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-
-        if (likelySubtags != NULL) {
-            /* Always use the language tag from the
-               maximal string, since it may be more
-               specific than the one provided. */
-            return createTagStringWithAlternates(
-                        NULL,
-                        0,
-                        script,
-                        scriptLength,
-                        NULL,
-                        0,
-                        variants,
-                        variantsLength,
-                        likelySubtags,
-                        tag,
-                        tagCapacity,
-                        err);
-        }
-    }
-
-    /**
-     * Finally, try just the language.
-     **/
-    {
-        const char* likelySubtags = NULL;
-
-        createTagString(
-            lang,
-            langLength,
-            NULL,
-            0,
-            NULL,
-            0,
-            NULL,
-            0,
-            tagBuffer,
-            sizeof(tagBuffer),
-            err);
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-
-        likelySubtags =
-            findLikelySubtags(
-                tagBuffer,
-                likelySubtagsBuffer,
-                sizeof(likelySubtagsBuffer),
-                err);
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-
-        if (likelySubtags != NULL) {
-            /* Always use the language tag from the
-               maximal string, since it may be more
-               specific than the one provided. */
-            return createTagStringWithAlternates(
-                        NULL,
-                        0,
-                        script,
-                        scriptLength,
-                        region,
-                        regionLength,
-                        variants,
-                        variantsLength,
-                        likelySubtags,
-                        tag,
-                        tagCapacity,
-                        err);
-        }
-    }
-
-    return u_terminateChars(
-                tag,
-                tagCapacity,
-                0,
-                err);
-
-error:
-
-    if (!U_FAILURE(*err)) {
-        *err = U_ILLEGAL_ARGUMENT_ERROR;
-    }
-
-    return -1;
-}
-
-static int32_t
-_uloc_addLikelySubtags(const char*    localeID,
-         char* maximizedLocaleID,
-         int32_t maximizedLocaleIDCapacity,
-         UErrorCode* err)
-{
-    char lang[ULOC_LANG_CAPACITY];
-    int32_t langLength = sizeof(lang);
-    char script[ULOC_SCRIPT_CAPACITY];
-    int32_t scriptLength = sizeof(script);
-    char region[ULOC_COUNTRY_CAPACITY];
-    int32_t regionLength = sizeof(region);
-    const char* trailing = "";
-    int32_t trailingLength = 0;
-    int32_t trailingIndex = 0;
-    int32_t resultLength = 0;
-
-    if(U_FAILURE(*err)) {
-        goto error;
-    }
-    else if (localeID == NULL ||
-             maximizedLocaleID == NULL ||
-             maximizedLocaleIDCapacity <= 0) {
-        goto error;
-    }
-
-    trailingIndex = parseTagString(
-        localeID,
-        lang,
-        &langLength,
-        script,
-        &scriptLength,
-        region,
-        &regionLength,
-        err);
-    if(U_FAILURE(*err)) {
-        /* Overflow indicates an illegal argument error */
-        if (*err == U_BUFFER_OVERFLOW_ERROR) {
-            *err = U_ILLEGAL_ARGUMENT_ERROR;
-        }
-
-        goto error;
-    }
-
-    /* Find the length of the trailing portion. */
-    trailing = &localeID[trailingIndex];
-    trailingLength = uprv_strlen(trailing);
-
-    resultLength =
-        createLikelySubtagsString(
-            lang,
-            langLength,
-            script,
-            scriptLength,
-            region,
-            regionLength,
-            trailing,
-            trailingLength,
-            maximizedLocaleID,
-            maximizedLocaleIDCapacity,
-            err);
-
-    if (resultLength == 0) {
-        const int32_t localIDLength =
-            uprv_strlen(localeID);
-
-        /*
-         * If we get here, we need to return localeID.
-         */
-        uprv_memcpy(
-            maximizedLocaleID,
-            localeID,
-            localIDLength <= maximizedLocaleIDCapacity ? 
-                localIDLength : maximizedLocaleIDCapacity);
-
-        resultLength =
-            u_terminateChars(
-                maximizedLocaleID,
-                maximizedLocaleIDCapacity,
-                localIDLength,
-                err);
-    }
-
-    return resultLength;
-
-error:
-
-    if (!U_FAILURE(*err)) {
-        *err = U_ILLEGAL_ARGUMENT_ERROR;
-    }
-
-    return -1;
-}
-
-static int32_t
-_uloc_minimizeSubtags(const char*    localeID,
-         char* minimizedLocaleID,
-         int32_t minimizedLocaleIDCapacity,
-         UErrorCode* err)
-{
-    /**
-     * ULOC_FULLNAME_CAPACITY will provide enough capacity
-     * that we can build a string that contains the language,
-     * script and region code without worrying about overrunning
-     * the user-supplied buffer.
-     **/
-    char maximizedTagBuffer[ULOC_FULLNAME_CAPACITY];
-    int32_t maximizedTagBufferLength = sizeof(maximizedTagBuffer);
-
-    char lang[ULOC_LANG_CAPACITY];
-    int32_t langLength = sizeof(lang);
-    char script[ULOC_SCRIPT_CAPACITY];
-    int32_t scriptLength = sizeof(script);
-    char region[ULOC_COUNTRY_CAPACITY];
-    int32_t regionLength = sizeof(region);
-    const char* trailing = "";
-    int32_t trailingLength = 0;
-    int32_t trailingIndex = 0;
-
-    if(U_FAILURE(*err)) {
-        goto error;
-    }
-    else if (localeID == NULL ||
-             minimizedLocaleID == NULL ||
-             minimizedLocaleIDCapacity <= 0) {
-        goto error;
-    }
-
-    trailingIndex =
-        parseTagString(
-            localeID,
-            lang,
-            &langLength,
-            script,
-            &scriptLength,
-            region,
-            &regionLength,
-            err);
-    if(U_FAILURE(*err)) {
-
-        /* Overflow indicates an illegal argument error */
-        if (*err == U_BUFFER_OVERFLOW_ERROR) {
-            *err = U_ILLEGAL_ARGUMENT_ERROR;
-        }
-
-        goto error;
-    }
-
-    /* Find the spot where the variants begin, if any. */
-    trailing = &localeID[trailingIndex];
-    trailingLength = uprv_strlen(trailing);
-
-    createTagString(
-        lang,
-        langLength,
-        script,
-        scriptLength,
-        region,
-        regionLength,
-        NULL,
-        0,
-        maximizedTagBuffer,
-        maximizedTagBufferLength,
-        err);
-    if(U_FAILURE(*err)) {
-        goto error;
-    }
-
-    /**
-     * First, we need to first get the maximization
-     * from AddLikelySubtags.
-     **/
-    maximizedTagBufferLength =
-        uloc_addLikelySubtags(
-            maximizedTagBuffer,
-            maximizedTagBuffer,
-            maximizedTagBufferLength,
-            err);
-
-    if(U_FAILURE(*err)) {
-        goto error;
-    }
-
-    /**
-     * Start first with just the language.
-     **/
-    {
-        char tagBuffer[ULOC_FULLNAME_CAPACITY];
-
-        const int32_t tagBufferLength =
-            createLikelySubtagsString(
-                lang,
-                langLength,
-                NULL,
-                0,
-                NULL,
-                0,
-                NULL,
-                0,
-                tagBuffer,
-                sizeof(tagBuffer),
-                err);
-
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-        else if (uprv_strnicmp(
-                    maximizedTagBuffer,
-                    tagBuffer,
-                    tagBufferLength) == 0) {
-
-            return createTagString(
-                        lang,
-                        langLength,
-                        NULL,
-                        0,
-                        NULL,
-                        0,
-                        trailing,
-                        trailingLength,
-                        minimizedLocaleID,
-                        minimizedLocaleIDCapacity,
-                        err);
-        }
-    }
-
-    /**
-     * Next, try the language and region.
-     **/
-    if (regionLength > 0) {
-
-        char tagBuffer[ULOC_FULLNAME_CAPACITY];
-
-        const int32_t tagBufferLength =
-            createLikelySubtagsString(
-                lang,
-                langLength,
-                NULL,
-                0,
-                region,
-                regionLength,
-                NULL,
-                0,
-                tagBuffer,
-                sizeof(tagBuffer),
-                err);
-
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-        else if (uprv_strnicmp(
-                    maximizedTagBuffer,
-                    tagBuffer,
-                    tagBufferLength) == 0) {
-
-            return createTagString(
-                        lang,
-                        langLength,
-                        NULL,
-                        0,
-                        region,
-                        regionLength,
-                        trailing,
-                        trailingLength,
-                        minimizedLocaleID,
-                        minimizedLocaleIDCapacity,
-                        err);
-        }
-    }
-
-    /**
-     * Finally, try the language and script.  This is our last chance,
-     * since trying with all three subtags would only yield the
-     * maximal version that we already have.
-     **/
-    if (scriptLength > 0 && regionLength > 0) {
-        char tagBuffer[ULOC_FULLNAME_CAPACITY];
-
-        const int32_t tagBufferLength =
-            createLikelySubtagsString(
-                lang,
-                langLength,
-                script,
-                scriptLength,
-                NULL,
-                0,
-                NULL,
-                0,
-                tagBuffer,
-                sizeof(tagBuffer),
-                err);
-
-        if(U_FAILURE(*err)) {
-            goto error;
-        }
-        else if (uprv_strnicmp(
-                    maximizedTagBuffer,
-                    tagBuffer,
-                    tagBufferLength) == 0) {
-
-            return createTagString(
-                        lang,
-                        langLength,
-                        script,
-                        scriptLength,
-                        NULL,
-                        0,
-                        trailing,
-                        trailingLength,
-                        minimizedLocaleID,
-                        minimizedLocaleIDCapacity,
-                        err);
-        }
-    }
-
-    {
-        /**
-         * If we got here, return the locale ID parameter.
-         **/
-        const int32_t localeIDLength = uprv_strlen(localeID);
-
-        uprv_memcpy(
-            minimizedLocaleID,
-            localeID,
-            localeIDLength <= minimizedLocaleIDCapacity ? 
-                localeIDLength : minimizedLocaleIDCapacity);
-
-        return u_terminateChars(
-                    minimizedLocaleID,
-                    minimizedLocaleIDCapacity,
-                    localeIDLength,
-                    err);
-    }
-
-error:
-
-    if (!U_FAILURE(*err)) {
-        *err = U_ILLEGAL_ARGUMENT_ERROR;
-    }
-
-    return -1;
-
-
-}
-
-static UBool
-do_canonicalize(const char*    localeID,
-         char* buffer,
-         int32_t bufferCapacity,
-         UErrorCode* err)
-{
-    uloc_canonicalize(
-        localeID,
-        buffer,
-        bufferCapacity,
-        err);
-
-    if (*err == U_STRING_NOT_TERMINATED_WARNING ||
-        *err == U_BUFFER_OVERFLOW_ERROR) {
-        *err = U_ILLEGAL_ARGUMENT_ERROR;
-
-        return FALSE;
-    }
-    else if (U_FAILURE(*err)) {
-
-        return FALSE;
-    }
-    else {
-        return TRUE;
-    }
-}
-
-U_DRAFT int32_t U_EXPORT2
-uloc_addLikelySubtags(const char*    localeID,
-         char* maximizedLocaleID,
-         int32_t maximizedLocaleIDCapacity,
-         UErrorCode* err)
-{
-    char localeBuffer[ULOC_FULLNAME_CAPACITY];
-
-    if (!do_canonicalize(
-        localeID,
-        localeBuffer,
-        sizeof(localeBuffer),
-        err)) {
-        return -1;
-    }
-    else {
-        return _uloc_addLikelySubtags(
-                    localeBuffer,
-                    maximizedLocaleID,
-                    maximizedLocaleIDCapacity,
-                    err);
-    }    
-}
-
-U_DRAFT int32_t U_EXPORT2
-uloc_minimizeSubtags(const char*    localeID,
-         char* minimizedLocaleID,
-         int32_t minimizedLocaleIDCapacity,
-         UErrorCode* err)
-{
-    char localeBuffer[ULOC_FULLNAME_CAPACITY];
-
-    if (!do_canonicalize(
-        localeID,
-        localeBuffer,
-        sizeof(localeBuffer),
-        err)) {
-        return -1;
-    }
-    else {
-        return _uloc_minimizeSubtags(
-                    localeBuffer,
-                    minimizedLocaleID,
-                    minimizedLocaleIDCapacity,
-                    err);
-    }    
-}
-
-/*eof*/
diff -Nura icu/source/common/uloc.cpp icu_new/source/common/uloc.cpp
--- icu/source/common/uloc.cpp	1970-01-01 08:00:00.000000000 +0800
+++ icu_new/source/common/uloc.cpp	2018-05-25 19:27:41.001324562 +0800
@@ -0,0 +1,4369 @@
+/*
+**********************************************************************
+*   Copyright (C) 1997-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*
+* File ULOC.CPP
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   04/01/97    aliu        Creation.
+*   08/21/98    stephen     JDK 1.2 sync
+*   12/08/98    rtg         New Locale implementation and C API
+*   03/15/99    damiba      overhaul.
+*   04/06/99    stephen     changed setDefault() to realloc and copy
+*   06/14/99    stephen     Changed calls to ures_open for new params
+*   07/21/99    stephen     Modified setDefault() to propagate to C++
+*   05/14/04    alan        7 years later: refactored, cleaned up, fixed bugs,
+*                           brought canonicalization code into line with spec
+*****************************************************************************/
+
+/*
+   POSIX's locale format, from putil.c: [no spaces]
+
+     ll [ _CC ] [ . MM ] [ @ VV]
+
+     l = lang, C = ctry, M = charmap, V = variant
+*/
+
+#include "unicode/utypes.h"
+#include "unicode/ustring.h"
+#include "unicode/uloc.h"
+#include "unicode/ures.h"
+
+#include "putilimp.h"
+#include "ustr_imp.h"
+#include "ulocimp.h"
+#include "uresimp.h"
+#include "umutex.h"
+#include "cstring.h"
+#include "cmemory.h"
+#include "ucln_cmn.h"
+#include "locmap.h"
+#include "uarrsort.h"
+#include "uenumimp.h"
+#include "uassert.h"
+
+#include <stdio.h> /* for sprintf */
+
+/* ### Declarations **************************************************/
+
+/* Locale stuff from locid.cpp */
+U_CFUNC void locale_set_default(const char *id);
+U_CFUNC const char *locale_get_default(void);
+U_CFUNC int32_t
+locale_getKeywords(const char *localeID,
+            char prev,
+            char *keywords, int32_t keywordCapacity,
+            char *values, int32_t valuesCapacity, int32_t *valLen,
+            UBool valuesToo,
+            UErrorCode *status);
+
+/* ### Constants **************************************************/
+
+/* These strings describe the resources we attempt to load from
+ the locale ResourceBundle data file.*/
+static const char _kLanguages[]       = "Languages";
+static const char _kScripts[]         = "Scripts";
+static const char _kCountries[]       = "Countries";
+static const char _kVariants[]        = "Variants";
+static const char _kKeys[]            = "Keys";
+static const char _kTypes[]           = "Types";
+static const char _kIndexLocaleName[] = "res_index";
+static const char _kRootName[]        = "root";
+static const char _kIndexTag[]        = "InstalledLocales";
+static const char _kCurrency[]        = "currency";
+static const char _kCurrencies[]      = "Currencies";
+static char** _installedLocales = NULL;
+static int32_t _installedLocalesCount = 0;
+
+/* ### Data tables **************************************************/
+
+/**
+ * Table of language codes, both 2- and 3-letter, with preference
+ * given to 2-letter codes where possible.  Includes 3-letter codes
+ * that lack a 2-letter equivalent.
+ *
+ * This list must be in sorted order.  This list is returned directly
+ * to the user by some API.
+ *
+ * This list must be kept in sync with LANGUAGES_3, with corresponding
+ * entries matched.
+ *
+ * This table should be terminated with a NULL entry, followed by a
+ * second list, and another NULL entry.  The first list is visible to
+ * user code when this array is returned by API.  The second list
+ * contains codes we support, but do not expose through user API.
+ *
+ * Notes
+ *
+ * Tables updated per http://lcweb.loc.gov/standards/iso639-2/ to
+ * include the revisions up to 2001/7/27 *CWB*
+ *
+ * The 3 character codes are the terminology codes like RFC 3066.  This
+ * is compatible with prior ICU codes
+ *
+ * "in" "iw" "ji" "jw" & "sh" have been withdrawn but are still in the
+ * table but now at the end of the table because 3 character codes are
+ * duplicates.  This avoids bad searches going from 3 to 2 character
+ * codes.
+ *
+ * The range qaa-qtz is reserved for local use
+ */
+static const char * const LANGUAGES[] = {
+    "aa",  "ab",  "ace", "ach", "ada", "ady", "ae",  "af",  "afa",
+    "afh", "ain", "ak",  "akk", "ale", "alg", "alt", "am",  "an",  
+    "ang", "anp", "apa",
+    "ar",  "arc", "arn", "arp", "art", "arw", "as",  "ast",
+    "ath", "aus", "av",  "awa", "ay",  "az",  "ba",  "bad",
+    "bai", "bal", "ban", "bas", "bat", "be",  "bej",
+    "bem", "ber", "bg",  "bh",  "bho", "bi",  "bik", "bin",
+    "bla", "bm",  "bn",  "bnt", "bo",  "br",  "bra", "bs",
+    "btk", "bua", "bug", "byn", "ca",  "cad", "cai", "car", "cau",
+    "cch", "ce",  "ceb", "cel", "ch",  "chb", "chg", "chk", "chm",
+    "chn", "cho", "chp", "chr", "chy", "cmc", "co",  "cop",
+    "cpe", "cpf", "cpp", "cr",  "crh", "crp", "cs",  "csb", "cu",  "cus",
+    "cv",  "cy",  "da",  "dak", "dar", "day", "de",  "del", "den",
+    "dgr", "din", "doi", "dra", "dsb", "dua", "dum", "dv",  "dyu",
+    "dz",  "ee",  "efi", "egy", "eka", "el",  "elx", "en",
+    "enm", "eo",  "es",  "et",  "eu",  "ewo", "fa",
+    "fan", "fat", "ff",  "fi",  "fil", "fiu", "fj",  "fo",  "fon",
+    "fr",  "frm", "fro", "frr", "frs", "fur", "fy",  
+    "ga",  "gaa", "gay", "gba", "gd",  "gem", "gez", "gil", 
+    "gl",  "gmh", "gn",  "goh", "gon", "gor", "got", "grb", 
+    "grc", "gsw", "gu",  "gv", "gwi", 
+    "ha",  "hai", "haw", "he",  "hi",  "hil", "him",
+    "hit", "hmn", "ho",  "hr",  "hsb", "ht",  "hu",  "hup", "hy",  "hz",
+    "ia",  "iba", "id",  "ie",  "ig",  "ii",  "ijo", "ik",
+    "ilo", "inc", "ine", "inh", "io",  "ira", "iro", "is",  "it",
+    "iu",  "ja",  "jbo", "jpr", "jrb", "jv",  "ka",  "kaa", "kab",
+    "kac", "kaj", "kam", "kar", "kaw", "kbd", "kcg", "kfo", "kg",  "kha", "khi",
+    "kho", "ki",  "kj",  "kk",  "kl",  "km",  "kmb", "kn",
+    "ko",  "kok", "kos", "kpe", "kr",  "krc", "krl", "kro", "kru", "ks",
+    "ku",  "kum", "kut", "kv",  "kw",  "ky",  "la",  "lad",
+    "lah", "lam", "lb",  "lez", "lg",  "li",  "ln",  "lo",  "lol",
+    "loz", "lt",  "lu",  "lua", "lui", "lun", "luo", "lus",
+    "lv",  "mad", "mag", "mai", "mak", "man", "map", "mas",
+    "mdf", "mdr", "men", "mg",  "mga", "mh",  "mi",  "mic", "min",
+    "mis", "mk",  "mkh", "ml",  "mn",  "mnc", "mni", "mno",
+    "mo",  "moh", "mos", "mr",  "ms",  "mt",  "mul", "mun",
+    "mus", "mwl", "mwr", "my",  "myn", "myv", "na",  "nah", "nai", "nap",
+    "nb",  "nd",  "nds", "ne",  "new", "ng",  "nia", "nic",
+    "niu", "nl",  "nn",  "no",  "nog", "non", "nqo", "nr",  "nso", "nub",
+    "nv",  "nwc", "ny",  "nym", "nyn", "nyo", "nzi", "oc",  "oj",
+    "om",  "or",  "os",  "osa", "ota", "oto", "pa",  "paa",
+    "pag", "pal", "pam", "pap", "pau", "peo", "phi", "phn",
+    "pi",  "pl",  "pon", "pra", "pro", "ps",  "pt",  "qu",
+    "raj", "rap", "rar", "rm",  "rn",  "ro",  "roa", "rom",
+    "ru",  "rup", "rw",  "sa",  "sad", "sah", "sai", "sal", "sam",
+    "sas", "sat", "sc",  "scn", "sco", "sd",  "se",  "sel", "sem",
+    "sg",  "sga", "sgn", "shn", "si",  "sid", "sio", "sit",
+    "sk",  "sl",  "sla", "sm",  "sma", "smi", "smj", "smn",
+    "sms", "sn",  "snk", "so",  "sog", "son", "sq",  "sr",
+    "srn", "srr", "ss",  "ssa", "st",  "su",  "suk", "sus", "sux",
+    "sv",  "sw",  "syc", "syr", "ta",  "tai", "te",  "tem", "ter",
+    "tet", "tg",  "th",  "ti",  "tig", "tiv", "tk",  "tkl",
+    "tl",  "tlh", "tli", "tmh", "tn",  "to",  "tog", "tpi", "tr",
+    "ts",  "tsi", "tt",  "tum", "tup", "tut", "tvl", "tw",
+    "ty",  "tyv", "udm", "ug",  "uga", "uk",  "umb", "und", "ur",
+    "uz",  "vai", "ve",  "vi",  "vo",  "vot", "wa",  "wak",
+    "wal", "war", "was", "wen", "wo",  "xal", "xh",  "yao", "yap",
+    "yi",  "yo",  "ypk", "za",  "zap", "zbl", "zen", "zh",  "znd",
+    "zu",  "zun", "zxx", "zza",
+NULL,
+    "in",  "iw",  "ji",  "jw",  "sh",    /* obsolete language codes */
+NULL
+};
+static const char* const DEPRECATED_LANGUAGES[]={
+    "in", "iw", "ji", "jw", NULL, NULL
+};
+static const char* const REPLACEMENT_LANGUAGES[]={
+    "id", "he", "yi", "jv", NULL, NULL
+};
+
+/**
+ * Table of 3-letter language codes.
+ *
+ * This is a lookup table used to convert 3-letter language codes to
+ * their 2-letter equivalent, where possible.  It must be kept in sync
+ * with LANGUAGES.  For all valid i, LANGUAGES[i] must refer to the
+ * same language as LANGUAGES_3[i].  The commented-out lines are
+ * copied from LANGUAGES to make eyeballing this baby easier.
+ *
+ * Where a 3-letter language code has no 2-letter equivalent, the
+ * 3-letter code occupies both LANGUAGES[i] and LANGUAGES_3[i].
+ *
+ * This table should be terminated with a NULL entry, followed by a
+ * second list, and another NULL entry.  The two lists correspond to
+ * the two lists in LANGUAGES.
+ */
+static const char * const LANGUAGES_3[] = {
+/*  "aa",  "ab",  "ace", "ach", "ada", "ady", "ae",  "af",  "afa",    */
+    "aar", "abk", "ace", "ach", "ada", "ady", "ave", "afr", "afa",
+/*  "afh", "ain", "ak",  "akk", "ale", "alg", "alt", "am",  "an",  "ang", "anp", "apa",    */
+    "afh", "ain", "aka", "akk", "ale", "alg", "alt", "amh", "arg", "ang", "anp", "apa",
+/*  "ar",  "arc", "arn", "arp", "art", "arw", "as",  "ast",    */
+    "ara", "arc", "arn", "arp", "art", "arw", "asm", "ast",
+/*  "ath", "aus", "av",  "awa", "ay",  "az",  "ba",  "bad",    */
+    "ath", "aus", "ava", "awa", "aym", "aze", "bak", "bad",
+/*  "bai", "bal", "ban", "bas", "bat", "be",  "bej",    */
+    "bai", "bal", "ban", "bas", "bat", "bel", "bej",
+/*  "bem", "ber", "bg",  "bh",  "bho", "bi",  "bik", "bin",    */
+    "bem", "ber", "bul", "bih", "bho", "bis", "bik", "bin",
+/*  "bla", "bm",  "bn",  "bnt", "bo",  "br",  "bra", "bs",     */
+    "bla", "bam", "ben", "bnt", "bod", "bre", "bra", "bos",
+/*  "btk", "bua", "bug", "byn", "ca",  "cad", "cai", "car", "cau",    */
+    "btk", "bua", "bug", "byn", "cat", "cad", "cai", "car", "cau",
+/*  "cch", "ce",  "ceb", "cel", "ch",  "chb", "chg", "chk", "chm",    */
+    "cch", "che", "ceb", "cel", "cha", "chb", "chg", "chk", "chm",
+/*  "chn", "cho", "chp", "chr", "chy", "cmc", "co",  "cop",    */
+    "chn", "cho", "chp", "chr", "chy", "cmc", "cos", "cop",
+/*  "cpe", "cpf", "cpp", "cr",  "crh", "crp", "cs",  "csb", "cu",  "cus",    */
+    "cpe", "cpf", "cpp", "cre", "crh", "crp", "ces", "csb", "chu", "cus",
+/*  "cv",  "cy",  "da",  "dak", "dar", "day", "de",  "del", "den",    */
+    "chv", "cym", "dan", "dak", "dar", "day", "deu", "del", "den",
+/*  "dgr", "din", "doi", "dra", "dsb", "dua", "dum", "dv",  "dyu",    */
+    "dgr", "din", "doi", "dra", "dsb", "dua", "dum", "div", "dyu",
+/*  "dz",  "ee",  "efi", "egy", "eka", "el",  "elx", "en",     */
+    "dzo", "ewe", "efi", "egy", "eka", "ell", "elx", "eng",
+/*  "enm", "eo",  "es",  "et",  "eu",  "ewo", "fa",     */
+    "enm", "epo", "spa", "est", "eus", "ewo", "fas",
+/*  "fan", "fat", "ff",  "fi",  "fil", "fiu", "fj",  "fo",  "fon",    */
+    "fan", "fat", "ful", "fin", "fil", "fiu", "fij", "fao", "fon",
+/*  "fr",  "frm", "fro", "frr", "frs", "fur", "fy",  "ga",  "gaa", "gay",    */
+    "fra", "frm", "fro", "frr", "frs", "fur", "fry", "gle", "gaa", "gay",
+/*  "gba", "gd",  "gem", "gez", "gil", "gl",  "gmh", "gn",     */
+    "gba", "gla", "gem", "gez", "gil", "glg", "gmh", "grn",
+/*  "goh", "gon", "gor", "got", "grb", "grc", "gsw", "gu",  "gv",     */
+    "goh", "gon", "gor", "got", "grb", "grc", "gsw", "guj", "glv",
+/*  "gwi", "ha",  "hai", "haw", "he",  "hi",  "hil", "him",    */
+    "gwi", "hau", "hai", "haw", "heb", "hin", "hil", "him",
+/*  "hit", "hmn", "ho",  "hr",  "hsb", "ht",  "hu",  "hup", "hy",  "hz",     */
+    "hit", "hmn", "hmo", "hrv", "hsb", "hat", "hun", "hup", "hye", "her",
+/*  "ia",  "iba", "id",  "ie",  "ig",  "ii",  "ijo", "ik",     */
+    "ina", "iba", "ind", "ile", "ibo", "iii", "ijo", "ipk",
+/*  "ilo", "inc", "ine", "inh", "io",  "ira", "iro", "is",  "it",      */
+    "ilo", "inc", "ine", "inh", "ido", "ira", "iro", "isl", "ita",
+/*  "iu",  "ja",  "jbo", "jpr", "jrb", "jv",  "ka",  "kaa", "kab",   */
+    "iku", "jpn", "jbo", "jpr", "jrb", "jav", "kat", "kaa", "kab",
+/*  "kac", "kaj", "kam", "kar", "kaw", "kbd", "kcg", "kfo", "kg",  "kha", "khi",*/
+    "kac", "kaj", "kam", "kar", "kaw", "kbd", "kcg", "kfo", "kg",  "kha", "khi",
+/*  "kho", "ki",  "kj",  "kk",  "kl",  "km",  "kmb", "kn",     */
+    "kho", "kik", "kua", "kaz", "kal", "khm", "kmb", "kan",
+/*  "ko",  "kok", "kos", "kpe", "kr",  "krc", "krl", "kro", "kru", "ks",     */
+    "kor", "kok", "kos", "kpe", "kau", "krc", "krl", "kro", "kru", "kas",
+/*  "ku",  "kum", "kut", "kv",  "kw",  "ky",  "la",  "lad",    */
+    "kur", "kum", "kut", "kom", "cor", "kir", "lat", "lad",
+/*  "lah", "lam", "lb",  "lez", "lg",  "li",  "ln",  "lo",  "lol",    */
+    "lah", "lam", "ltz", "lez", "lug", "lim", "lin", "lao", "lol",
+/*  "loz", "lt",  "lu",  "lua", "lui", "lun", "luo", "lus",    */
+    "loz", "lit", "lub", "lua", "lui", "lun", "luo", "lus",
+/*  "lv",  "mad", "mag", "mai", "mak", "man", "map", "mas",    */
+    "lav", "mad", "mag", "mai", "mak", "man", "map", "mas",
+/*  "mdf", "mdr", "men", "mg",  "mga", "mh",  "mi",  "mic", "min",    */
+    "mdf", "mdr", "men", "mlg", "mga", "mah", "mri", "mic", "min",
+/*  "mis", "mk",  "mkh", "ml",  "mn",  "mnc", "mni", "mno",    */
+    "mis", "mkd", "mkh", "mal", "mon", "mnc", "mni", "mno",
+/*  "mo",  "moh", "mos", "mr",  "ms",  "mt",  "mul", "mun",    */
+    "mol", "moh", "mos", "mar", "msa", "mlt", "mul", "mun",
+/*  "mus", "mwl", "mwr", "my",  "myn", "myv", "na",  "nah", "nai", "nap",    */
+    "mus", "mwl", "mwr", "mya", "myn", "myv", "nau", "nah", "nai", "nap",
+/*  "nb",  "nd",  "nds", "ne",  "new", "ng",  "nia", "nic",    */
+    "nob", "nde", "nds", "nep", "new", "ndo", "nia", "nic",
+/*  "niu", "nl",  "nn",  "no",  "nog", "non", "nqo", "nr",  "nso", "nub",    */
+    "niu", "nld", "nno", "nor", "nog", "non", "nqo", "nbl", "nso", "nub",
+/*  "nv",  "nwc", "ny",  "nym", "nyn", "nyo", "nzi", "oc",  "oj",     */
+    "nav", "nwc", "nya", "nym", "nyn", "nyo", "nzi", "oci", "oji",
+/*  "om",  "or",  "os",  "osa", "ota", "oto", "pa",  "paa",    */
+    "orm", "ori", "oss", "osa", "ota", "oto", "pan", "paa",
+/*  "pag", "pal", "pam", "pap", "pau", "peo", "phi", "phn",    */
+    "pag", "pal", "pam", "pap", "pau", "peo", "phi", "phn",
+/*  "pi",  "pl",  "pon", "pra", "pro", "ps",  "pt",  "qu",     */
+    "pli", "pol", "pon", "pra", "pro", "pus", "por", "que",
+/*  "raj", "rap", "rar", "rm",  "rn",  "ro",  "roa", "rom",    */
+    "raj", "rap", "rar", "roh", "run", "ron", "roa", "rom",
+/*  "ru",  "rup", "rw",  "sa",  "sad", "sah", "sai", "sal", "sam",    */
+    "rus", "rup", "kin", "san", "sad", "sah", "sai", "sal", "sam",
+/*  "sas", "sat", "sc",  "scn", "sco", "sd",  "se",  "sel", "sem",    */
+    "sas", "sat", "srd", "scn", "sco", "snd", "sme", "sel", "sem",
+/*  "sg",  "sga", "sgn", "shn", "si",  "sid", "sio", "sit",    */
+    "sag", "sga", "sgn", "shn", "sin", "sid", "sio", "sit",
+/*  "sk",  "sl",  "sla", "sm",  "sma", "smi", "smj", "smn",    */
+    "slk", "slv", "sla", "smo", "sma", "smi", "smj", "smn",
+/*  "sms", "sn",  "snk", "so",  "sog", "son", "sq",  "sr",     */
+    "sms", "sna", "snk", "som", "sog", "son", "sqi", "srp",
+/*  "srn", "srr", "ss",  "ssa", "st",  "su",  "suk", "sus", "sux",    */
+    "srn", "srr", "ssw", "ssa", "sot", "sun", "suk", "sus", "sux",
+/*  "sv",  "sw",  "syc", "syr", "ta",  "tai", "te",  "tem", "ter",    */
+    "swe", "swa", "syc", "syr", "tam", "tai", "tel", "tem", "ter",
+/*  "tet", "tg",  "th",  "ti",  "tig", "tiv", "tk",  "tkl",    */
+    "tet", "tgk", "tha", "tir", "tig", "tiv", "tuk", "tkl",
+/*  "tl",  "tlh", "tli", "tmh", "tn",  "to",  "tog", "tpi", "tr",     */
+    "tgl", "tlh", "tli", "tmh", "tsn", "ton", "tog", "tpi", "tur",
+/*  "ts",  "tsi", "tt",  "tum", "tup", "tut", "tvl", "tw",     */
+    "tso", "tsi", "tat", "tum", "tup", "tut", "tvl", "twi",
+/*  "ty",  "tyv", "udm", "ug",  "uga", "uk",  "umb", "und", "ur",     */
+    "tah", "tyv", "udm", "uig", "uga", "ukr", "umb", "und", "urd",
+/*  "uz",  "vai", "ve",  "vi",  "vo",  "vot", "wa",  "wak",    */
+    "uzb", "vai", "ven", "vie", "vol", "vot", "wln", "wak",
+/*  "wal", "war", "was", "wen", "wo",  "xal", "xh",  "yao", "yap",    */
+    "wal", "war", "was", "wen", "wol", "xal", "xho", "yao", "yap",
+/*  "yi",  "yo",  "ypk", "za",  "zap", "zbl", "zen", "zh",  "znd",    */
+    "yid", "yor", "ypk", "zha", "zap", "zbl", "zen", "zho", "znd",
+/*  "zu",  "zun", "zxx", "zza",                                         */
+    "zul", "zun", "zxx", "zza",
+NULL,
+/*  "in",  "iw",  "ji",  "jw",  "sh",                          */
+    "ind", "heb", "yid", "jaw", "srp",
+NULL
+};
+
+/**
+ * Table of 2-letter country codes.
+ *
+ * This list must be in sorted order.  This list is returned directly
+ * to the user by some API.
+ *
+ * This list must be kept in sync with COUNTRIES_3, with corresponding
+ * entries matched.
+ *
+ * This table should be terminated with a NULL entry, followed by a
+ * second list, and another NULL entry.  The first list is visible to
+ * user code when this array is returned by API.  The second list
+ * contains codes we support, but do not expose through user API.
+ *
+ * Notes:
+ *
+ * ZR(ZAR) is now CD(COD) and FX(FXX) is PS(PSE) as per
+ * http://www.evertype.com/standards/iso3166/iso3166-1-en.html added
+ * new codes keeping the old ones for compatibility updated to include
+ * 1999/12/03 revisions *CWB*
+ *
+ * RO(ROM) is now RO(ROU) according to
+ * http://www.iso.org/iso/en/prods-services/iso3166ma/03updates-on-iso-3166/nlv3e-rou.html
+ */
+static const char * const COUNTRIES[] = {
+    "AD",  "AE",  "AF",  "AG",  "AI",  "AL",  "AM",  "AN",
+    "AO",  "AQ",  "AR",  "AS",  "AT",  "AU",  "AW",  "AX",  "AZ",
+    "BA",  "BB",  "BD",  "BE",  "BF",  "BG",  "BH",  "BI",
+    "BJ",  "BL",  "BM",  "BN",  "BO",  "BR",  "BS",  "BT",  "BV",
+    "BW",  "BY",  "BZ",  "CA",  "CC",  "CD",  "CF",  "CG",
+    "CH",  "CI",  "CK",  "CL",  "CM",  "CN",  "CO",  "CR",
+    "CU",  "CV",  "CX",  "CY",  "CZ",  "DE",  "DJ",  "DK",
+    "DM",  "DO",  "DZ",  "EC",  "EE",  "EG",  "EH",  "ER",
+    "ES",  "ET",  "FI",  "FJ",  "FK",  "FM",  "FO",  "FR",
+    "GA",  "GB",  "GD",  "GE",  "GF",  "GG",  "GH",  "GI",  "GL",
+    "GM",  "GN",  "GP",  "GQ",  "GR",  "GS",  "GT",  "GU",
+    "GW",  "GY",  "HK",  "HM",  "HN",  "HR",  "HT",  "HU",
+    "ID",  "IE",  "IL",  "IM",  "IN",  "IO",  "IQ",  "IR",  "IS",
+    "IT",  "JE",  "JM",  "JO",  "JP",  "KE",  "KG",  "KH",  "KI",
+    "KM",  "KN",  "KP",  "KR",  "KW",  "KY",  "KZ",  "LA",
+    "LB",  "LC",  "LI",  "LK",  "LR",  "LS",  "LT",  "LU",
+    "LV",  "LY",  "MA",  "MC",  "MD",  "ME",  "MF",  "MG",  "MH",  "MK",
+    "ML",  "MM",  "MN",  "MO",  "MP",  "MQ",  "MR",  "MS",
+    "MT",  "MU",  "MV",  "MW",  "MX",  "MY",  "MZ",  "NA",
+    "NC",  "NE",  "NF",  "NG",  "NI",  "NL",  "NO",  "NP",
+    "NR",  "NU",  "NZ",  "OM",  "PA",  "PE",  "PF",  "PG",
+    "PH",  "PK",  "PL",  "PM",  "PN",  "PR",  "PS",  "PT",
+    "PW",  "PY",  "QA",  "RE",  "RO",  "RS",  "RU",  "RW",  "SA",
+    "SB",  "SC",  "SD",  "SE",  "SG",  "SH",  "SI",  "SJ",
+    "SK",  "SL",  "SM",  "SN",  "SO",  "SR",  "ST",  "SV",
+    "SY",  "SZ",  "TC",  "TD",  "TF",  "TG",  "TH",  "TJ",
+    "TK",  "TL",  "TM",  "TN",  "TO",  "TR",  "TT",  "TV",
+    "TW",  "TZ",  "UA",  "UG",  "UM",  "US",  "UY",  "UZ",
+    "VA",  "VC",  "VE",  "VG",  "VI",  "VN",  "VU",  "WF",
+    "WS",  "YE",  "YT",  "ZA",  "ZM",  "ZW",
+NULL,
+    "FX",  "CS",  "RO",  "TP",  "YU",  "ZR",   /* obsolete country codes */
+NULL
+};
+
+static const char* const DEPRECATED_COUNTRIES[] ={
+    "BU", "CS", "DY", "FX", "HV", "NH", "RH", "TP", "YU", "ZR", NULL, NULL /* deprecated country list */
+};
+static const char* const REPLACEMENT_COUNTRIES[] = {
+/*  "BU", "CS", "DY", "FX", "HV", "NH", "RH", "TP", "YU", "ZR" */
+    "MM", "RS", "BJ", "FR", "BF", "VU", "ZW", "TL", "RS", "CD", NULL, NULL  /* replacement country codes */      
+};
+    
+/**
+ * Table of 3-letter country codes.
+ *
+ * This is a lookup table used to convert 3-letter country codes to
+ * their 2-letter equivalent.  It must be kept in sync with COUNTRIES.
+ * For all valid i, COUNTRIES[i] must refer to the same country as
+ * COUNTRIES_3[i].  The commented-out lines are copied from COUNTRIES
+ * to make eyeballing this baby easier.
+ *
+ * This table should be terminated with a NULL entry, followed by a
+ * second list, and another NULL entry.  The two lists correspond to
+ * the two lists in COUNTRIES.
+ */
+static const char * const COUNTRIES_3[] = {
+/*  "AD",  "AE",  "AF",  "AG",  "AI",  "AL",  "AM",  "AN",     */
+    "AND", "ARE", "AFG", "ATG", "AIA", "ALB", "ARM", "ANT",
+/*  "AO",  "AQ",  "AR",  "AS",  "AT",  "AU",  "AW",  "AX",  "AZ",     */
+    "AGO", "ATA", "ARG", "ASM", "AUT", "AUS", "ABW", "ALA", "AZE",
+/*  "BA",  "BB",  "BD",  "BE",  "BF",  "BG",  "BH",  "BI",     */
+    "BIH", "BRB", "BGD", "BEL", "BFA", "BGR", "BHR", "BDI",
+/*  "BJ",  "BL",  "BM",  "BN",  "BO",  "BR",  "BS",  "BT",  "BV",     */
+    "BEN", "BLM", "BMU", "BRN", "BOL", "BRA", "BHS", "BTN", "BVT",
+/*  "BW",  "BY",  "BZ",  "CA",  "CC",  "CD",  "CF",  "CG",     */
+    "BWA", "BLR", "BLZ", "CAN", "CCK", "COD", "CAF", "COG",
+/*  "CH",  "CI",  "CK",  "CL",  "CM",  "CN",  "CO",  "CR",     */
+    "CHE", "CIV", "COK", "CHL", "CMR", "CHN", "COL", "CRI",
+/*  "CU",  "CV",  "CX",  "CY",  "CZ",  "DE",  "DJ",  "DK",     */
+    "CUB", "CPV", "CXR", "CYP", "CZE", "DEU", "DJI", "DNK",
+/*  "DM",  "DO",  "DZ",  "EC",  "EE",  "EG",  "EH",  "ER",     */
+    "DMA", "DOM", "DZA", "ECU", "EST", "EGY", "ESH", "ERI",
+/*  "ES",  "ET",  "FI",  "FJ",  "FK",  "FM",  "FO",  "FR",     */
+    "ESP", "ETH", "FIN", "FJI", "FLK", "FSM", "FRO", "FRA",
+/*  "GA",  "GB",  "GD",  "GE",  "GF",  "GG",  "GH",  "GI",  "GL",     */
+    "GAB", "GBR", "GRD", "GEO", "GUF", "GGY", "GHA", "GIB", "GRL",
+/*  "GM",  "GN",  "GP",  "GQ",  "GR",  "GS",  "GT",  "GU",     */
+    "GMB", "GIN", "GLP", "GNQ", "GRC", "SGS", "GTM", "GUM",
+/*  "GW",  "GY",  "HK",  "HM",  "HN",  "HR",  "HT",  "HU",     */
+    "GNB", "GUY", "HKG", "HMD", "HND", "HRV", "HTI", "HUN",
+/*  "ID",  "IE",  "IL",  "IM",  "IN",  "IO",  "IQ",  "IR",  "IS" */
+    "IDN", "IRL", "ISR", "IMN", "IND", "IOT", "IRQ", "IRN", "ISL",
+/*  "IT",  "JE",  "JM",  "JO",  "JP",  "KE",  "KG",  "KH",  "KI",     */
+    "ITA", "JEY", "JAM", "JOR", "JPN", "KEN", "KGZ", "KHM", "KIR",
+/*  "KM",  "KN",  "KP",  "KR",  "KW",  "KY",  "KZ",  "LA",     */
+    "COM", "KNA", "PRK", "KOR", "KWT", "CYM", "KAZ", "LAO",
+/*  "LB",  "LC",  "LI",  "LK",  "LR",  "LS",  "LT",  "LU",     */
+    "LBN", "LCA", "LIE", "LKA", "LBR", "LSO", "LTU", "LUX",
+/*  "LV",  "LY",  "MA",  "MC",  "MD",  "ME",  "MF",  "MG",  "MH",  "MK",     */
+    "LVA", "LBY", "MAR", "MCO", "MDA", "MNE", "MAF", "MDG", "MHL", "MKD",
+/*  "ML",  "MM",  "MN",  "MO",  "MP",  "MQ",  "MR",  "MS",     */
+    "MLI", "MMR", "MNG", "MAC", "MNP", "MTQ", "MRT", "MSR",
+/*  "MT",  "MU",  "MV",  "MW",  "MX",  "MY",  "MZ",  "NA",     */
+    "MLT", "MUS", "MDV", "MWI", "MEX", "MYS", "MOZ", "NAM",
+/*  "NC",  "NE",  "NF",  "NG",  "NI",  "NL",  "NO",  "NP",     */
+    "NCL", "NER", "NFK", "NGA", "NIC", "NLD", "NOR", "NPL",
+/*  "NR",  "NU",  "NZ",  "OM",  "PA",  "PE",  "PF",  "PG",     */
+    "NRU", "NIU", "NZL", "OMN", "PAN", "PER", "PYF", "PNG",
+/*  "PH",  "PK",  "PL",  "PM",  "PN",  "PR",  "PS",  "PT",     */
+    "PHL", "PAK", "POL", "SPM", "PCN", "PRI", "PSE", "PRT",
+/*  "PW",  "PY",  "QA",  "RE",  "RO",  "RS",  "RU",  "RW",  "SA",     */
+    "PLW", "PRY", "QAT", "REU", "ROU", "SRB", "RUS", "RWA", "SAU",
+/*  "SB",  "SC",  "SD",  "SE",  "SG",  "SH",  "SI",  "SJ",     */
+    "SLB", "SYC", "SDN", "SWE", "SGP", "SHN", "SVN", "SJM",
+/*  "SK",  "SL",  "SM",  "SN",  "SO",  "SR",  "ST",  "SV",     */
+    "SVK", "SLE", "SMR", "SEN", "SOM", "SUR", "STP", "SLV",
+/*  "SY",  "SZ",  "TC",  "TD",  "TF",  "TG",  "TH",  "TJ",     */
+    "SYR", "SWZ", "TCA", "TCD", "ATF", "TGO", "THA", "TJK",
+/*  "TK",  "TL",  "TM",  "TN",  "TO",  "TR",  "TT",  "TV",     */
+    "TKL", "TLS", "TKM", "TUN", "TON", "TUR", "TTO", "TUV",
+/*  "TW",  "TZ",  "UA",  "UG",  "UM",  "US",  "UY",  "UZ",     */
+    "TWN", "TZA", "UKR", "UGA", "UMI", "USA", "URY", "UZB",
+/*  "VA",  "VC",  "VE",  "VG",  "VI",  "VN",  "VU",  "WF",     */
+    "VAT", "VCT", "VEN", "VGB", "VIR", "VNM", "VUT", "WLF",
+/*  "WS",  "YE",  "YT",  "ZA",  "ZM",  "ZW",          */
+    "WSM", "YEM", "MYT", "ZAF", "ZMB", "ZWE",
+NULL,
+/*  "FX",  "CS",  "RO",  "TP",  "YU",  "ZR",   */
+    "FXX", "SCG", "ROM", "TMP", "YUG", "ZAR",
+NULL
+};
+
+typedef struct CanonicalizationMap {
+    const char *id;          /* input ID */
+    const char *canonicalID; /* canonicalized output ID */
+    const char *keyword;     /* keyword, or NULL if none */
+    const char *value;       /* keyword value, or NULL if kw==NULL */
+} CanonicalizationMap;
+
+/**
+ * A map to canonicalize locale IDs.  This handles a variety of
+ * different semantic kinds of transformations.
+ */
+static const CanonicalizationMap CANONICALIZE_MAP[] = {
+    { "",               "en_US_POSIX", NULL, NULL }, /* .NET name */
+    { "C",              "en_US_POSIX", NULL, NULL }, /* POSIX name */
+    { "posix",          "en_US_POSIX", NULL, NULL }, /* POSIX name (alias of C) */
+    { "art_LOJBAN",     "jbo", NULL, NULL }, /* registered name */
+    { "az_AZ_CYRL",     "az_Cyrl_AZ", NULL, NULL }, /* .NET name */
+    { "az_AZ_LATN",     "az_Latn_AZ", NULL, NULL }, /* .NET name */
+    { "ca_ES_PREEURO",  "ca_ES", "currency", "ESP" },
+    { "cel_GAULISH",    "cel__GAULISH", NULL, NULL }, /* registered name */
+    { "de_1901",        "de__1901", NULL, NULL }, /* registered name */
+    { "de_1906",        "de__1906", NULL, NULL }, /* registered name */
+    { "de__PHONEBOOK",  "de", "collation", "phonebook" }, /* Old ICU name */
+    { "de_AT_PREEURO",  "de_AT", "currency", "ATS" },
+    { "de_DE_PREEURO",  "de_DE", "currency", "DEM" },
+    { "de_LU_PREEURO",  "de_LU", "currency", "LUF" },
+    { "el_GR_PREEURO",  "el_GR", "currency", "GRD" },
+    { "en_BOONT",       "en__BOONT", NULL, NULL }, /* registered name */
+    { "en_SCOUSE",      "en__SCOUSE", NULL, NULL }, /* registered name */
+    { "en_BE_PREEURO",  "en_BE", "currency", "BEF" },
+    { "en_IE_PREEURO",  "en_IE", "currency", "IEP" },
+    { "es__TRADITIONAL", "es", "collation", "traditional" }, /* Old ICU name */
+    { "es_ES_PREEURO",  "es_ES", "currency", "ESP" },
+    { "eu_ES_PREEURO",  "eu_ES", "currency", "ESP" },
+    { "fi_FI_PREEURO",  "fi_FI", "currency", "FIM" },
+    { "fr_BE_PREEURO",  "fr_BE", "currency", "BEF" },
+    { "fr_FR_PREEURO",  "fr_FR", "currency", "FRF" },
+    { "fr_LU_PREEURO",  "fr_LU", "currency", "LUF" },
+    { "ga_IE_PREEURO",  "ga_IE", "currency", "IEP" },
+    { "gl_ES_PREEURO",  "gl_ES", "currency", "ESP" },
+    { "hi__DIRECT",     "hi", "collation", "direct" }, /* Old ICU name */
+    { "it_IT_PREEURO",  "it_IT", "currency", "ITL" },
+    { "ja_JP_TRADITIONAL", "ja_JP", "calendar", "japanese" }, /* Old ICU name */
+    { "nb_NO_NY",       "nn_NO", NULL, NULL },  /* "markus said this was ok" :-) */
+    { "nl_BE_PREEURO",  "nl_BE", "currency", "BEF" },
+    { "nl_NL_PREEURO",  "nl_NL", "currency", "NLG" },
+    { "pt_PT_PREEURO",  "pt_PT", "currency", "PTE" },
+    { "sl_ROZAJ",       "sl__ROZAJ", NULL, NULL }, /* registered name */
+    { "sr_SP_CYRL",     "sr_Cyrl_RS", NULL, NULL }, /* .NET name */
+    { "sr_SP_LATN",     "sr_Latn_RS", NULL, NULL }, /* .NET name */
+    { "sr_YU_CYRILLIC", "sr_Cyrl_RS", NULL, NULL }, /* Linux name */
+    { "th_TH_TRADITIONAL", "th_TH", "calendar", "buddhist" }, /* Old ICU name */
+    { "uz_UZ_CYRILLIC", "uz_Cyrl_UZ", NULL, NULL }, /* Linux name */
+    { "uz_UZ_CYRL",     "uz_Cyrl_UZ", NULL, NULL }, /* .NET name */
+    { "uz_UZ_LATN",     "uz_Latn_UZ", NULL, NULL }, /* .NET name */
+    { "zh_CHS",         "zh_Hans", NULL, NULL }, /* .NET name */
+    { "zh_CHT",         "zh_Hant", NULL, NULL }, /* .NET name */
+    { "zh_GAN",         "zh__GAN", NULL, NULL }, /* registered name */
+    { "zh_GUOYU",       "zh", NULL, NULL }, /* registered name */
+    { "zh_HAKKA",       "zh__HAKKA", NULL, NULL }, /* registered name */
+    { "zh_MIN",         "zh__MIN", NULL, NULL }, /* registered name */
+    { "zh_MIN_NAN",     "zh__MINNAN", NULL, NULL }, /* registered name */
+    { "zh_WUU",         "zh__WUU", NULL, NULL }, /* registered name */
+    { "zh_XIANG",       "zh__XIANG", NULL, NULL }, /* registered name */
+    { "zh_YUE",         "zh__YUE", NULL, NULL }, /* registered name */
+};
+
+typedef struct VariantMap {
+    const char *variant;          /* input ID */
+    const char *keyword;     /* keyword, or NULL if none */
+    const char *value;       /* keyword value, or NULL if kw==NULL */
+} VariantMap;
+
+static const VariantMap VARIANT_MAP[] = {
+    { "EURO",   "currency", "EUR" },
+    { "PINYIN", "collation", "pinyin" }, /* Solaris variant */
+    { "STROKE", "collation", "stroke" }  /* Solaris variant */
+};
+
+/* ### Keywords **************************************************/
+
+#define ULOC_KEYWORD_BUFFER_LEN 25
+#define ULOC_MAX_NO_KEYWORDS 25
+
+static const char * 
+locale_getKeywordsStart(const char *localeID) {
+    const char *result = NULL;
+    if((result = uprv_strchr(localeID, '@')) != NULL) {
+        return result;
+    }
+#if (U_CHARSET_FAMILY == U_EBCDIC_FAMILY)
+    else {
+        /* We do this because the @ sign is variant, and the @ sign used on one
+        EBCDIC machine won't be compiled the same way on other EBCDIC based
+        machines. */
+        static const uint8_t ebcdicSigns[] = { 0x7C, 0x44, 0x66, 0x80, 0xAC, 0xAE, 0xAF, 0xB5, 0xEC, 0xEF, 0x00 };
+        const uint8_t *charToFind = ebcdicSigns;
+        while(*charToFind) {
+            if((result = uprv_strchr(localeID, *charToFind)) != NULL) {
+                return result;
+            }
+            charToFind++;
+        }
+    }
+#endif
+    return NULL;
+}
+
+/**
+ * @param buf buffer of size [ULOC_KEYWORD_BUFFER_LEN]
+ * @param keywordName incoming name to be canonicalized
+ * @param status return status (keyword too long)
+ * @return length of the keyword name
+ */
+static int32_t locale_canonKeywordName(char *buf, const char *keywordName, UErrorCode *status)
+{
+  int32_t i;
+  int32_t keywordNameLen = (int32_t)uprv_strlen(keywordName);
+  
+  if(keywordNameLen >= ULOC_KEYWORD_BUFFER_LEN) {
+    /* keyword name too long for internal buffer */
+    *status = U_INTERNAL_PROGRAM_ERROR;
+          return 0;
+  }
+  
+  /* normalize the keyword name */
+  for(i = 0; i < keywordNameLen; i++) {
+    buf[i] = uprv_tolower(keywordName[i]);
+  }
+  buf[i] = 0;
+    
+  return keywordNameLen;
+}
+
+typedef struct {
+    char keyword[ULOC_KEYWORD_BUFFER_LEN];
+    int32_t keywordLen;
+    const char *valueStart;
+    int32_t valueLen;
+} KeywordStruct;
+
+static int32_t U_CALLCONV
+compareKeywordStructs(const void *context, const void *left, const void *right) {
+    const char* leftString = ((const KeywordStruct *)left)->keyword;
+    const char* rightString = ((const KeywordStruct *)right)->keyword;
+    return uprv_strcmp(leftString, rightString);
+}
+
+/**
+ * Both addKeyword and addValue must already be in canonical form.
+ * Either both addKeyword and addValue are NULL, or neither is NULL.
+ * If they are not NULL they must be zero terminated.
+ * If addKeyword is not NULL is must have length small enough to fit in KeywordStruct.keyword.
+ */
+static int32_t
+_getKeywords(const char *localeID,
+             char prev,
+             char *keywords, int32_t keywordCapacity,
+             char *values, int32_t valuesCapacity, int32_t *valLen,
+             UBool valuesToo,
+             const char* addKeyword,
+             const char* addValue,
+             UErrorCode *status)
+{
+    KeywordStruct keywordList[ULOC_MAX_NO_KEYWORDS];
+    
+    int32_t maxKeywords = ULOC_MAX_NO_KEYWORDS;
+    int32_t numKeywords = 0;
+    const char* pos = localeID;
+    const char* equalSign = NULL;
+    const char* semicolon = NULL;
+    int32_t i = 0, j, n;
+    int32_t keywordsLen = 0;
+    int32_t valuesLen = 0;
+
+    if(prev == '@') { /* start of keyword definition */
+        /* we will grab pairs, trim spaces, lowercase keywords, sort and return */
+        do {
+            UBool duplicate = FALSE;
+            /* skip leading spaces */
+            while(*pos == ' ') {
+                pos++;
+            }
+            if (!*pos) { /* handle trailing "; " */
+                break;
+            }
+            if(numKeywords == maxKeywords) {
+                *status = U_INTERNAL_PROGRAM_ERROR;
+                return 0;
+            }
+            equalSign = uprv_strchr(pos, '=');
+            semicolon = uprv_strchr(pos, ';');
+            /* lack of '=' [foo@currency] is illegal */
+            /* ';' before '=' [foo@currency;collation=pinyin] is illegal */
+            if(!equalSign || (semicolon && semicolon<equalSign)) {
+                *status = U_INVALID_FORMAT_ERROR;
+                return 0;
+            }
+            /* need to normalize both keyword and keyword name */
+            if(equalSign - pos >= ULOC_KEYWORD_BUFFER_LEN) {
+                /* keyword name too long for internal buffer */
+                *status = U_INTERNAL_PROGRAM_ERROR;
+                return 0;
+            }
+            for(i = 0, n = 0; i < equalSign - pos; ++i) {
+                if (pos[i] != ' ') {
+                    keywordList[numKeywords].keyword[n++] = uprv_tolower(pos[i]);
+                }
+            }
+            keywordList[numKeywords].keyword[n] = 0;
+            keywordList[numKeywords].keywordLen = n;
+            /* now grab the value part. First we skip the '=' */
+            equalSign++;
+            /* then we leading spaces */
+            while(*equalSign == ' ') {
+                equalSign++;
+            }
+            keywordList[numKeywords].valueStart = equalSign;
+            
+            pos = semicolon;
+            i = 0;
+            if(pos) {
+                while(*(pos - i - 1) == ' ') {
+                    i++;
+                }
+                keywordList[numKeywords].valueLen = (int32_t)(pos - equalSign - i);
+                pos++;
+            } else {
+                i = (int32_t)uprv_strlen(equalSign);
+                while(equalSign[i-1] == ' ') {
+                    i--;
+                }
+                keywordList[numKeywords].valueLen = i;
+            }
+            /* If this is a duplicate keyword, then ignore it */
+            for (j=0; j<numKeywords; ++j) {
+                if (uprv_strcmp(keywordList[j].keyword, keywordList[numKeywords].keyword) == 0) {
+                    duplicate = TRUE;
+                    break;
+                }
+            }
+            if (!duplicate) {
+                ++numKeywords;
+            }
+        } while(pos);
+
+        /* Handle addKeyword/addValue. */
+        if (addKeyword != NULL) {
+            UBool duplicate = FALSE;
+            U_ASSERT(addValue != NULL);
+            /* Search for duplicate; if found, do nothing. Explicit keyword
+               overrides addKeyword. */
+            for (j=0; j<numKeywords; ++j) {
+                if (uprv_strcmp(keywordList[j].keyword, addKeyword) == 0) {
+                    duplicate = TRUE;
+                    break;
+                }
+            }
+            if (!duplicate) {
+                if (numKeywords == maxKeywords) {
+                    *status = U_INTERNAL_PROGRAM_ERROR;
+                    return 0;
+                }
+                uprv_strcpy(keywordList[numKeywords].keyword, addKeyword);
+                keywordList[numKeywords].keywordLen = (int32_t)uprv_strlen(addKeyword);
+                keywordList[numKeywords].valueStart = addValue;
+                keywordList[numKeywords].valueLen = (int32_t)uprv_strlen(addValue);
+                ++numKeywords;
+            }
+        } else {
+            U_ASSERT(addValue == NULL);
+        }
+
+        /* now we have a list of keywords */
+        /* we need to sort it */
+        uprv_sortArray(keywordList, numKeywords, sizeof(KeywordStruct), compareKeywordStructs, NULL, FALSE, status);
+        
+        /* Now construct the keyword part */
+        for(i = 0; i < numKeywords; i++) {
+            if(keywordsLen + keywordList[i].keywordLen + 1< keywordCapacity) {
+                uprv_strcpy(keywords+keywordsLen, keywordList[i].keyword);
+                if(valuesToo) {
+                    keywords[keywordsLen + keywordList[i].keywordLen] = '=';
+                } else {
+                    keywords[keywordsLen + keywordList[i].keywordLen] = 0;
+                }
+            }
+            keywordsLen += keywordList[i].keywordLen + 1;
+            if(valuesToo) {
+                if(keywordsLen + keywordList[i].valueLen < keywordCapacity) {
+                    uprv_strncpy(keywords+keywordsLen, keywordList[i].valueStart, keywordList[i].valueLen);
+                }
+                keywordsLen += keywordList[i].valueLen;
+                
+                if(i < numKeywords - 1) {
+                    if(keywordsLen < keywordCapacity) {       
+                        keywords[keywordsLen] = ';';
+                    }
+                    keywordsLen++;
+                }
+            }
+            if(values) {
+                if(valuesLen + keywordList[i].valueLen + 1< valuesCapacity) {
+                    uprv_strcpy(values+valuesLen, keywordList[i].valueStart);
+                    values[valuesLen + keywordList[i].valueLen] = 0;
+                }
+                valuesLen += keywordList[i].valueLen + 1;
+            }
+        }
+        if(values) {
+            values[valuesLen] = 0;
+            if(valLen) {
+                *valLen = valuesLen;
+            }
+        }
+        return u_terminateChars(keywords, keywordCapacity, keywordsLen, status);   
+    } else {
+        return 0;
+    }
+}
+
+U_CFUNC int32_t
+locale_getKeywords(const char *localeID,
+                   char prev,
+                   char *keywords, int32_t keywordCapacity,
+                   char *values, int32_t valuesCapacity, int32_t *valLen,
+                   UBool valuesToo,
+                   UErrorCode *status) {
+    return _getKeywords(localeID, prev, keywords, keywordCapacity,
+                        values, valuesCapacity, valLen, valuesToo,
+                        NULL, NULL, status);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getKeywordValue(const char* localeID,
+                     const char* keywordName,
+                     char* buffer, int32_t bufferCapacity,
+                     UErrorCode* status)
+{ 
+    const char* nextSeparator = NULL;
+    char keywordNameBuffer[ULOC_KEYWORD_BUFFER_LEN];
+    char localeKeywordNameBuffer[ULOC_KEYWORD_BUFFER_LEN];
+    int32_t i = 0;
+    int32_t result = 0;
+
+    if(status && U_SUCCESS(*status) && localeID) {
+    
+      const char* startSearchHere = uprv_strchr(localeID, '@'); /* TODO: REVISIT: shouldn't this be locale_getKeywordsStart ? */
+      if(startSearchHere == NULL) {
+          /* no keywords, return at once */
+          return 0;
+      }
+
+      locale_canonKeywordName(keywordNameBuffer, keywordName, status);
+      if(U_FAILURE(*status)) {
+        return 0;
+      }
+    
+      /* find the first keyword */
+      while(startSearchHere) {
+          startSearchHere++;
+          /* skip leading spaces (allowed?) */
+          while(*startSearchHere == ' ') {
+              startSearchHere++;
+          }
+          nextSeparator = uprv_strchr(startSearchHere, '=');
+          /* need to normalize both keyword and keyword name */
+          if(!nextSeparator) {
+              break;
+          }
+          if(nextSeparator - startSearchHere >= ULOC_KEYWORD_BUFFER_LEN) {
+              /* keyword name too long for internal buffer */
+              *status = U_INTERNAL_PROGRAM_ERROR;
+              return 0;
+          }
+          for(i = 0; i < nextSeparator - startSearchHere; i++) {
+              localeKeywordNameBuffer[i] = uprv_tolower(startSearchHere[i]);
+          }
+          /* trim trailing spaces */
+          while(startSearchHere[i-1] == ' ') {
+              i--;
+          }
+          localeKeywordNameBuffer[i] = 0;
+        
+          startSearchHere = uprv_strchr(nextSeparator, ';');
+        
+          if(uprv_strcmp(keywordNameBuffer, localeKeywordNameBuffer) == 0) {
+              nextSeparator++;
+              while(*nextSeparator == ' ') {
+                  nextSeparator++;
+              }
+              /* we actually found the keyword. Copy the value */
+              if(startSearchHere && startSearchHere - nextSeparator < bufferCapacity) {
+                  while(*(startSearchHere-1) == ' ') {
+                      startSearchHere--;
+                  }
+                  uprv_strncpy(buffer, nextSeparator, startSearchHere - nextSeparator);
+                  result = u_terminateChars(buffer, bufferCapacity, (int32_t)(startSearchHere - nextSeparator), status);
+              } else if(!startSearchHere && (int32_t)uprv_strlen(nextSeparator) < bufferCapacity) { /* last item in string */
+                  i = (int32_t)uprv_strlen(nextSeparator);
+                  while(nextSeparator[i - 1] == ' ') {
+                      i--;
+                  }
+                  uprv_strncpy(buffer, nextSeparator, i);
+                  result = u_terminateChars(buffer, bufferCapacity, i, status);
+              } else {
+                  /* give a bigger buffer, please */
+                  *status = U_BUFFER_OVERFLOW_ERROR;
+                  if(startSearchHere) {
+                      result = (int32_t)(startSearchHere - nextSeparator);
+                  } else {
+                      result = (int32_t)uprv_strlen(nextSeparator); 
+                  }
+              }
+              return result;
+          }
+      }
+    }
+    return 0;
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_setKeywordValue(const char* keywordName,
+                     const char* keywordValue,
+                     char* buffer, int32_t bufferCapacity,
+                     UErrorCode* status)
+{
+    /* TODO: sorting. removal. */
+    int32_t keywordNameLen;
+    int32_t keywordValueLen;
+    int32_t bufLen;
+    int32_t needLen = 0;
+    int32_t foundValueLen;
+    int32_t keywordAtEnd = 0; /* is the keyword at the end of the string? */
+    char keywordNameBuffer[ULOC_KEYWORD_BUFFER_LEN];
+    char localeKeywordNameBuffer[ULOC_KEYWORD_BUFFER_LEN];
+    int32_t i = 0;
+    int32_t rc;
+    char* nextSeparator = NULL;
+    char* nextEqualsign = NULL;
+    char* startSearchHere = NULL;
+    char* keywordStart = NULL;
+    char *insertHere = NULL;
+    if(U_FAILURE(*status)) { 
+        return -1; 
+    }
+    if(bufferCapacity>1) {
+        bufLen = (int32_t)uprv_strlen(buffer);
+    } else {
+        *status = U_ILLEGAL_ARGUMENT_ERROR;
+        return 0;
+    }
+    if(bufferCapacity<bufLen) {
+        /* The capacity is less than the length?! Is this NULL terminated? */
+        *status = U_ILLEGAL_ARGUMENT_ERROR;
+        return 0;
+    }
+    if(keywordValue && !*keywordValue) { 
+        keywordValue = NULL;
+    }
+    if(keywordValue) {
+        keywordValueLen = (int32_t)uprv_strlen(keywordValue);
+    } else { 
+        keywordValueLen = 0;
+    }
+    keywordNameLen = locale_canonKeywordName(keywordNameBuffer, keywordName, status);
+    if(U_FAILURE(*status)) {
+        return 0;
+    }
+    startSearchHere = (char*)locale_getKeywordsStart(buffer);
+    if(startSearchHere == NULL || (startSearchHere[1]==0)) {
+        if(!keywordValue) { /* no keywords = nothing to remove */
+            return bufLen; 
+        }
+
+        needLen = bufLen+1+keywordNameLen+1+keywordValueLen;
+        if(startSearchHere) { /* had a single @ */ 
+            needLen--; /* already had the @ */
+            /* startSearchHere points at the @ */
+        } else {
+            startSearchHere=buffer+bufLen;
+        }
+        if(needLen >= bufferCapacity) {
+            *status = U_BUFFER_OVERFLOW_ERROR;
+            return needLen; /* no change */
+        }
+        *startSearchHere = '@';
+        startSearchHere++;
+        uprv_strcpy(startSearchHere, keywordNameBuffer);
+        startSearchHere += keywordNameLen;
+        *startSearchHere = '=';
+        startSearchHere++;
+        uprv_strcpy(startSearchHere, keywordValue);
+        startSearchHere+=keywordValueLen;
+        return needLen;
+    } /* end shortcut - no @ */
+    
+    keywordStart = startSearchHere;
+    /* search for keyword */
+    while(keywordStart) {
+        keywordStart++;
+        /* skip leading spaces (allowed?) */
+        while(*keywordStart == ' ') {
+            keywordStart++;
+        }
+        nextEqualsign = uprv_strchr(keywordStart, '=');
+        /* need to normalize both keyword and keyword name */
+        if(!nextEqualsign) {
+            break;
+        }
+        if(nextEqualsign - keywordStart >= ULOC_KEYWORD_BUFFER_LEN) {
+            /* keyword name too long for internal buffer */
+            *status = U_INTERNAL_PROGRAM_ERROR;
+            return 0;
+        }
+        for(i = 0; i < nextEqualsign - keywordStart; i++) {
+            localeKeywordNameBuffer[i] = uprv_tolower(keywordStart[i]);
+        }
+        /* trim trailing spaces */
+        while(keywordStart[i-1] == ' ') {
+            i--;
+        }
+        localeKeywordNameBuffer[i] = 0;
+
+        nextSeparator = uprv_strchr(nextEqualsign, ';');
+        rc = uprv_strcmp(keywordNameBuffer, localeKeywordNameBuffer);
+        if(rc == 0) {
+            nextEqualsign++;
+            while(*nextEqualsign == ' ') {
+                nextEqualsign++;
+            }
+            /* we actually found the keyword. Change the value */
+            if (nextSeparator) {
+                keywordAtEnd = 0;
+                foundValueLen = (int32_t)(nextSeparator - nextEqualsign);
+            } else {
+                keywordAtEnd = 1;
+                foundValueLen = (int32_t)uprv_strlen(nextEqualsign);
+            }
+            if(keywordValue) { /* adding a value - not removing */
+              if(foundValueLen == keywordValueLen) {
+                uprv_strncpy(nextEqualsign, keywordValue, keywordValueLen);
+                return bufLen; /* no change in size */
+              } else if(foundValueLen > keywordValueLen) {
+                int32_t delta = foundValueLen - keywordValueLen;
+                if(nextSeparator) { /* RH side */
+                  uprv_memmove(nextSeparator - delta, nextSeparator, bufLen-(nextSeparator-buffer));
+                }
+                uprv_strncpy(nextEqualsign, keywordValue, keywordValueLen);
+                bufLen -= delta;
+                buffer[bufLen]=0;
+                return bufLen;
+              } else { /* FVL < KVL */
+                int32_t delta = keywordValueLen - foundValueLen;
+                if((bufLen+delta) >= bufferCapacity) {
+                  *status = U_BUFFER_OVERFLOW_ERROR;
+                  return bufLen+delta;
+                }
+                if(nextSeparator) { /* RH side */
+                  uprv_memmove(nextSeparator+delta,nextSeparator, bufLen-(nextSeparator-buffer));
+                }
+                uprv_strncpy(nextEqualsign, keywordValue, keywordValueLen);
+                bufLen += delta;
+                buffer[bufLen]=0;
+                return bufLen;
+              }
+            } else { /* removing a keyword */
+              if(keywordAtEnd) {
+                /* zero out the ';' or '@' just before startSearchhere */
+                keywordStart[-1] = 0;
+                return (int32_t)((keywordStart-buffer)-1); /* (string length without keyword) minus separator */
+              } else {
+                uprv_memmove(keywordStart, nextSeparator+1, bufLen-((nextSeparator+1)-buffer));
+                keywordStart[bufLen-((nextSeparator+1)-buffer)]=0;
+                return (int32_t)(bufLen-((nextSeparator+1)-keywordStart));
+              }
+            }
+        } else if(rc<0){ /* end match keyword */
+          /* could insert at this location. */
+          insertHere = keywordStart;
+        }
+        keywordStart = nextSeparator;
+    } /* end loop searching */
+    
+    if(!keywordValue) {
+      return bufLen; /* removal of non-extant keyword - no change */
+    }
+
+    /* we know there is at least one keyword. */
+    needLen = bufLen+1+keywordNameLen+1+keywordValueLen;
+    if(needLen >= bufferCapacity) {
+        *status = U_BUFFER_OVERFLOW_ERROR;
+        return needLen; /* no change */
+    }
+    
+    if(insertHere) {
+      uprv_memmove(insertHere+(1+keywordNameLen+1+keywordValueLen), insertHere, bufLen-(insertHere-buffer));
+      keywordStart = insertHere;
+    } else {
+      keywordStart = buffer+bufLen;
+      *keywordStart = ';';
+      keywordStart++;
+    }
+    uprv_strncpy(keywordStart, keywordNameBuffer, keywordNameLen);
+    keywordStart += keywordNameLen;
+    *keywordStart = '=';
+    keywordStart++;
+    uprv_strncpy(keywordStart, keywordValue, keywordValueLen); /* terminates. */
+    keywordStart+=keywordValueLen;
+    if(insertHere) {
+      *keywordStart = ';';
+      keywordStart++;
+    }
+    buffer[needLen]=0;
+    return needLen;
+}
+
+/* ### ID parsing implementation **************************************************/
+
+/*returns TRUE if a is an ID separator FALSE otherwise*/
+#define _isIDSeparator(a) (a == '_' || a == '-')
+
+#define _isPrefixLetter(a) ((a=='x')||(a=='X')||(a=='i')||(a=='I'))
+
+/*returns TRUE if one of the special prefixes is here (s=string)
+  'x-' or 'i-' */
+#define _isIDPrefix(s) (_isPrefixLetter(s[0])&&_isIDSeparator(s[1]))
+
+/* Dot terminates it because of POSIX form  where dot precedes the codepage
+ * except for variant
+ */
+#define _isTerminator(a)  ((a==0)||(a=='.')||(a=='@'))
+
+static char* _strnchr(const char* str, int32_t len, char c) {
+    U_ASSERT(str != 0 && len >= 0);
+    while (len-- != 0) {
+        char d = *str;
+        if (d == c) {
+            return (char*) str;
+        } else if (d == 0) {
+            break;
+        }
+        ++str;
+    }
+    return NULL;
+}
+
+/**
+ * Lookup 'key' in the array 'list'.  The array 'list' should contain
+ * a NULL entry, followed by more entries, and a second NULL entry.
+ *
+ * The 'list' param should be LANGUAGES, LANGUAGES_3, COUNTRIES, or
+ * COUNTRIES_3.
+ */
+static int16_t _findIndex(const char* const* list, const char* key)
+{
+    const char* const* anchor = list;
+    int32_t pass = 0;
+
+    /* Make two passes through two NULL-terminated arrays at 'list' */
+    while (pass++ < 2) {
+        while (*list) {
+            if (uprv_strcmp(key, *list) == 0) {
+                return (int16_t)(list - anchor);
+            }
+            list++;
+        }
+        ++list;     /* skip final NULL *CWB*/
+    }
+    return -1;
+}
+
+/* count the length of src while copying it to dest; return strlen(src) */
+static U_INLINE int32_t
+_copyCount(char *dest, int32_t destCapacity, const char *src) {
+    const char *anchor;
+    char c;
+
+    anchor=src;
+    for(;;) {
+        if((c=*src)==0) {
+            return (int32_t)(src-anchor);
+        }
+        if(destCapacity<=0) {
+            return (int32_t)((src-anchor)+uprv_strlen(src));
+        }
+        ++src;
+        *dest++=c;
+        --destCapacity;
+    }
+}
+
+static const char* 
+uloc_getCurrentCountryID(const char* oldID){
+    int32_t offset = _findIndex(DEPRECATED_COUNTRIES, oldID);
+    if (offset >= 0) {
+        return REPLACEMENT_COUNTRIES[offset];
+    }
+    return oldID;
+}
+static const char* 
+uloc_getCurrentLanguageID(const char* oldID){
+    int32_t offset = _findIndex(DEPRECATED_LANGUAGES, oldID);
+    if (offset >= 0) {
+        return REPLACEMENT_LANGUAGES[offset];
+    }
+    return oldID;        
+}
+/*
+ * the internal functions _getLanguage(), _getCountry(), _getVariant()
+ * avoid duplicating code to handle the earlier locale ID pieces
+ * in the functions for the later ones by
+ * setting the *pEnd pointer to where they stopped parsing
+ *
+ * TODO try to use this in Locale
+ */
+static int32_t
+_getLanguage(const char *localeID,
+             char *language, int32_t languageCapacity,
+             const char **pEnd) {
+    int32_t i=0;
+    int32_t offset;
+    char lang[4]={ 0, 0, 0, 0 }; /* temporary buffer to hold language code for searching */
+
+    /* if it starts with i- or x- then copy that prefix */
+    if(_isIDPrefix(localeID)) {
+        if(i<languageCapacity) {
+            language[i]=(char)uprv_tolower(*localeID);
+        }
+        if(i<languageCapacity) {
+            language[i+1]='-';
+        }
+        i+=2;
+        localeID+=2;
+    }
+    
+    /* copy the language as far as possible and count its length */
+    while(!_isTerminator(*localeID) && !_isIDSeparator(*localeID)) {
+        if(i<languageCapacity) {
+            language[i]=(char)uprv_tolower(*localeID);
+        }
+        if(i<3) {
+            lang[i]=(char)uprv_tolower(*localeID);
+        }
+        i++;
+        localeID++;
+    }
+
+    if(i==3) {
+        /* convert 3 character code to 2 character code if possible *CWB*/
+        offset=_findIndex(LANGUAGES_3, lang);
+        if(offset>=0) {
+            i=_copyCount(language, languageCapacity, LANGUAGES[offset]);
+        }
+    }
+
+    if(pEnd!=NULL) {
+        *pEnd=localeID;
+    }
+    return i;
+}
+
+static int32_t
+_getScript(const char *localeID,
+            char *script, int32_t scriptCapacity,
+            const char **pEnd)
+{
+    int32_t idLen = 0;
+
+    if (pEnd != NULL) {
+        *pEnd = localeID;
+    }
+
+    /* copy the second item as far as possible and count its length */
+    while(!_isTerminator(localeID[idLen]) && !_isIDSeparator(localeID[idLen])) {
+        idLen++;
+    }
+
+    /* If it's exactly 4 characters long, then it's a script and not a country. */
+    if (idLen == 4) {
+        int32_t i;
+        if (pEnd != NULL) {
+            *pEnd = localeID+idLen;
+        }
+        if(idLen > scriptCapacity) {
+            idLen = scriptCapacity;
+        }
+        if (idLen >= 1) {
+            script[0]=(char)uprv_toupper(*(localeID++));
+        }
+        for (i = 1; i < idLen; i++) {
+            script[i]=(char)uprv_tolower(*(localeID++));
+        }
+    }
+    else {
+        idLen = 0;
+    }
+    return idLen;
+}
+
+static int32_t
+_getCountry(const char *localeID,
+            char *country, int32_t countryCapacity,
+            const char **pEnd)
+{
+    int32_t i=0;
+    char cnty[ULOC_COUNTRY_CAPACITY]={ 0, 0, 0, 0 };
+    int32_t offset;
+
+    /* copy the country as far as possible and count its length */
+    while(!_isTerminator(*localeID) && !_isIDSeparator(*localeID)) {
+        if(i<countryCapacity) {
+            country[i]=(char)uprv_toupper(*localeID);
+        }
+        if(i<(ULOC_COUNTRY_CAPACITY-1)) {   /*CWB*/
+            cnty[i]=(char)uprv_toupper(*localeID);
+        }
+        i++;
+        localeID++;
+    }
+
+    /* convert 3 character code to 2 character code if possible *CWB*/
+    if(i==3) {
+        offset=_findIndex(COUNTRIES_3, cnty);
+        if(offset>=0) {
+            i=_copyCount(country, countryCapacity, COUNTRIES[offset]);
+        }
+    }
+
+    if(pEnd!=NULL) {
+        *pEnd=localeID;
+    }
+    return i;
+}
+
+/**
+ * @param needSeparator if true, then add leading '_' if any variants
+ * are added to 'variant'
+ */
+static int32_t
+_getVariantEx(const char *localeID,
+              char prev,
+              char *variant, int32_t variantCapacity,
+              UBool needSeparator) {
+    int32_t i=0;
+
+    /* get one or more variant tags and separate them with '_' */
+    if(_isIDSeparator(prev)) {
+        /* get a variant string after a '-' or '_' */
+        while(!_isTerminator(*localeID)) {
+            if (needSeparator) {
+                if (i<variantCapacity) {
+                    variant[i] = '_';
+                }
+                ++i;
+                needSeparator = FALSE;
+            }
+            if(i<variantCapacity) {
+                variant[i]=(char)uprv_toupper(*localeID);
+                if(variant[i]=='-') {
+                    variant[i]='_';
+                }
+            }
+            i++;
+            localeID++;
+        }
+    }
+
+    /* if there is no variant tag after a '-' or '_' then look for '@' */
+    if(i==0) {
+        if(prev=='@') {
+            /* keep localeID */
+        } else if((localeID=locale_getKeywordsStart(localeID))!=NULL) {
+            ++localeID; /* point after the '@' */
+        } else {
+            return 0;
+        }
+        while(!_isTerminator(*localeID)) {
+            if (needSeparator) {
+                if (i<variantCapacity) {
+                    variant[i] = '_';
+                }
+                ++i;
+                needSeparator = FALSE;
+            }
+            if(i<variantCapacity) {
+                variant[i]=(char)uprv_toupper(*localeID);
+                if(variant[i]=='-' || variant[i]==',') {
+                    variant[i]='_';
+                }
+            }
+            i++;
+            localeID++;
+        }
+    }
+    
+    return i;
+}
+
+static int32_t
+_getVariant(const char *localeID,
+            char prev,
+            char *variant, int32_t variantCapacity) {
+    return _getVariantEx(localeID, prev, variant, variantCapacity, FALSE);
+}
+
+/**
+ * Delete ALL instances of a variant from the given list of one or
+ * more variants.  Example: "FOO_EURO_BAR_EURO" => "FOO_BAR".
+ * @param variants the source string of one or more variants,
+ * separated by '_'.  This will be MODIFIED IN PLACE.  Not zero
+ * terminated; if it is, trailing zero will NOT be maintained.
+ * @param variantsLen length of variants
+ * @param toDelete variant to delete, without separators, e.g.  "EURO"
+ * or "PREEURO"; not zero terminated
+ * @param toDeleteLen length of toDelete
+ * @return number of characters deleted from variants
+ */
+static int32_t
+_deleteVariant(char* variants, int32_t variantsLen,
+               const char* toDelete, int32_t toDeleteLen)
+{
+    int32_t delta = 0; /* number of chars deleted */
+    for (;;) {
+        UBool flag = FALSE;
+        if (variantsLen < toDeleteLen) {
+            return delta;
+        }
+        if (uprv_strncmp(variants, toDelete, toDeleteLen) == 0 &&
+            (variantsLen == toDeleteLen ||
+             (flag=(variants[toDeleteLen] == '_'))))
+        {
+            int32_t d = toDeleteLen + (flag?1:0);
+            variantsLen -= d;
+            delta += d;
+            if (variantsLen > 0) {
+                uprv_memmove(variants, variants+d, variantsLen);
+            }
+        } else {
+            char* p = _strnchr(variants, variantsLen, '_');
+            if (p == NULL) {
+                return delta;
+            }
+            ++p;
+            variantsLen -= (int32_t)(p - variants);
+            variants = p;
+        }
+    }
+}
+
+/* Keyword enumeration */
+
+typedef struct UKeywordsContext {
+    char* keywords;
+    char* current;
+} UKeywordsContext;
+
+static void U_CALLCONV
+uloc_kw_closeKeywords(UEnumeration *enumerator) {
+    uprv_free(((UKeywordsContext *)enumerator->context)->keywords);
+    uprv_free(enumerator->context);
+    uprv_free(enumerator);
+}
+
+static int32_t U_CALLCONV
+uloc_kw_countKeywords(UEnumeration *en, UErrorCode *status) {
+    char *kw = ((UKeywordsContext *)en->context)->keywords;
+    int32_t result = 0;
+    while(*kw) {
+        result++;
+        kw += uprv_strlen(kw)+1;
+    }
+    return result;
+}
+
+static const char* U_CALLCONV 
+uloc_kw_nextKeyword(UEnumeration* en,
+                    int32_t* resultLength,
+                    UErrorCode* status) {
+    const char* result = ((UKeywordsContext *)en->context)->current;
+    int32_t len = 0;
+    if(*result) {
+        len = (int32_t)uprv_strlen(((UKeywordsContext *)en->context)->current);
+        ((UKeywordsContext *)en->context)->current += len+1;
+    } else {
+        result = NULL;
+    }
+    if (resultLength) {
+        *resultLength = len;
+    }
+    return result;
+}
+
+static void U_CALLCONV 
+uloc_kw_resetKeywords(UEnumeration* en, 
+                      UErrorCode* status) {
+    ((UKeywordsContext *)en->context)->current = ((UKeywordsContext *)en->context)->keywords;
+}
+
+static const UEnumeration gKeywordsEnum = {
+    NULL,
+    NULL,
+    uloc_kw_closeKeywords,
+    uloc_kw_countKeywords,
+    uenum_unextDefault,
+    uloc_kw_nextKeyword,
+    uloc_kw_resetKeywords
+};
+
+U_CAPI UEnumeration* U_EXPORT2
+uloc_openKeywordList(const char *keywordList, int32_t keywordListSize, UErrorCode* status)
+{
+    UKeywordsContext *myContext = NULL;
+    UEnumeration *result = NULL;
+
+    if(U_FAILURE(*status)) {
+        return NULL;
+    }
+    result = (UEnumeration *)uprv_malloc(sizeof(UEnumeration));
+    /* Null pointer test */
+    if (result == NULL) {
+        *status = U_MEMORY_ALLOCATION_ERROR;
+        return NULL;
+    }
+    uprv_memcpy(result, &gKeywordsEnum, sizeof(UEnumeration));
+    myContext = static_cast<UKeywordsContext *>(uprv_malloc(sizeof(UKeywordsContext)));
+    if (myContext == NULL) {
+        *status = U_MEMORY_ALLOCATION_ERROR;
+        uprv_free(result);
+        return NULL;
+    }
+    myContext->keywords = (char *)uprv_malloc(keywordListSize+1);
+    uprv_memcpy(myContext->keywords, keywordList, keywordListSize);
+    myContext->keywords[keywordListSize] = 0;
+    myContext->current = myContext->keywords;
+    result->context = myContext;
+    return result;
+}
+
+U_CAPI UEnumeration* U_EXPORT2
+uloc_openKeywords(const char* localeID,
+                        UErrorCode* status) 
+{
+    int32_t i=0;
+    char keywords[256];
+    int32_t keywordsCapacity = 256;
+    if(status==NULL || U_FAILURE(*status)) {
+        return 0;
+    }
+    
+    if(localeID==NULL) {
+        localeID=uloc_getDefault();
+    }
+
+    /* Skip the language */
+    _getLanguage(localeID, NULL, 0, &localeID);
+    if(_isIDSeparator(*localeID)) {
+        const char *scriptID;
+        /* Skip the script if available */
+        _getScript(localeID+1, NULL, 0, &scriptID);
+        if(scriptID != localeID+1) {
+            /* Found optional script */
+            localeID = scriptID;
+        }
+        /* Skip the Country */
+        if (_isIDSeparator(*localeID)) {
+            _getCountry(localeID+1, NULL, 0, &localeID);
+            if(_isIDSeparator(*localeID)) {
+                _getVariant(localeID+1, *localeID, NULL, 0);
+            }
+        }
+    }
+
+    /* keywords are located after '@' */
+    if((localeID = locale_getKeywordsStart(localeID)) != NULL) {
+        i=locale_getKeywords(localeID+1, '@', keywords, keywordsCapacity, NULL, 0, NULL, FALSE, status);
+    }
+
+    if(i) {
+        return uloc_openKeywordList(keywords, i, status);
+    } else {
+        return NULL;
+    }
+}
+
+
+/* bit-flags for 'options' parameter of _canonicalize */
+#define _ULOC_STRIP_KEYWORDS 0x2
+#define _ULOC_CANONICALIZE   0x1
+
+#define OPTION_SET(options, mask) ((options & mask) != 0)
+
+static const char i_default[] = {'i', '-', 'd', 'e', 'f', 'a', 'u', 'l', 't'};
+#define I_DEFAULT_LENGTH (sizeof i_default / sizeof i_default[0])
+
+/**
+ * Canonicalize the given localeID, to level 1 or to level 2,
+ * depending on the options.  To specify level 1, pass in options=0.
+ * To specify level 2, pass in options=_ULOC_CANONICALIZE.
+ *
+ * This is the code underlying uloc_getName and uloc_canonicalize.
+ */
+static int32_t
+_canonicalize(const char* localeID,
+              char* result,
+              int32_t resultCapacity,
+              uint32_t options,
+              UErrorCode* err) {
+    int32_t j, len, fieldCount=0, scriptSize=0, variantSize=0, nameCapacity;
+    char localeBuffer[ULOC_FULLNAME_CAPACITY];
+    const char* origLocaleID;
+    const char* keywordAssign = NULL;
+    const char* separatorIndicator = NULL;
+    const char* addKeyword = NULL;
+    const char* addValue = NULL;
+    char* name;
+    char* variant = NULL; /* pointer into name, or NULL */
+
+    if (U_FAILURE(*err)) {
+        return 0;
+    }
+    
+    if (localeID==NULL) {
+        localeID=uloc_getDefault();
+    }
+    origLocaleID=localeID;
+
+    /* if we are doing a full canonicalization, then put results in
+       localeBuffer, if necessary; otherwise send them to result. */
+    if (OPTION_SET(options, _ULOC_CANONICALIZE) &&
+        (result == NULL || resultCapacity < (int32_t)sizeof(localeBuffer))) {
+        name = localeBuffer;
+        nameCapacity = sizeof(localeBuffer);
+    } else {
+        name = result;
+        nameCapacity = resultCapacity;
+    }
+
+    /* get all pieces, one after another, and separate with '_' */
+    len=_getLanguage(localeID, name, nameCapacity, &localeID);
+
+    if(len == I_DEFAULT_LENGTH && uprv_strncmp(origLocaleID, i_default, len) == 0) {
+        const char *d = uloc_getDefault();
+        
+        len = uprv_strlen(d);
+
+        if (name != NULL) {
+            uprv_strncpy(name, d, len);
+        }
+    } else if(_isIDSeparator(*localeID)) {
+        const char *scriptID;
+
+        ++fieldCount;
+        if(len<nameCapacity) {
+            name[len]='_';
+        }
+        ++len;
+
+        scriptSize=_getScript(localeID+1, name+len, nameCapacity-len, &scriptID);
+        if(scriptSize > 0) {
+            /* Found optional script */
+            localeID = scriptID;
+            ++fieldCount;
+            len+=scriptSize;
+            if (_isIDSeparator(*localeID)) {
+                /* If there is something else, then we add the _ */
+                if(len<nameCapacity) {
+                    name[len]='_';
+                }
+                ++len;
+            }
+        }
+
+        if (_isIDSeparator(*localeID)) {
+            len+=_getCountry(localeID+1, name+len, nameCapacity-len, &localeID);
+            if(_isIDSeparator(*localeID)) {
+                ++fieldCount;
+                if(len<nameCapacity) {
+                    name[len]='_';
+                }
+                ++len;
+                variantSize = _getVariant(localeID+1, *localeID, name+len, nameCapacity-len);
+                if (variantSize > 0) {
+                    variant = name+len;
+                    len += variantSize;
+                    localeID += variantSize + 1; /* skip '_' and variant */
+                }
+            }
+        }
+    }
+
+    /* Copy POSIX-style charset specifier, if any [mr.utf8] */
+    if (!OPTION_SET(options, _ULOC_CANONICALIZE) && *localeID == '.') {
+        UBool done = FALSE;
+        do {
+            char c = *localeID;
+            switch (c) {
+            case 0:
+            case '@':
+                done = TRUE;
+                break;
+            default:
+                if (len<nameCapacity) {
+                    name[len] = c;
+                }
+                ++len;
+                ++localeID;
+                break;
+            }
+        } while (!done);
+    }
+
+    /* Scan ahead to next '@' and determine if it is followed by '=' and/or ';'
+       After this, localeID either points to '@' or is NULL */
+    if ((localeID=locale_getKeywordsStart(localeID))!=NULL) {
+        keywordAssign = uprv_strchr(localeID, '=');
+        separatorIndicator = uprv_strchr(localeID, ';');
+    }
+
+    /* Copy POSIX-style variant, if any [mr@FOO] */
+    if (!OPTION_SET(options, _ULOC_CANONICALIZE) &&
+        localeID != NULL && keywordAssign == NULL) {
+        for (;;) {
+            char c = *localeID;
+            if (c == 0) {
+                break;
+            }
+            if (len<nameCapacity) {
+                name[len] = c;
+            }
+            ++len;
+            ++localeID;
+        }
+    }
+
+    if (OPTION_SET(options, _ULOC_CANONICALIZE)) {
+        /* Handle @FOO variant if @ is present and not followed by = */
+        if (localeID!=NULL && keywordAssign==NULL) {
+            int32_t posixVariantSize;
+            /* Add missing '_' if needed */
+            if (fieldCount < 2 || (fieldCount < 3 && scriptSize > 0)) {
+                do {
+                    if(len<nameCapacity) {
+                        name[len]='_';
+                    }
+                    ++len;
+                    ++fieldCount;
+                } while(fieldCount<2);
+            }
+            posixVariantSize = _getVariantEx(localeID+1, '@', name+len, nameCapacity-len,
+                                             (UBool)(variantSize > 0));
+            if (posixVariantSize > 0) {
+                if (variant == NULL) {
+                    variant = name+len;
+                }
+                len += posixVariantSize;
+                variantSize += posixVariantSize;
+            }
+        }
+
+        /* Handle generic variants first */
+        if (variant) {
+            for (j=0; j<(int32_t)(sizeof(VARIANT_MAP)/sizeof(VARIANT_MAP[0])); j++) {
+                const char* variantToCompare = VARIANT_MAP[j].variant;
+                int32_t n = (int32_t)uprv_strlen(variantToCompare);
+                int32_t variantLen = _deleteVariant(variant, uprv_min(variantSize, (nameCapacity-len)), variantToCompare, n);
+                len -= variantLen;
+                if (variantLen > 0) {
+                    if (len > 0 && name[len-1] == '_') { /* delete trailing '_' */
+                        --len;
+                    }
+                    addKeyword = VARIANT_MAP[j].keyword;
+                    addValue = VARIANT_MAP[j].value;
+                    break;
+                }
+            }
+            if (len > 0 && len <= nameCapacity && name[len-1] == '_') { /* delete trailing '_' */
+                --len;
+            }
+        }
+
+        /* Look up the ID in the canonicalization map */
+        for (j=0; j<(int32_t)(sizeof(CANONICALIZE_MAP)/sizeof(CANONICALIZE_MAP[0])); j++) {
+            const char* id = CANONICALIZE_MAP[j].id;
+            int32_t n = (int32_t)uprv_strlen(id);
+            if (len == n && uprv_strncmp(name, id, n) == 0) {
+                if (n == 0 && localeID != NULL) {
+                    break; /* Don't remap "" if keywords present */
+                }
+                len = _copyCount(name, nameCapacity, CANONICALIZE_MAP[j].canonicalID);
+                if (CANONICALIZE_MAP[j].keyword) {
+                    addKeyword = CANONICALIZE_MAP[j].keyword;
+                    addValue = CANONICALIZE_MAP[j].value;
+                }
+                break;
+            }
+        }
+    }
+
+    if (!OPTION_SET(options, _ULOC_STRIP_KEYWORDS)) {
+        if (localeID!=NULL && keywordAssign!=NULL &&
+            (!separatorIndicator || separatorIndicator > keywordAssign)) {
+            if(len<nameCapacity) {
+                name[len]='@';
+            }
+            ++len;
+            ++fieldCount;
+            len += _getKeywords(localeID+1, '@', name+len, nameCapacity-len, NULL, 0, NULL, TRUE,
+                                addKeyword, addValue, err);
+        } else if (addKeyword != NULL) {
+            U_ASSERT(addValue != NULL);
+            /* inelegant but works -- later make _getKeywords do this? */
+            len += _copyCount(name+len, nameCapacity-len, "@");
+            len += _copyCount(name+len, nameCapacity-len, addKeyword);
+            len += _copyCount(name+len, nameCapacity-len, "=");
+            len += _copyCount(name+len, nameCapacity-len, addValue);
+        }
+    }
+
+    if (U_SUCCESS(*err) && result != NULL && name == localeBuffer) {
+        uprv_strncpy(result, localeBuffer, (len > resultCapacity) ? resultCapacity : len);
+    }
+
+    return u_terminateChars(result, resultCapacity, len, err);
+}
+
+/* ### ID parsing API **************************************************/
+
+U_CAPI int32_t  U_EXPORT2
+uloc_getParent(const char*    localeID,
+               char* parent,
+               int32_t parentCapacity,
+               UErrorCode* err)
+{
+    const char *lastUnderscore;
+    int32_t i;
+    
+    if (U_FAILURE(*err))
+        return 0;
+    
+    if (localeID == NULL)
+        localeID = uloc_getDefault();
+
+    lastUnderscore=uprv_strrchr(localeID, '_');
+    if(lastUnderscore!=NULL) {
+        i=(int32_t)(lastUnderscore-localeID);
+    } else {
+        i=0;
+    }
+
+    if(i>0 && parent != localeID) {
+        uprv_memcpy(parent, localeID, uprv_min(i, parentCapacity));
+    }
+    return u_terminateChars(parent, parentCapacity, i, err);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getLanguage(const char*    localeID,
+         char* language,
+         int32_t languageCapacity,
+         UErrorCode* err)
+{
+    /* uloc_getLanguage will return a 2 character iso-639 code if one exists. *CWB*/
+    int32_t i=0;
+
+    if (err==NULL || U_FAILURE(*err)) {
+        return 0;
+    }
+    
+    if(localeID==NULL) {
+        localeID=uloc_getDefault();
+    }
+
+    i=_getLanguage(localeID, language, languageCapacity, NULL);
+    return u_terminateChars(language, languageCapacity, i, err);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getScript(const char*    localeID,
+         char* script,
+         int32_t scriptCapacity,
+         UErrorCode* err)
+{
+    int32_t i=0;
+
+    if(err==NULL || U_FAILURE(*err)) {
+        return 0;
+    }
+
+    if(localeID==NULL) {
+        localeID=uloc_getDefault();
+    }
+
+    /* skip the language */
+    _getLanguage(localeID, NULL, 0, &localeID);
+    if(_isIDSeparator(*localeID)) {
+        i=_getScript(localeID+1, script, scriptCapacity, NULL);
+    }
+    return u_terminateChars(script, scriptCapacity, i, err);
+}
+
+U_CAPI int32_t  U_EXPORT2
+uloc_getCountry(const char* localeID,
+            char* country,
+            int32_t countryCapacity,
+            UErrorCode* err) 
+{
+    int32_t i=0;
+
+    if(err==NULL || U_FAILURE(*err)) {
+        return 0;
+    }
+
+    if(localeID==NULL) {
+        localeID=uloc_getDefault();
+    }
+
+    /* Skip the language */
+    _getLanguage(localeID, NULL, 0, &localeID);
+    if(_isIDSeparator(*localeID)) {
+        const char *scriptID;
+        /* Skip the script if available */
+        _getScript(localeID+1, NULL, 0, &scriptID);
+        if(scriptID != localeID+1) {
+            /* Found optional script */
+            localeID = scriptID;
+        }
+        if(_isIDSeparator(*localeID)) {
+            i=_getCountry(localeID+1, country, countryCapacity, NULL);
+        }
+    }
+    return u_terminateChars(country, countryCapacity, i, err);
+}
+
+U_CAPI int32_t  U_EXPORT2
+uloc_getVariant(const char* localeID,
+                char* variant,
+                int32_t variantCapacity,
+                UErrorCode* err) 
+{
+    int32_t i=0;
+    
+    if(err==NULL || U_FAILURE(*err)) {
+        return 0;
+    }
+    
+    if(localeID==NULL) {
+        localeID=uloc_getDefault();
+    }
+    
+    /* Skip the language */
+    _getLanguage(localeID, NULL, 0, &localeID);
+    if(_isIDSeparator(*localeID)) {
+        const char *scriptID;
+        /* Skip the script if available */
+        _getScript(localeID+1, NULL, 0, &scriptID);
+        if(scriptID != localeID+1) {
+            /* Found optional script */
+            localeID = scriptID;
+        }
+        /* Skip the Country */
+        if (_isIDSeparator(*localeID)) {
+            _getCountry(localeID+1, NULL, 0, &localeID);
+            if(_isIDSeparator(*localeID)) {
+                i=_getVariant(localeID+1, *localeID, variant, variantCapacity);
+            }
+        }
+    }
+    
+    /* removed by weiv. We don't want to handle POSIX variants anymore. Use canonicalization function */
+    /* if we do not have a variant tag yet then try a POSIX variant after '@' */
+/*
+    if(!haveVariant && (localeID=uprv_strrchr(localeID, '@'))!=NULL) {
+        i=_getVariant(localeID+1, '@', variant, variantCapacity);
+    }
+*/
+    return u_terminateChars(variant, variantCapacity, i, err);
+}
+
+U_CAPI int32_t  U_EXPORT2
+uloc_getName(const char* localeID,
+             char* name,
+             int32_t nameCapacity,
+             UErrorCode* err)  
+{
+    return _canonicalize(localeID, name, nameCapacity, 0, err);
+}
+
+U_CAPI int32_t  U_EXPORT2
+uloc_getBaseName(const char* localeID,
+                 char* name,
+                 int32_t nameCapacity,
+                 UErrorCode* err)  
+{
+    return _canonicalize(localeID, name, nameCapacity, _ULOC_STRIP_KEYWORDS, err);
+}
+
+U_CAPI int32_t  U_EXPORT2
+uloc_canonicalize(const char* localeID,
+                  char* name,
+                  int32_t nameCapacity,
+                  UErrorCode* err)  
+{
+    return _canonicalize(localeID, name, nameCapacity, _ULOC_CANONICALIZE, err);
+}
+  
+U_CAPI const char*  U_EXPORT2
+uloc_getISO3Language(const char* localeID) 
+{
+    int16_t offset;
+    char lang[ULOC_LANG_CAPACITY];
+    UErrorCode err = U_ZERO_ERROR;
+    
+    if (localeID == NULL)
+    {
+        localeID = uloc_getDefault();
+    }
+    uloc_getLanguage(localeID, lang, ULOC_LANG_CAPACITY, &err);
+    if (U_FAILURE(err))
+        return "";
+    offset = _findIndex(LANGUAGES, lang);
+    if (offset < 0)
+        return "";
+    return LANGUAGES_3[offset];
+}
+
+U_CAPI const char*  U_EXPORT2
+uloc_getISO3Country(const char* localeID) 
+{
+    int16_t offset;
+    char cntry[ULOC_LANG_CAPACITY];
+    UErrorCode err = U_ZERO_ERROR;
+    
+    if (localeID == NULL)
+    {
+        localeID = uloc_getDefault();
+    }
+    uloc_getCountry(localeID, cntry, ULOC_LANG_CAPACITY, &err);
+    if (U_FAILURE(err))
+        return "";
+    offset = _findIndex(COUNTRIES, cntry);
+    if (offset < 0)
+        return "";
+    
+    return COUNTRIES_3[offset];
+}
+
+U_CAPI uint32_t  U_EXPORT2
+uloc_getLCID(const char* localeID) 
+{
+    UErrorCode status = U_ZERO_ERROR;
+    char       langID[ULOC_FULLNAME_CAPACITY];
+
+    uloc_getLanguage(localeID, langID, sizeof(langID), &status);
+    if (U_FAILURE(status)) {
+        return 0;
+    }
+
+    return uprv_convertToLCID(langID, localeID, &status);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getLocaleForLCID(uint32_t hostid, char *locale, int32_t localeCapacity,
+                UErrorCode *status)
+{
+    int32_t length;
+    const char *posix = uprv_convertToPosix(hostid, status);
+    if (U_FAILURE(*status) || posix == NULL) {
+        return 0;
+    }
+    length = (int32_t)uprv_strlen(posix);
+    if (length+1 > localeCapacity) {
+        *status = U_BUFFER_OVERFLOW_ERROR;
+    }
+    else {
+        uprv_strcpy(locale, posix);
+    }
+    return length;
+}
+
+/* ### Default locale **************************************************/
+
+U_CAPI const char*  U_EXPORT2
+uloc_getDefault()
+{
+    return locale_get_default();
+}
+
+U_CAPI void  U_EXPORT2
+uloc_setDefault(const char*   newDefaultLocale,
+             UErrorCode* err) 
+{
+    if (U_FAILURE(*err))
+        return;
+    /* the error code isn't currently used for anything by this function*/
+    
+    /* propagate change to C++ */
+    locale_set_default(newDefaultLocale);
+}
+
+/* ### Display name **************************************************/
+
+/*
+ * Lookup a resource bundle table item with fallback on the table level.
+ * Regular resource bundle lookups perform fallback to parent locale bundles
+ * and eventually the root bundle, but only for top-level items.
+ * This function takes the name of a top-level table and of an item in that table
+ * and performs a lookup of both, falling back until a bundle contains a table
+ * with this item.
+ *
+ * Note: Only the opening of entire bundles falls back through the default locale
+ * before root. Once a bundle is open, item lookups do not go through the
+ * default locale because that would result in a mix of languages that is
+ * unpredictable to the programmer and most likely useless.
+ */
+static const UChar *
+_res_getTableStringWithFallback(const char *path, const char *locale,
+                              const char *tableKey, const char *subTableKey,
+                              const char *itemKey,
+                              int32_t *pLength,
+                              UErrorCode *pErrorCode)
+{
+/*    char localeBuffer[ULOC_FULLNAME_CAPACITY*4];*/
+    UResourceBundle *rb=NULL, table, subTable;
+    const UChar *item=NULL;
+    UErrorCode errorCode;
+    char explicitFallbackName[ULOC_FULLNAME_CAPACITY] = {0};
+
+    /*
+     * open the bundle for the current locale
+     * this falls back through the locale's chain to root
+     */
+    errorCode=U_ZERO_ERROR;
+    rb=ures_open(path, locale, &errorCode);
+    if(U_FAILURE(errorCode)) {
+        /* total failure, not even root could be opened */
+        *pErrorCode=errorCode;
+        return NULL;
+    } else if(errorCode==U_USING_DEFAULT_WARNING ||
+                (errorCode==U_USING_FALLBACK_WARNING && *pErrorCode!=U_USING_DEFAULT_WARNING)
+    ) {
+        /* set the "strongest" error code (success->fallback->default->failure) */
+        *pErrorCode=errorCode;
+    }
+
+    for(;;){
+        ures_initStackObject(&table);
+        ures_initStackObject(&subTable);
+        ures_getByKeyWithFallback(rb, tableKey, &table, &errorCode);
+        if (subTableKey != NULL) {
+            /*
+            ures_getByKeyWithFallback(&table,subTableKey, &subTable, &errorCode);
+            item = ures_getStringByKeyWithFallback(&subTable, itemKey, pLength, &errorCode);
+            if(U_FAILURE(errorCode)){
+                *pErrorCode = errorCode;
+            }
+            
+            break;*/
+            
+            ures_getByKeyWithFallback(&table,subTableKey, &table, &errorCode);
+        }
+        if(U_SUCCESS(errorCode)){
+            item = ures_getStringByKeyWithFallback(&table, itemKey, pLength, &errorCode);
+            if(U_FAILURE(errorCode)){
+                const char* replacement = NULL;
+                *pErrorCode = errorCode; /*save the errorCode*/
+                errorCode = U_ZERO_ERROR;
+                /* may be a deprecated code */
+                if(uprv_strcmp(tableKey, "Countries")==0){
+                    replacement =  uloc_getCurrentCountryID(itemKey);
+                }else if(uprv_strcmp(tableKey, "Languages")==0){
+                    replacement =  uloc_getCurrentLanguageID(itemKey);
+                }
+                /*pointer comparison is ok since uloc_getCurrentCountryID & uloc_getCurrentLanguageID return the key itself is replacement is not found*/
+                if(replacement!=NULL && itemKey != replacement){
+                    item = ures_getStringByKeyWithFallback(&table, replacement, pLength, &errorCode);
+                    if(U_SUCCESS(errorCode)){
+                        *pErrorCode = errorCode;
+                        break;
+                    }
+                }
+            }else{
+                break;
+            }
+        }
+        
+        if(U_FAILURE(errorCode)){    
+
+            /* still can't figure out ?.. try the fallback mechanism */
+            int32_t len = 0;
+            const UChar* fallbackLocale =  NULL;
+            *pErrorCode = errorCode;
+            errorCode = U_ZERO_ERROR;
+
+            fallbackLocale = ures_getStringByKeyWithFallback(&table, "Fallback", &len, &errorCode);
+            if(U_FAILURE(errorCode)){
+               *pErrorCode = errorCode;
+                break;
+            }
+            
+            u_UCharsToChars(fallbackLocale, explicitFallbackName, len);
+            
+            /* guard against recursive fallback */
+            if(uprv_strcmp(explicitFallbackName, locale)==0){
+                *pErrorCode = U_INTERNAL_PROGRAM_ERROR;
+                break;
+            }
+            ures_close(rb);
+            rb = ures_open(NULL, explicitFallbackName, &errorCode);
+            if(U_FAILURE(errorCode)){
+                *pErrorCode = errorCode;
+                break;
+            }
+            /* succeeded in opening the fallback bundle .. continue and try to fetch the item */
+        }else{
+            break;
+        }
+    }
+    /* done with the locale string - ready to close table and rb */
+    ures_close(&subTable);
+    ures_close(&table);
+    ures_close(rb);
+    return item;
+}
+
+static int32_t
+_getStringOrCopyKey(const char *path, const char *locale,
+                    const char *tableKey, 
+                    const char* subTableKey,
+                    const char *itemKey,
+                    const char *substitute,
+                    UChar *dest, int32_t destCapacity,
+                    UErrorCode *pErrorCode) {
+    const UChar *s = NULL;
+    int32_t length = 0;
+
+    if(itemKey==NULL) {
+        /* top-level item: normal resource bundle access */
+        UResourceBundle *rb;
+
+        rb=ures_open(path, locale, pErrorCode);
+        if(U_SUCCESS(*pErrorCode)) {
+            s=ures_getStringByKey(rb, tableKey, &length, pErrorCode);
+            /* see comment about closing rb near "return item;" in _res_getTableStringWithFallback() */
+            ures_close(rb);
+        }
+    } else {
+        /* second-level item, use special fallback */
+        s=_res_getTableStringWithFallback(path, locale,
+                                           tableKey, 
+                                           subTableKey,
+                                           itemKey,
+                                           &length,
+                                           pErrorCode);
+    }
+    if(U_SUCCESS(*pErrorCode)) {
+        int32_t copyLength=uprv_min(length, destCapacity);
+        if(copyLength>0 && s != NULL) {
+            u_memcpy(dest, s, copyLength);
+        }
+    } else {
+        /* no string from a resource bundle: convert the substitute */
+        length=(int32_t)uprv_strlen(substitute);
+        u_charsToUChars(substitute, dest, uprv_min(length, destCapacity));
+        *pErrorCode=U_USING_DEFAULT_WARNING;
+    }
+
+    return u_terminateUChars(dest, destCapacity, length, pErrorCode);
+}
+
+static int32_t
+_getDisplayNameForComponent(const char *locale,
+                            const char *displayLocale,
+                            UChar *dest, int32_t destCapacity,
+                            int32_t (*getter)(const char *, char *, int32_t, UErrorCode *),
+                            const char *tag,
+                            UErrorCode *pErrorCode) {
+    char localeBuffer[ULOC_FULLNAME_CAPACITY*4];
+    int32_t length;
+    UErrorCode localStatus;
+
+    /* argument checking */
+    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
+        return 0;
+    }
+
+    if(destCapacity<0 || (destCapacity>0 && dest==NULL)) {
+        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
+        return 0;
+    }
+
+    localStatus = U_ZERO_ERROR;
+    length=(*getter)(locale, localeBuffer, sizeof(localeBuffer), &localStatus);
+    if(U_FAILURE(localStatus) || localStatus==U_STRING_NOT_TERMINATED_WARNING) {
+        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
+        return 0;
+    }
+    if(length==0) {
+        return u_terminateUChars(dest, destCapacity, 0, pErrorCode);
+    }
+
+    return _getStringOrCopyKey(NULL, displayLocale,
+                               tag, NULL, localeBuffer,
+                               localeBuffer, 
+                               dest, destCapacity,
+                               pErrorCode);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getDisplayLanguage(const char *locale,
+                        const char *displayLocale,
+                        UChar *dest, int32_t destCapacity,
+                        UErrorCode *pErrorCode) {
+    return _getDisplayNameForComponent(locale, displayLocale, dest, destCapacity,
+                uloc_getLanguage, _kLanguages, pErrorCode);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getDisplayScript(const char* locale,
+                      const char* displayLocale,
+                      UChar *dest, int32_t destCapacity,
+                      UErrorCode *pErrorCode)
+{
+    return _getDisplayNameForComponent(locale, displayLocale, dest, destCapacity,
+                uloc_getScript, _kScripts, pErrorCode);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getDisplayCountry(const char *locale,
+                       const char *displayLocale,
+                       UChar *dest, int32_t destCapacity,
+                       UErrorCode *pErrorCode) {
+    return _getDisplayNameForComponent(locale, displayLocale, dest, destCapacity,
+                uloc_getCountry, _kCountries, pErrorCode);
+}
+
+/*
+ * TODO separate variant1_variant2_variant3...
+ * by getting each tag's display string and concatenating them with ", "
+ * in between - similar to uloc_getDisplayName()
+ */
+U_CAPI int32_t U_EXPORT2
+uloc_getDisplayVariant(const char *locale,
+                       const char *displayLocale,
+                       UChar *dest, int32_t destCapacity,
+                       UErrorCode *pErrorCode) {
+    return _getDisplayNameForComponent(locale, displayLocale, dest, destCapacity,
+                uloc_getVariant, _kVariants, pErrorCode);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getDisplayName(const char *locale,
+                    const char *displayLocale,
+                    UChar *dest, int32_t destCapacity,
+                    UErrorCode *pErrorCode)
+{
+    int32_t length, length2, length3 = 0;
+    UBool hasLanguage, hasScript, hasCountry, hasVariant, hasKeywords;
+    UEnumeration* keywordEnum = NULL;
+    int32_t keywordCount = 0;
+    const char *keyword = NULL;
+    int32_t keywordLen = 0;
+    char keywordValue[256];
+    int32_t keywordValueLen = 0;
+
+    /* argument checking */
+    if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
+        return 0;
+    }
+
+    if(destCapacity<0 || (destCapacity>0 && dest==NULL)) {
+        *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
+        return 0;
+    }
+
+    /*
+     * if there is a language, then write "language (country, variant)"
+     * otherwise write "country, variant"
+     */
+
+    /* write the language */
+    length=uloc_getDisplayLanguage(locale, displayLocale,
+                                   dest, destCapacity,
+                                   pErrorCode);
+    hasLanguage= length>0;
+
+    if(hasLanguage) {
+        /* append " (" */
+        if(length<destCapacity) {
+            dest[length]=0x20;
+        }
+        ++length;
+        if(length<destCapacity) {
+            dest[length]=0x28;
+        }
+        ++length;
+    }
+
+    if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
+        /* keep preflighting */
+        *pErrorCode=U_ZERO_ERROR;
+    }
+
+    /* append the script */
+    if(length<destCapacity) {
+        length2=uloc_getDisplayScript(locale, displayLocale,
+                                       dest+length, destCapacity-length,
+                                       pErrorCode);
+    } else {
+        length2=uloc_getDisplayScript(locale, displayLocale,
+                                       NULL, 0,
+                                       pErrorCode);
+    }
+    hasScript= length2>0;
+    length+=length2;
+
+    if(hasScript) {
+        /* append ", " */
+        if(length<destCapacity) {
+            dest[length]=0x2c;
+        }
+        ++length;
+        if(length<destCapacity) {
+            dest[length]=0x20;
+        }
+        ++length;
+    }
+
+    if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
+        /* keep preflighting */
+        *pErrorCode=U_ZERO_ERROR;
+    }
+
+    /* append the country */
+    if(length<destCapacity) {
+        length2=uloc_getDisplayCountry(locale, displayLocale,
+                                       dest+length, destCapacity-length,
+                                       pErrorCode);
+    } else {
+        length2=uloc_getDisplayCountry(locale, displayLocale,
+                                       NULL, 0,
+                                       pErrorCode);
+    }
+    hasCountry= length2>0;
+    length+=length2;
+
+    if(hasCountry) {
+        /* append ", " */
+        if(length<destCapacity) {
+            dest[length]=0x2c;
+        }
+        ++length;
+        if(length<destCapacity) {
+            dest[length]=0x20;
+        }
+        ++length;
+    }
+
+    if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
+        /* keep preflighting */
+        *pErrorCode=U_ZERO_ERROR;
+    }
+
+    /* append the variant */
+    if(length<destCapacity) {
+        length2=uloc_getDisplayVariant(locale, displayLocale,
+                                       dest+length, destCapacity-length,
+                                       pErrorCode);
+    } else {
+        length2=uloc_getDisplayVariant(locale, displayLocale,
+                                       NULL, 0,
+                                       pErrorCode);
+    }
+    hasVariant= length2>0;
+    length+=length2;
+
+    if(hasVariant) {
+        /* append ", " */
+        if(length<destCapacity) {
+            dest[length]=0x2c;
+        }
+        ++length;
+        if(length<destCapacity) {
+            dest[length]=0x20;
+        }
+        ++length;
+    }
+
+    keywordEnum = uloc_openKeywords(locale, pErrorCode);
+    
+    for(keywordCount = uenum_count(keywordEnum, pErrorCode); keywordCount > 0 ; keywordCount--){
+          if(U_FAILURE(*pErrorCode)){
+              break;
+          }
+          /* the uenum_next returns NUL terminated string */
+          keyword = uenum_next(keywordEnum, &keywordLen, pErrorCode);
+          if(length + length3 < destCapacity) {
+            length3 += uloc_getDisplayKeyword(keyword, displayLocale, dest+length+length3, destCapacity-length-length3, pErrorCode);
+          } else {
+            length3 += uloc_getDisplayKeyword(keyword, displayLocale, NULL, 0, pErrorCode);
+          }
+          if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
+              /* keep preflighting */
+              *pErrorCode=U_ZERO_ERROR;
+          }
+          keywordValueLen = uloc_getKeywordValue(locale, keyword, keywordValue, 256, pErrorCode);
+          if(keywordValueLen) {
+            if(length + length3 < destCapacity) {
+              dest[length + length3] = 0x3D;
+            }
+            length3++;
+            if(length + length3 < destCapacity) {
+              length3 += uloc_getDisplayKeywordValue(locale, keyword, displayLocale, dest+length+length3, destCapacity-length-length3, pErrorCode);
+            } else {
+              length3 += uloc_getDisplayKeywordValue(locale, keyword, displayLocale, NULL, 0, pErrorCode);
+            }
+            if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
+                /* keep preflighting */
+                *pErrorCode=U_ZERO_ERROR;
+            }
+          }
+          if(keywordCount > 1) {
+            if(length + length3 + 1 < destCapacity && keywordCount) {
+              dest[length + length3]=0x2c;
+              dest[length + length3+1]=0x20;
+            }
+            length3++; /* ',' */
+            length3++; /* ' ' */ 
+          }
+    }
+    uenum_close(keywordEnum);
+
+    hasKeywords = length3 > 0;
+    length += length3;
+
+
+
+    if ((hasScript && !hasCountry)
+        || ((hasScript || hasCountry) && !hasVariant && !hasKeywords)
+        || ((hasScript || hasCountry || hasVariant) && !hasKeywords)
+        || (hasLanguage && !hasScript && !hasCountry && !hasVariant && !hasKeywords))
+    {
+        /* remove ", " or " (" */
+        length-=2;
+    }
+
+    if (hasLanguage && (hasScript || hasCountry || hasVariant || hasKeywords)) {
+        /* append ")" */
+        if(length<destCapacity) {
+            dest[length]=0x29;
+        }
+        ++length;
+    }
+
+    if(*pErrorCode==U_BUFFER_OVERFLOW_ERROR) {
+        /* keep preflighting */
+        *pErrorCode=U_ZERO_ERROR;
+    }
+
+    return u_terminateUChars(dest, destCapacity, length, pErrorCode);
+}
+
+U_CAPI int32_t U_EXPORT2
+uloc_getDisplayKeyword(const char* keyword,
+                       const char* displayLocale,
+                       UChar* dest,
+                       int32_t destCapacity,
+                       UErrorCode* status){
+
+    /* argument checking */
+    if(status==NULL || U_FAILURE(*status)) {
+        return 0;
+    }
+
+    if(destCapacity<0 || (destCapacity>0 && dest==NULL)) {
+        *status=U_ILLEGAL_ARGUMENT_ERROR;
+        return 0;
+    }
+
+
+    /* pass itemKey=NULL to look for a top-level item */
+    return _getStringOrCopyKey(NULL, displayLocale,
+                               _kKeys, NULL, 
+                               keyword, 
+                               keyword,      
+                               dest, destCapacity,
+                               status);
+
+}
+
+
+#define UCURRENCY_DISPLAY_NAME_INDEX 1
+
+U_CAPI int32_t U_EXPORT2
+uloc_getDisplayKeywordValue(   const char* locale,
+                               const char* keyword,
+                               const char* displayLocale,
+                               UChar* dest,
+                               int32_t destCapacity,
+                               UErrorCode* status){
+
+
+    char keywordValue[ULOC_FULLNAME_CAPACITY*4];
+    int32_t capacity = ULOC_FULLNAME_CAPACITY*4;
+    int32_t keywordValueLen =0;
+
+    /* argument checking */
+    if(status==NULL || U_FAILURE(*status)) {
+        return 0;
+    }
+
+    if(destCapacity<0 || (destCapacity>0 && dest==NULL)) {
+        *status=U_ILLEGAL_ARGUMENT_ERROR;
+        return 0;
+    }
+
+    /* get the keyword value */
+    keywordValue[0]=0;
+    keywordValueLen = uloc_getKeywordValue(locale, keyword, keywordValue, capacity, status);
+
+    /* 
+     * if the keyword is equal to currency .. then to get the display name 
+     * we need to do the fallback ourselves
+     */
+    if(uprv_stricmp(keyword, _kCurrency)==0){
+
+        int32_t dispNameLen = 0;
+        const UChar *dispName = NULL;
+        
+        UResourceBundle *bundle     = ures_open(NULL, displayLocale, status);
+        UResourceBundle *currencies = ures_getByKey(bundle, _kCurrencies, NULL, status);
+        UResourceBundle *currency   = ures_getByKeyWithFallback(currencies, keywordValue, NULL, status);
+        
+        dispName = ures_getStringByIndex(currency, UCURRENCY_DISPLAY_NAME_INDEX, &dispNameLen, status);
+        
+        /*close the bundles */
+        ures_close(currency);
+        ures_close(currencies);
+        ures_close(bundle);
+        
+        if(U_FAILURE(*status)){
+            if(*status == U_MISSING_RESOURCE_ERROR){
+                /* we just want to write the value over if nothing is available */
+                *status = U_USING_DEFAULT_WARNING;
+            }else{
+                return 0;
+            }
+        }
+
+        /* now copy the dispName over if not NULL */
+        if(dispName != NULL){
+            if(dispNameLen <= destCapacity){
+                uprv_memcpy(dest, dispName, dispNameLen * U_SIZEOF_UCHAR);
+                return u_terminateUChars(dest, destCapacity, dispNameLen, status);
+            }else{
+                *status = U_BUFFER_OVERFLOW_ERROR;
+                return dispNameLen;
+            }
+        }else{
+            /* we have not found the display name for the value .. just copy over */
+            if(keywordValueLen <= destCapacity){
+                u_charsToUChars(keywordValue, dest, keywordValueLen);
+                return u_terminateUChars(dest, destCapacity, keywordValueLen, status);
+            }else{
+                 *status = U_BUFFER_OVERFLOW_ERROR;
+                return keywordValueLen;
+            }
+        }
+
+        
+    }else{
+
+        return _getStringOrCopyKey(NULL, displayLocale,
+                                   _kTypes, keyword, 
+                                   keywordValue,
+                                   keywordValue,
+                                   dest, destCapacity,
+                                   status);
+    }
+}
+
+/* ### Get available **************************************************/
+
+static UBool U_CALLCONV uloc_cleanup(void) {
+    char ** temp;
+
+    if (_installedLocales) {
+        temp = _installedLocales;
+        _installedLocales = NULL;
+
+        _installedLocalesCount = 0;
+
+        uprv_free(temp);
+    }
+    return TRUE;
+}
+
+static void _load_installedLocales()
+{
+    UBool   localesLoaded;
+
+    UMTX_CHECK(NULL, _installedLocales != NULL, localesLoaded);
+    
+    if (localesLoaded == FALSE) {
+        UResourceBundle *index = NULL;
+        UResourceBundle installed;
+        UErrorCode status = U_ZERO_ERROR;
+        char ** temp;
+        int32_t i = 0;
+        int32_t localeCount;
+        
+        ures_initStackObject(&installed);
+        index = ures_openDirect(NULL, _kIndexLocaleName, &status);
+        ures_getByKey(index, _kIndexTag, &installed, &status);
+        
+        if(U_SUCCESS(status)) {
+            localeCount = ures_getSize(&installed);
+            temp = (char **) uprv_malloc(sizeof(char*) * (localeCount+1));
+            /* Check for null pointer */
+            if (temp != NULL) {
+                ures_resetIterator(&installed);
+                while(ures_hasNext(&installed)) {
+                    ures_getNextString(&installed, NULL, (const char **)&temp[i++], &status);
+                }
+                temp[i] = NULL;
+
+                umtx_lock(NULL);
+                if (_installedLocales == NULL)
+                {
+                    _installedLocales = temp;
+                    _installedLocalesCount = localeCount;
+                    temp = NULL;
+                    ucln_common_registerCleanup(UCLN_COMMON_ULOC, uloc_cleanup);
+                } 
+                umtx_unlock(NULL);
+
+                uprv_free(temp);
+            }
+        }
+        ures_close(&installed);
+        ures_close(index);
+    }
+}
+
+U_CAPI const char* U_EXPORT2
+uloc_getAvailable(int32_t offset) 
+{
+    
+    _load_installedLocales();
+    
+    if (offset > _installedLocalesCount)
+        return NULL;
+    return _installedLocales[offset];
+}
+
+U_CAPI int32_t  U_EXPORT2
+uloc_countAvailable()
+{
+    _load_installedLocales();
+    return _installedLocalesCount;
+}
+
+/**
+ * Returns a list of all language codes defined in ISO 639.  This is a pointer
+ * to an array of pointers to arrays of char.  All of these pointers are owned
+ * by ICU-- do not delete them, and do not write through them.  The array is
+ * terminated with a null pointer.
+ */
+U_CAPI const char* const*  U_EXPORT2
+uloc_getISOLanguages() 
+{
+    return LANGUAGES;
+}
+
+/**
+ * Returns a list of all 2-letter country codes defined in ISO 639.  This is a
+ * pointer to an array of pointers to arrays of char.  All of these pointers are
+ * owned by ICU-- do not delete them, and do not write through them.  The array is
+ * terminated with a null pointer.
+ */
+U_CAPI const char* const*  U_EXPORT2
+uloc_getISOCountries() 
+{
+    return COUNTRIES;
+}
+
+
+/* this function to be moved into cstring.c later */
+static char gDecimal = 0;
+
+static /* U_CAPI */
+double
+/* U_EXPORT2 */
+_uloc_strtod(const char *start, char **end) {
+    char *decimal;
+    char *myEnd;
+    char buf[30];
+    double rv;
+    if (!gDecimal) {
+        char rep[5];
+        /* For machines that decide to change the decimal on you,
+        and try to be too smart with localization.
+        This normally should be just a '.'. */
+        sprintf(rep, "%+1.1f", 1.0);
+        gDecimal = rep[2];
+    }
+
+    if(gDecimal == '.') {
+        return uprv_strtod(start, end); /* fall through to OS */
+    } else {
+        uprv_strncpy(buf, start, 29);
+        buf[29]=0;
+        decimal = uprv_strchr(buf, '.');
+        if(decimal) {
+            *decimal = gDecimal;
+        } else {
+            return uprv_strtod(start, end); /* no decimal point */
+        }
+        rv = uprv_strtod(buf, &myEnd);
+        if(end) {
+            *end = (char*)(start+(myEnd-buf)); /* cast away const (to follow uprv_strtod API.) */
+        }
+        return rv;
+    }
+}
+
+typedef struct { 
+    float q;
+    int32_t dummy;  /* to avoid uninitialized memory copy from qsort */
+    char *locale;
+} _acceptLangItem;
+
+static int32_t U_CALLCONV
+uloc_acceptLanguageCompare(const void *context, const void *a, const void *b)
+{
+    const _acceptLangItem *aa = (const _acceptLangItem*)a;
+    const _acceptLangItem *bb = (const _acceptLangItem*)b;
+
+    int32_t rc = 0;
+    if(bb->q < aa->q) {
+        rc = -1;  /* A > B */
+    } else if(bb->q > aa->q) {
+        rc = 1;   /* A < B */
+    } else {
+        rc = 0;   /* A = B */
+    }
+
+    if(rc==0) {
+        rc = uprv_stricmp(aa->locale, bb->locale);
+    }
+
+#if defined(ULOC_DEBUG)
+    /*  fprintf(stderr, "a:[%s:%g], b:[%s:%g] -> %d\n", 
+    aa->locale, aa->q, 
+    bb->locale, bb->q,
+    rc);*/
+#endif
+
+    return rc;
+}
+
+static ULayoutType
+_uloc_getOrientationHelper(const char* localeId,
+                           const char* key,
+                           UErrorCode *status)
+{
+    ULayoutType result = ULOC_LAYOUT_UNKNOWN;
+
+    if (!U_FAILURE(*status)) {
+        int32_t length = 0;
+        char localeBuffer[ULOC_FULLNAME_CAPACITY];
+
+        uloc_canonicalize(localeId, localeBuffer, sizeof(localeBuffer), status);
+
+        if (!U_FAILURE(*status)) {
+            const UChar* const value =
+                _res_getTableStringWithFallback(
+                    NULL,
+                    localeBuffer,
+                    "layout",
+                    NULL,
+                    key,
+                    &length,
+                    status);
+
+            if (!U_FAILURE(*status) && length != 0) {
+                switch(value[0])
+                {
+                case 0x0062: /* 'b' */
+                    result = ULOC_LAYOUT_BTT;
+                    break;
+                case 0x006C: /* 'l' */
+                    result = ULOC_LAYOUT_LTR;
+                    break;
+                case 0x0072: /* 'r' */
+                    result = ULOC_LAYOUT_RTL;
+                    break;
+                case 0x0074: /* 't' */
+                    result = ULOC_LAYOUT_TTB;
+                    break;
+                default:
+                    *status = U_INTERNAL_PROGRAM_ERROR;
+                    break;
+                }
+            }
+        }
+    }
+
+    return result;
+}
+
+U_DRAFT ULayoutType U_EXPORT2
+uloc_getCharacterOrientation(const char* localeId,
+                             UErrorCode *status)
+{
+    return _uloc_getOrientationHelper(localeId, "characters", status);
+}
+
+/**
+ * Get the layout line orientation for the specified locale.
+ * 
+ * @param localeID locale name
+ * @param status Error status
+ * @return an enum indicating the layout orientation for lines.
+ * @draft ICU 4.0
+ */
+U_DRAFT ULayoutType U_EXPORT2
+uloc_getLineOrientation(const char* localeId,
+                        UErrorCode *status)
+{
+    return _uloc_getOrientationHelper(localeId, "lines", status);
+}
+
+/* 
+mt-mt, ja;q=0.76, en-us;q=0.95, en;q=0.92, en-gb;q=0.89, fr;q=0.87, iu-ca;q=0.84, iu;q=0.82, ja-jp;q=0.79, mt;q=0.97, de-de;q=0.74, de;q=0.71, es;q=0.68, it-it;q=0.66, it;q=0.63, vi-vn;q=0.61, vi;q=0.58, nl-nl;q=0.55, nl;q=0.53
+*/
+
+U_CAPI int32_t U_EXPORT2
+uloc_acceptLanguageFromHTTP(char *result, int32_t resultAvailable, UAcceptResult *outResult,
+                            const char *httpAcceptLanguage,
+                            UEnumeration* availableLocales,
+                            UErrorCode *status)
+{
+    _acceptLangItem *j;
+    _acceptLangItem smallBuffer[30];
+    char **strs;
+    char tmp[ULOC_FULLNAME_CAPACITY +1];
+    int32_t n = 0;
+    const char *itemEnd;
+    const char *paramEnd;
+    const char *s;
+    const char *t;
+    int32_t res;
+    int32_t i;
+    int32_t l = (int32_t)uprv_strlen(httpAcceptLanguage);
+    int32_t jSize;
+    char *tempstr; /* Use for null pointer check */
+
+    j = smallBuffer;
+    jSize = sizeof(smallBuffer)/sizeof(smallBuffer[0]);
+    if(U_FAILURE(*status)) {
+        return -1;
+    }
+
+    for(s=httpAcceptLanguage;s&&*s;) {
+        while(isspace(*s)) /* eat space at the beginning */
+            s++;
+        itemEnd=uprv_strchr(s,',');
+        paramEnd=uprv_strchr(s,';');
+        if(!itemEnd) {
+            itemEnd = httpAcceptLanguage+l; /* end of string */
+        }
+        if(paramEnd && paramEnd<itemEnd) { 
+            /* semicolon (;) is closer than end (,) */
+            t = paramEnd+1;
+            if(*t=='q') {
+                t++;
+            }
+            while(isspace(*t)) {
+                t++;
+            }
+            if(*t=='=') {
+                t++;
+            }
+            while(isspace(*t)) {
+                t++;
+            }
+            j[n].q = (float)_uloc_strtod(t,NULL);
+        } else {
+            /* no semicolon - it's 1.0 */
+            j[n].q = 1.0f;
+            paramEnd = itemEnd;
+        }
+        j[n].dummy=0;
+        /* eat spaces prior to semi */
+        for(t=(paramEnd-1);(paramEnd>s)&&isspace(*t);t--)
+            ;
+        /* Check for null pointer from uprv_strndup */
+        tempstr = uprv_strndup(s,(int32_t)((t+1)-s));
+        if (tempstr == NULL) {
+            *status = U_MEMORY_ALLOCATION_ERROR;
+            return -1;
+        }
+        j[n].locale = tempstr;
+        uloc_canonicalize(j[n].locale,tmp,sizeof(tmp)/sizeof(tmp[0]),status);
+        if(strcmp(j[n].locale,tmp)) {
+            uprv_free(j[n].locale);
+            j[n].locale=uprv_strdup(tmp);
+        }
+#if defined(ULOC_DEBUG)
+        /*fprintf(stderr,"%d: s <%s> q <%g>\n", n, j[n].locale, j[n].q);*/
+#endif
+        n++;
+        s = itemEnd;
+        while(*s==',') { /* eat duplicate commas */
+            s++;
+        }
+        if(n>=jSize) {
+            if(j==smallBuffer) {  /* overflowed the small buffer. */
+                j = static_cast<_acceptLangItem *>(uprv_malloc(sizeof(j[0])*(jSize*2)));
+                if(j!=NULL) {
+                    uprv_memcpy(j,smallBuffer,sizeof(j[0])*jSize);
+                }
+#if defined(ULOC_DEBUG)
+                fprintf(stderr,"malloced at size %d\n", jSize);
+#endif
+            } else {
+                j = static_cast<_acceptLangItem *>(uprv_realloc(j, sizeof(j[0])*jSize*2));
+#if defined(ULOC_DEBUG)
+                fprintf(stderr,"re-alloced at size %d\n", jSize);
+#endif
+            }
+            jSize *= 2;
+            if(j==NULL) {
+                *status = U_MEMORY_ALLOCATION_ERROR;
+                return -1;
+            }
+        }
+    }
+    uprv_sortArray(j, n, sizeof(j[0]), uloc_acceptLanguageCompare, NULL, TRUE, status);
+    if(U_FAILURE(*status)) {
+        if(j != smallBuffer) {
+#if defined(ULOC_DEBUG)
+            fprintf(stderr,"freeing j %p\n", j);
+#endif
+            uprv_free(j);
+        }
+        return -1;
+    }
+    strs = static_cast<char **>(uprv_malloc((size_t)(sizeof(strs[0])*n)));
+    /* Check for null pointer */
+    if (strs == NULL) {
+        uprv_free(j); /* Free to avoid memory leak */
+        *status = U_MEMORY_ALLOCATION_ERROR;
+        return -1;
+    }
+    for(i=0;i<n;i++) {
+#if defined(ULOC_DEBUG)
+        /*fprintf(stderr,"%d: s <%s> q <%g>\n", i, j[i].locale, j[i].q);*/
+#endif
+        strs[i]=j[i].locale;
+    }
+    res =  uloc_acceptLanguage(result, resultAvailable, outResult, 
+        (const char**)strs, n, availableLocales, status);
+    for(i=0;i<n;i++) {
+        uprv_free(strs[i]);
+    }
+    uprv_free(strs);
+    if(j != smallBuffer) {
+#if defined(ULOC_DEBUG)
+        fprintf(stderr,"freeing j %p\n", j);
+#endif
+        uprv_free(j);
+    }
+    return res;
+}
+
+
+U_CAPI int32_t U_EXPORT2
+uloc_acceptLanguage(char *result, int32_t resultAvailable, 
+                    UAcceptResult *outResult, const char **acceptList,
+                    int32_t acceptListCount,
+                    UEnumeration* availableLocales,
+                    UErrorCode *status)
+{
+    int32_t i,j;
+    int32_t len;
+    int32_t maxLen=0;
+    char tmp[ULOC_FULLNAME_CAPACITY+1];
+    const char *l;
+    char **fallbackList;
+    if(U_FAILURE(*status)) {
+        return -1;
+    }
+    fallbackList = static_cast<char **>(uprv_malloc((size_t)(sizeof(fallbackList[0])*acceptListCount)));
+    if(fallbackList==NULL) {
+        *status = U_MEMORY_ALLOCATION_ERROR;
+        return -1;
+    }
+    for(i=0;i<acceptListCount;i++) {
+#if defined(ULOC_DEBUG)
+        fprintf(stderr,"%02d: %s\n", i, acceptList[i]);
+#endif
+        while((l=uenum_next(availableLocales, NULL, status))) {
+#if defined(ULOC_DEBUG)
+            fprintf(stderr,"  %s\n", l);
+#endif
+            len = (int32_t)uprv_strlen(l);
+            if(!uprv_strcmp(acceptList[i], l)) {
+                if(outResult) { 
+                    *outResult = ULOC_ACCEPT_VALID;
+                }
+#if defined(ULOC_DEBUG)
+                fprintf(stderr, "MATCH! %s\n", l);
+#endif
+                if(len>0) {
+                    uprv_strncpy(result, l, uprv_min(len, resultAvailable));
+                }
+                for(j=0;j<i;j++) {
+                    uprv_free(fallbackList[j]);
+                }
+                uprv_free(fallbackList);
+                return u_terminateChars(result, resultAvailable, len, status);   
+            }
+            if(len>maxLen) {
+                maxLen = len;
+            }
+        }
+        uenum_reset(availableLocales, status);    
+        /* save off parent info */
+        if(uloc_getParent(acceptList[i], tmp, sizeof(tmp)/sizeof(tmp[0]), status)!=0) {
+            fallbackList[i] = uprv_strdup(tmp);
+        } else {
+            fallbackList[i]=0;
+        }
+    }
+
+    for(maxLen--;maxLen>0;maxLen--) {
+        for(i=0;i<acceptListCount;i++) {
+            if(fallbackList[i] && ((int32_t)uprv_strlen(fallbackList[i])==maxLen)) {
+#if defined(ULOC_DEBUG)
+                fprintf(stderr,"Try: [%s]", fallbackList[i]);
+#endif
+                while((l=uenum_next(availableLocales, NULL, status))) {
+#if defined(ULOC_DEBUG)
+                    fprintf(stderr,"  %s\n", l);
+#endif
+                    len = (int32_t)uprv_strlen(l);
+                    if(!uprv_strcmp(fallbackList[i], l)) {
+                        if(outResult) { 
+                            *outResult = ULOC_ACCEPT_FALLBACK;
+                        }
+#if defined(ULOC_DEBUG)
+                        fprintf(stderr, "fallback MATCH! %s\n", l);
+#endif
+                        if(len>0) {
+                            uprv_strncpy(result, l, uprv_min(len, resultAvailable));
+                        }
+                        for(j=0;j<acceptListCount;j++) {
+                            uprv_free(fallbackList[j]);
+                        }
+                        uprv_free(fallbackList);
+                        return u_terminateChars(result, resultAvailable, len, status);
+                    }
+                }
+                uenum_reset(availableLocales, status);    
+
+                if(uloc_getParent(fallbackList[i], tmp, sizeof(tmp)/sizeof(tmp[0]), status)!=0) {
+                    uprv_free(fallbackList[i]);
+                    fallbackList[i] = uprv_strdup(tmp);
+                } else {
+                    uprv_free(fallbackList[i]);
+                    fallbackList[i]=0;
+                }
+            }
+        }
+        if(outResult) { 
+            *outResult = ULOC_ACCEPT_FAILED;
+        }
+    }
+    for(i=0;i<acceptListCount;i++) {
+        uprv_free(fallbackList[i]);
+    }
+    uprv_free(fallbackList);
+    return -1;
+}
+
+
+/**
+ * This function looks for the localeID in the likelySubtags resource.
+ *
+ * @param localeID The tag to find.
+ * @param buffer A buffer to hold the matching entry
+ * @param bufferLength The length of the output buffer
+ * @return A pointer to "buffer" if found, or a null pointer if not.
+ */
+static const char*  U_CALLCONV
+findLikelySubtags(const char* localeID,
+                  char* buffer,
+                  int32_t bufferLength,
+                  UErrorCode* err) {
+    const char* result = NULL;
+
+    if (!U_FAILURE(*err)) {
+        int32_t resLen = 0;
+        const UChar* s = NULL;
+        UResourceBundle* subtags = ures_openDirect(NULL, "likelySubtags", err);
+        if (!U_FAILURE(*err)) {
+            s = ures_getStringByKey(subtags, localeID, &resLen, err);
+
+            if (U_FAILURE(*err)) {
+                /*
+                 * If a resource is missing, it's not really an error, it's
+                 * just that we don't have any data for that particular locale ID.
+                 */
+                if (*err == U_MISSING_RESOURCE_ERROR) {
+                    *err = U_ZERO_ERROR;
+                }
+            }
+            else if (resLen >= bufferLength) {
+                /* The buffer should never overflow. */
+                *err = U_INTERNAL_PROGRAM_ERROR;
+            }
+            else {
+                u_UCharsToChars(s, buffer, resLen + 1);
+                result = buffer;
+            }
+
+            ures_close(subtags);
+        }
+    }
+
+    return result;
+}
+
+/**
+ * Append a tag to a buffer, adding the separator if necessary.  The buffer
+ * must be large enough to contain the resulting tag plus any separator
+ * necessary. The tag must not be a zero-length string.
+ *
+ * @param tag The tag to add.
+ * @param tagLength The length of the tag.
+ * @param buffer The output buffer.
+ * @param bufferLength The length of the output buffer.  This is an input/ouput parameter.
+ **/
+static void U_CALLCONV
+appendTag(
+    const char* tag,
+    int32_t tagLength,
+    char* buffer,
+    int32_t* bufferLength) {
+
+    if (*bufferLength > 0) {
+        buffer[*bufferLength] = '_';
+        ++(*bufferLength);
+    }
+
+    uprv_memmove(
+        &buffer[*bufferLength],
+        tag,
+        tagLength);
+
+    *bufferLength += tagLength;
+}
+
+/**
+ * These are the canonical strings for unknown languages, scripts and regions.
+ **/
+static const char* const unknownLanguage = "und";
+static const char* const unknownScript = "Zzzz";
+static const char* const unknownRegion = "ZZ";
+
+/**
+ * Create a tag string from the supplied parameters.  The lang, script and region
+ * parameters may be NULL pointers. If they are, their corresponding length parameters
+ * must be less than or equal to 0.
+ *
+ * If any of the language, script or region parameters are empty, and the alternateTags
+ * parameter is not NULL, it will be parsed for potential language, script and region tags
+ * to be used when constructing the new tag.  If the alternateTags parameter is NULL, or
+ * it contains no language tag, the default tag for the unknown language is used.
+ *
+ * If the length of the new string exceeds the capacity of the output buffer, 
+ * the function copies as many bytes to the output buffer as it can, and returns
+ * the error U_BUFFER_OVERFLOW_ERROR.
+ *
+ * If an illegal argument is provided, the function returns the error
+ * U_ILLEGAL_ARGUMENT_ERROR.
+ *
+ * Note that this function can return the warning U_STRING_NOT_TERMINATED_WARNING if
+ * the tag string fits in the output buffer, but the null terminator doesn't.
+ *
+ * @param lang The language tag to use.
+ * @param langLength The length of the language tag.
+ * @param script The script tag to use.
+ * @param scriptLength The length of the script tag.
+ * @param region The region tag to use.
+ * @param regionLength The length of the region tag.
+ * @param trailing Any trailing data to append to the new tag.
+ * @param trailingLength The length of the trailing data.
+ * @param alternateTags A string containing any alternate tags.
+ * @param tag The output buffer.
+ * @param tagCapacity The capacity of the output buffer.
+ * @param err A pointer to a UErrorCode for error reporting.
+ * @return The length of the tag string, which may be greater than tagCapacity, or -1 on error.
+ **/
+static int32_t U_CALLCONV
+createTagStringWithAlternates(
+    const char* lang,
+    int32_t langLength,
+    const char* script,
+    int32_t scriptLength,
+    const char* region,
+    int32_t regionLength,
+    const char* trailing,
+    int32_t trailingLength,
+    const char* alternateTags,
+    char* tag,
+    int32_t tagCapacity,
+    UErrorCode* err) {
+
+    if (U_FAILURE(*err)) {
+        goto error;
+    }
+    else if (tag == NULL ||
+             tagCapacity <= 0 ||
+             langLength >= ULOC_LANG_CAPACITY ||
+             scriptLength >= ULOC_SCRIPT_CAPACITY ||
+             regionLength >= ULOC_COUNTRY_CAPACITY) {
+        goto error;
+    }
+    else {
+        /**
+         * ULOC_FULLNAME_CAPACITY will provide enough capacity
+         * that we can build a string that contains the language,
+         * script and region code without worrying about overrunning
+         * the user-supplied buffer.
+         **/
+        char tagBuffer[ULOC_FULLNAME_CAPACITY];
+        int32_t tagLength = 0;
+        int32_t capacityRemaining = tagCapacity;
+        UBool regionAppended = FALSE;
+
+        if (langLength > 0) {
+            appendTag(
+                lang,
+                langLength,
+                tagBuffer,
+                &tagLength);
+        }
+        else if (alternateTags == NULL) {
+            /*
+             * Append the value for an unknown language, if
+             * we found no language.
+             */
+            appendTag(
+                unknownLanguage,
+                uprv_strlen(unknownLanguage),
+                tagBuffer,
+                &tagLength);
+        }
+        else {
+            /*
+             * Parse the alternateTags string for the language.
+             */
+            char alternateLang[ULOC_LANG_CAPACITY];
+            int32_t alternateLangLength = sizeof(alternateLang);
+
+            alternateLangLength =
+                uloc_getLanguage(
+                    alternateTags,
+                    alternateLang,
+                    alternateLangLength,
+                    err);
+            if(U_FAILURE(*err) ||
+                alternateLangLength >= ULOC_LANG_CAPACITY) {
+                goto error;
+            }
+            else if (alternateLangLength == 0) {
+                /*
+                 * Append the value for an unknown language, if
+                 * we found no language.
+                 */
+                appendTag(
+                    unknownLanguage,
+                    uprv_strlen(unknownLanguage),
+                    tagBuffer,
+                    &tagLength);
+            }
+            else {
+                appendTag(
+                    alternateLang,
+                    alternateLangLength,
+                    tagBuffer,
+                    &tagLength);
+            }
+        }
+
+        if (scriptLength > 0) {
+            appendTag(
+                script,
+                scriptLength,
+                tagBuffer,
+                &tagLength);
+        }
+        else if (alternateTags != NULL) {
+            /*
+             * Parse the alternateTags string for the script.
+             */
+            char alternateScript[ULOC_SCRIPT_CAPACITY];
+
+            const int32_t alternateScriptLength =
+                uloc_getScript(
+                    alternateTags,
+                    alternateScript,
+                    sizeof(alternateScript),
+                    err);
+
+            if (U_FAILURE(*err) ||
+                alternateScriptLength >= ULOC_SCRIPT_CAPACITY) {
+                goto error;
+            }
+            else if (alternateScriptLength > 0) {
+                appendTag(
+                    alternateScript,
+                    alternateScriptLength,
+                    tagBuffer,
+                    &tagLength);
+            }
+        }
+
+        if (regionLength > 0) {
+            appendTag(
+                region,
+                regionLength,
+                tagBuffer,
+                &tagLength);
+
+            regionAppended = TRUE;
+        }
+        else if (alternateTags != NULL) {
+            /*
+             * Parse the alternateTags string for the region.
+             */
+            char alternateRegion[ULOC_COUNTRY_CAPACITY];
+
+            const int32_t alternateRegionLength =
+                uloc_getCountry(
+                    alternateTags,
+                    alternateRegion,
+                    sizeof(alternateRegion),
+                    err);
+            if (U_FAILURE(*err) ||
+                alternateRegionLength >= ULOC_COUNTRY_CAPACITY) {
+                goto error;
+            }
+            else if (alternateRegionLength > 0) {
+                appendTag(
+                    alternateRegion,
+                    alternateRegionLength,
+                    tagBuffer,
+                    &tagLength);
+
+                regionAppended = TRUE;
+            }
+        }
+
+        {
+            const int32_t toCopy =
+                tagLength >= tagCapacity ? tagCapacity : tagLength;
+
+            /**
+             * Copy the partial tag from our internal buffer to the supplied
+             * target.
+             **/
+            uprv_memcpy(
+                tag,
+                tagBuffer,
+                toCopy);
+
+            capacityRemaining -= toCopy;
+        }
+
+        if (trailingLength > 0) {
+            if (capacityRemaining > 0 && !regionAppended) {
+                tag[tagLength++] = '_';
+                --capacityRemaining;
+            }
+
+            if (capacityRemaining > 0) {
+                /*
+                 * Copy the trailing data into the supplied buffer.  Use uprv_memmove, since we
+                 * don't know if the user-supplied buffers overlap.
+                 */
+                const int32_t toCopy =
+                    trailingLength >= capacityRemaining ? capacityRemaining : trailingLength;
+
+                uprv_memmove(
+                    &tag[tagLength],
+                    trailing,
+                    toCopy);
+            }
+        }
+
+        tagLength += trailingLength;
+
+        return u_terminateChars(
+                    tag,
+                    tagCapacity,
+                    tagLength,
+                    err);
+    }
+
+error:
+
+    /**
+     * An overflow indicates the locale ID passed in
+     * is ill-formed.  If we got here, and there was
+     * no previous error, it's an implicit overflow.
+     **/
+    if (*err ==  U_BUFFER_OVERFLOW_ERROR ||
+        U_SUCCESS(*err)) {
+        *err = U_ILLEGAL_ARGUMENT_ERROR;
+    }
+
+    return -1;
+}
+
+/**
+ * Create a tag string from the supplied parameters.  The lang, script and region
+ * parameters may be NULL pointers. If they are, their corresponding length parameters
+ * must be less than or equal to 0.  If the lang parameter is an empty string, the
+ * default value for an unknown language is written to the output buffer.
+ *
+ * If the length of the new string exceeds the capacity of the output buffer, 
+ * the function copies as many bytes to the output buffer as it can, and returns
+ * the error U_BUFFER_OVERFLOW_ERROR.
+ *
+ * If an illegal argument is provided, the function returns the error
+ * U_ILLEGAL_ARGUMENT_ERROR.
+ *
+ * @param lang The language tag to use.
+ * @param langLength The length of the language tag.
+ * @param script The script tag to use.
+ * @param scriptLength The length of the script tag.
+ * @param region The region tag to use.
+ * @param regionLength The length of the region tag.
+ * @param trailing Any trailing data to append to the new tag.
+ * @param trailingLength The length of the trailing data.
+ * @param tag The output buffer.
+ * @param tagCapacity The capacity of the output buffer.
+ * @param err A pointer to a UErrorCode for error reporting.
+ * @return The length of the tag string, which may be greater than tagCapacity.
+ **/
+static int32_t U_CALLCONV
+createTagString(
+    const char* lang,
+    int32_t langLength,
+    const char* script,
+    int32_t scriptLength,
+    const char* region,
+    int32_t regionLength,
+    const char* trailing,
+    int32_t trailingLength,
+    char* tag,
+    int32_t tagCapacity,
+    UErrorCode* err)
+{
+    return createTagStringWithAlternates(
+                lang,
+                langLength,
+                script,
+                scriptLength,
+                region,
+                regionLength,
+                trailing,
+                trailingLength,
+                NULL,
+                tag,
+                tagCapacity,
+                err);
+}
+
+/**
+ * Parse the language, script, and region subtags from a tag string, and copy the
+ * results into the corresponding output parameters. The buffers are null-terminated,
+ * unless overflow occurs.
+ *
+ * The langLength, scriptLength, and regionLength parameters are input/output
+ * parameters, and must contain the capacity of their corresponding buffers on
+ * input.  On output, they will contain the actual length of the buffers, not
+ * including the null terminator.
+ *
+ * If the length of any of the output subtags exceeds the capacity of the corresponding
+ * buffer, the function copies as many bytes to the output buffer as it can, and returns
+ * the error U_BUFFER_OVERFLOW_ERROR.  It will not parse any more subtags once overflow
+ * occurs.
+ *
+ * If an illegal argument is provided, the function returns the error
+ * U_ILLEGAL_ARGUMENT_ERROR.
+ *
+ * @param localeID The locale ID to parse.
+ * @param lang The language tag buffer.
+ * @param langLength The length of the language tag.
+ * @param script The script tag buffer.
+ * @param scriptLength The length of the script tag.
+ * @param region The region tag buffer.
+ * @param regionLength The length of the region tag.
+ * @param err A pointer to a UErrorCode for error reporting.
+ * @return The number of chars of the localeID parameter consumed.
+ **/
+static int32_t U_CALLCONV
+parseTagString(
+    const char* localeID,
+    char* lang,
+    int32_t* langLength,
+    char* script,
+    int32_t* scriptLength,
+    char* region,
+    int32_t* regionLength,
+    UErrorCode* err)
+{
+    const char* position = localeID;
+    int32_t subtagLength = 0;
+
+    if(U_FAILURE(*err) ||
+       localeID == NULL ||
+       lang == NULL ||
+       langLength == NULL ||
+       script == NULL ||
+       scriptLength == NULL ||
+       region == NULL ||
+       regionLength == NULL) {
+        goto error;
+    }
+
+    subtagLength = _getLanguage(position, lang, *langLength, &position);
+    u_terminateChars(lang, *langLength, subtagLength, err);
+
+    /*
+     * Note that we explicit consider U_STRING_NOT_TERMINATED_WARNING
+     * to be an error, because it indicates the user-supplied tag is
+     * not well-formed.
+     */
+    if(*err != U_ZERO_ERROR) {
+        goto error;
+    }
+
+    *langLength = subtagLength;
+
+    /*
+     * If no language was present, use the value of unknownLanguage
+     * instead.  Otherwise, move past any separator.
+     */
+    if (*langLength == 0) {
+        uprv_strcpy(
+            lang,
+            unknownLanguage);
+        *langLength = uprv_strlen(lang);
+    }
+    else if (_isIDSeparator(*position)) {
+        ++position;
+    }
+
+    subtagLength = _getScript(position, script, *scriptLength, &position);
+    u_terminateChars(script, *scriptLength, subtagLength, err);
+
+    if(*err != U_ZERO_ERROR) {
+        goto error;
+    }
+
+    *scriptLength = subtagLength;
+
+    if (*scriptLength > 0) {
+        if (uprv_strnicmp(script, unknownScript, *scriptLength) == 0) {
+            /**
+             * If the script part is the "unknown" script, then don't return it.
+             **/
+            *scriptLength = 0;
+        }
+
+        /*
+         * Move past any separator.
+         */
+        if (_isIDSeparator(*position)) {
+            ++position;
+        }    
+    }
+
+    subtagLength = _getCountry(position, region, *regionLength, &position);
+    u_terminateChars(region, *regionLength, subtagLength, err);
+
+    if(*err != U_ZERO_ERROR) {
+        goto error;
+    }
+
+    *regionLength = subtagLength;
+
+    if (*regionLength > 0) {
+        if (uprv_strnicmp(region, unknownRegion, *regionLength) == 0) {
+            /**
+             * If the region part is the "unknown" region, then don't return it.
+             **/
+            *regionLength = 0;
+        }
+    }
+
+exit:
+
+    return (int32_t)(position - localeID);
+
+error:
+
+    /**
+     * If we get here, we have no explicit error, it's the result of an
+     * illegal argument.
+     **/
+    if (!U_FAILURE(*err)) {
+        *err = U_ILLEGAL_ARGUMENT_ERROR;
+    }
+
+    goto exit;
+}
+
+static int32_t U_CALLCONV
+createLikelySubtagsString(
+    const char* lang,
+    int32_t langLength,
+    const char* script,
+    int32_t scriptLength,
+    const char* region,
+    int32_t regionLength,
+    const char* variants,
+    int32_t variantsLength,
+    char* tag,
+    int32_t tagCapacity,
+    UErrorCode* err)
+{
+    /**
+     * ULOC_FULLNAME_CAPACITY will provide enough capacity
+     * that we can build a string that contains the language,
+     * script and region code without worrying about overrunning
+     * the user-supplied buffer.
+     **/
+    char tagBuffer[ULOC_FULLNAME_CAPACITY];
+    char likelySubtagsBuffer[ULOC_FULLNAME_CAPACITY];
+    int32_t tagBufferLength = 0;
+
+    if(U_FAILURE(*err)) {
+        goto error;
+    }
+
+    /**
+     * Try the language with the script and region first.
+     **/
+    if (scriptLength > 0 && regionLength > 0) {
+
+        const char* likelySubtags = NULL;
+
+        tagBufferLength = createTagString(
+            lang,
+            langLength,
+            script,
+            scriptLength,
+            region,
+            regionLength,
+            NULL,
+            0,
+            tagBuffer,
+            sizeof(tagBuffer),
+            err);
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+
+        likelySubtags =
+            findLikelySubtags(
+                tagBuffer,
+                likelySubtagsBuffer,
+                sizeof(likelySubtagsBuffer),
+                err);
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+
+        if (likelySubtags != NULL) {
+            /* Always use the language tag from the
+               maximal string, since it may be more
+               specific than the one provided. */
+            return createTagStringWithAlternates(
+                        NULL,
+                        0,
+                        NULL,
+                        0,
+                        NULL,
+                        0,
+                        variants,
+                        variantsLength,
+                        likelySubtags,
+                        tag,
+                        tagCapacity,
+                        err);
+        }
+    }
+
+    /**
+     * Try the language with just the script.
+     **/
+    if (scriptLength > 0) {
+
+        const char* likelySubtags = NULL;
+
+        tagBufferLength = createTagString(
+            lang,
+            langLength,
+            script,
+            scriptLength,
+            NULL,
+            0,
+            NULL,
+            0,
+            tagBuffer,
+            sizeof(tagBuffer),
+            err);
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+
+        likelySubtags =
+            findLikelySubtags(
+                tagBuffer,
+                likelySubtagsBuffer,
+                sizeof(likelySubtagsBuffer),
+                err);
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+
+        if (likelySubtags != NULL) {
+            /* Always use the language tag from the
+               maximal string, since it may be more
+               specific than the one provided. */
+            return createTagStringWithAlternates(
+                        NULL,
+                        0,
+                        NULL,
+                        0,
+                        region,
+                        regionLength,
+                        variants,
+                        variantsLength,
+                        likelySubtags,
+                        tag,
+                        tagCapacity,
+                        err);
+        }
+    }
+
+    /**
+     * Try the language with just the region.
+     **/
+    if (regionLength > 0) {
+
+        const char* likelySubtags = NULL;
+
+        createTagString(
+            lang,
+            langLength,
+            NULL,
+            0,
+            region,
+            regionLength,
+            NULL,
+            0,
+            tagBuffer,
+            sizeof(tagBuffer),
+            err);
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+
+        likelySubtags =
+            findLikelySubtags(
+                tagBuffer,
+                likelySubtagsBuffer,
+                sizeof(likelySubtagsBuffer),
+                err);
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+
+        if (likelySubtags != NULL) {
+            /* Always use the language tag from the
+               maximal string, since it may be more
+               specific than the one provided. */
+            return createTagStringWithAlternates(
+                        NULL,
+                        0,
+                        script,
+                        scriptLength,
+                        NULL,
+                        0,
+                        variants,
+                        variantsLength,
+                        likelySubtags,
+                        tag,
+                        tagCapacity,
+                        err);
+        }
+    }
+
+    /**
+     * Finally, try just the language.
+     **/
+    {
+        const char* likelySubtags = NULL;
+
+        createTagString(
+            lang,
+            langLength,
+            NULL,
+            0,
+            NULL,
+            0,
+            NULL,
+            0,
+            tagBuffer,
+            sizeof(tagBuffer),
+            err);
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+
+        likelySubtags =
+            findLikelySubtags(
+                tagBuffer,
+                likelySubtagsBuffer,
+                sizeof(likelySubtagsBuffer),
+                err);
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+
+        if (likelySubtags != NULL) {
+            /* Always use the language tag from the
+               maximal string, since it may be more
+               specific than the one provided. */
+            return createTagStringWithAlternates(
+                        NULL,
+                        0,
+                        script,
+                        scriptLength,
+                        region,
+                        regionLength,
+                        variants,
+                        variantsLength,
+                        likelySubtags,
+                        tag,
+                        tagCapacity,
+                        err);
+        }
+    }
+
+    return u_terminateChars(
+                tag,
+                tagCapacity,
+                0,
+                err);
+
+error:
+
+    if (!U_FAILURE(*err)) {
+        *err = U_ILLEGAL_ARGUMENT_ERROR;
+    }
+
+    return -1;
+}
+
+static int32_t
+_uloc_addLikelySubtags(const char*    localeID,
+         char* maximizedLocaleID,
+         int32_t maximizedLocaleIDCapacity,
+         UErrorCode* err)
+{
+    char lang[ULOC_LANG_CAPACITY];
+    int32_t langLength = sizeof(lang);
+    char script[ULOC_SCRIPT_CAPACITY];
+    int32_t scriptLength = sizeof(script);
+    char region[ULOC_COUNTRY_CAPACITY];
+    int32_t regionLength = sizeof(region);
+    const char* trailing = "";
+    int32_t trailingLength = 0;
+    int32_t trailingIndex = 0;
+    int32_t resultLength = 0;
+
+    if(U_FAILURE(*err)) {
+        goto error;
+    }
+    else if (localeID == NULL ||
+             maximizedLocaleID == NULL ||
+             maximizedLocaleIDCapacity <= 0) {
+        goto error;
+    }
+
+    trailingIndex = parseTagString(
+        localeID,
+        lang,
+        &langLength,
+        script,
+        &scriptLength,
+        region,
+        &regionLength,
+        err);
+    if(U_FAILURE(*err)) {
+        /* Overflow indicates an illegal argument error */
+        if (*err == U_BUFFER_OVERFLOW_ERROR) {
+            *err = U_ILLEGAL_ARGUMENT_ERROR;
+        }
+
+        goto error;
+    }
+
+    /* Find the length of the trailing portion. */
+    trailing = &localeID[trailingIndex];
+    trailingLength = uprv_strlen(trailing);
+
+    resultLength =
+        createLikelySubtagsString(
+            lang,
+            langLength,
+            script,
+            scriptLength,
+            region,
+            regionLength,
+            trailing,
+            trailingLength,
+            maximizedLocaleID,
+            maximizedLocaleIDCapacity,
+            err);
+
+    if (resultLength == 0) {
+        const int32_t localIDLength =
+            uprv_strlen(localeID);
+
+        /*
+         * If we get here, we need to return localeID.
+         */
+        uprv_memcpy(
+            maximizedLocaleID,
+            localeID,
+            localIDLength <= maximizedLocaleIDCapacity ? 
+                localIDLength : maximizedLocaleIDCapacity);
+
+        resultLength =
+            u_terminateChars(
+                maximizedLocaleID,
+                maximizedLocaleIDCapacity,
+                localIDLength,
+                err);
+    }
+
+    return resultLength;
+
+error:
+
+    if (!U_FAILURE(*err)) {
+        *err = U_ILLEGAL_ARGUMENT_ERROR;
+    }
+
+    return -1;
+}
+
+static int32_t
+_uloc_minimizeSubtags(const char*    localeID,
+         char* minimizedLocaleID,
+         int32_t minimizedLocaleIDCapacity,
+         UErrorCode* err)
+{
+    /**
+     * ULOC_FULLNAME_CAPACITY will provide enough capacity
+     * that we can build a string that contains the language,
+     * script and region code without worrying about overrunning
+     * the user-supplied buffer.
+     **/
+    char maximizedTagBuffer[ULOC_FULLNAME_CAPACITY];
+    int32_t maximizedTagBufferLength = sizeof(maximizedTagBuffer);
+
+    char lang[ULOC_LANG_CAPACITY];
+    int32_t langLength = sizeof(lang);
+    char script[ULOC_SCRIPT_CAPACITY];
+    int32_t scriptLength = sizeof(script);
+    char region[ULOC_COUNTRY_CAPACITY];
+    int32_t regionLength = sizeof(region);
+    const char* trailing = "";
+    int32_t trailingLength = 0;
+    int32_t trailingIndex = 0;
+
+    if(U_FAILURE(*err)) {
+        goto error;
+    }
+    else if (localeID == NULL ||
+             minimizedLocaleID == NULL ||
+             minimizedLocaleIDCapacity <= 0) {
+        goto error;
+    }
+
+    trailingIndex =
+        parseTagString(
+            localeID,
+            lang,
+            &langLength,
+            script,
+            &scriptLength,
+            region,
+            &regionLength,
+            err);
+    if(U_FAILURE(*err)) {
+
+        /* Overflow indicates an illegal argument error */
+        if (*err == U_BUFFER_OVERFLOW_ERROR) {
+            *err = U_ILLEGAL_ARGUMENT_ERROR;
+        }
+
+        goto error;
+    }
+
+    /* Find the spot where the variants begin, if any. */
+    trailing = &localeID[trailingIndex];
+    trailingLength = uprv_strlen(trailing);
+
+    createTagString(
+        lang,
+        langLength,
+        script,
+        scriptLength,
+        region,
+        regionLength,
+        NULL,
+        0,
+        maximizedTagBuffer,
+        maximizedTagBufferLength,
+        err);
+    if(U_FAILURE(*err)) {
+        goto error;
+    }
+
+    /**
+     * First, we need to first get the maximization
+     * from AddLikelySubtags.
+     **/
+    maximizedTagBufferLength =
+        uloc_addLikelySubtags(
+            maximizedTagBuffer,
+            maximizedTagBuffer,
+            maximizedTagBufferLength,
+            err);
+
+    if(U_FAILURE(*err)) {
+        goto error;
+    }
+
+    /**
+     * Start first with just the language.
+     **/
+    {
+        char tagBuffer[ULOC_FULLNAME_CAPACITY];
+
+        const int32_t tagBufferLength =
+            createLikelySubtagsString(
+                lang,
+                langLength,
+                NULL,
+                0,
+                NULL,
+                0,
+                NULL,
+                0,
+                tagBuffer,
+                sizeof(tagBuffer),
+                err);
+
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+        else if (uprv_strnicmp(
+                    maximizedTagBuffer,
+                    tagBuffer,
+                    tagBufferLength) == 0) {
+
+            return createTagString(
+                        lang,
+                        langLength,
+                        NULL,
+                        0,
+                        NULL,
+                        0,
+                        trailing,
+                        trailingLength,
+                        minimizedLocaleID,
+                        minimizedLocaleIDCapacity,
+                        err);
+        }
+    }
+
+    /**
+     * Next, try the language and region.
+     **/
+    if (regionLength > 0) {
+
+        char tagBuffer[ULOC_FULLNAME_CAPACITY];
+
+        const int32_t tagBufferLength =
+            createLikelySubtagsString(
+                lang,
+                langLength,
+                NULL,
+                0,
+                region,
+                regionLength,
+                NULL,
+                0,
+                tagBuffer,
+                sizeof(tagBuffer),
+                err);
+
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+        else if (uprv_strnicmp(
+                    maximizedTagBuffer,
+                    tagBuffer,
+                    tagBufferLength) == 0) {
+
+            return createTagString(
+                        lang,
+                        langLength,
+                        NULL,
+                        0,
+                        region,
+                        regionLength,
+                        trailing,
+                        trailingLength,
+                        minimizedLocaleID,
+                        minimizedLocaleIDCapacity,
+                        err);
+        }
+    }
+
+    /**
+     * Finally, try the language and script.  This is our last chance,
+     * since trying with all three subtags would only yield the
+     * maximal version that we already have.
+     **/
+    if (scriptLength > 0 && regionLength > 0) {
+        char tagBuffer[ULOC_FULLNAME_CAPACITY];
+
+        const int32_t tagBufferLength =
+            createLikelySubtagsString(
+                lang,
+                langLength,
+                script,
+                scriptLength,
+                NULL,
+                0,
+                NULL,
+                0,
+                tagBuffer,
+                sizeof(tagBuffer),
+                err);
+
+        if(U_FAILURE(*err)) {
+            goto error;
+        }
+        else if (uprv_strnicmp(
+                    maximizedTagBuffer,
+                    tagBuffer,
+                    tagBufferLength) == 0) {
+
+            return createTagString(
+                        lang,
+                        langLength,
+                        script,
+                        scriptLength,
+                        NULL,
+                        0,
+                        trailing,
+                        trailingLength,
+                        minimizedLocaleID,
+                        minimizedLocaleIDCapacity,
+                        err);
+        }
+    }
+
+    {
+        /**
+         * If we got here, return the locale ID parameter.
+         **/
+        const int32_t localeIDLength = uprv_strlen(localeID);
+
+        uprv_memcpy(
+            minimizedLocaleID,
+            localeID,
+            localeIDLength <= minimizedLocaleIDCapacity ? 
+                localeIDLength : minimizedLocaleIDCapacity);
+
+        return u_terminateChars(
+                    minimizedLocaleID,
+                    minimizedLocaleIDCapacity,
+                    localeIDLength,
+                    err);
+    }
+
+error:
+
+    if (!U_FAILURE(*err)) {
+        *err = U_ILLEGAL_ARGUMENT_ERROR;
+    }
+
+    return -1;
+
+
+}
+
+static UBool
+do_canonicalize(const char*    localeID,
+         char* buffer,
+         int32_t bufferCapacity,
+         UErrorCode* err)
+{
+    uloc_canonicalize(
+        localeID,
+        buffer,
+        bufferCapacity,
+        err);
+
+    if (*err == U_STRING_NOT_TERMINATED_WARNING ||
+        *err == U_BUFFER_OVERFLOW_ERROR) {
+        *err = U_ILLEGAL_ARGUMENT_ERROR;
+
+        return FALSE;
+    }
+    else if (U_FAILURE(*err)) {
+
+        return FALSE;
+    }
+    else {
+        return TRUE;
+    }
+}
+
+U_DRAFT int32_t U_EXPORT2
+uloc_addLikelySubtags(const char*    localeID,
+         char* maximizedLocaleID,
+         int32_t maximizedLocaleIDCapacity,
+         UErrorCode* err)
+{
+    char localeBuffer[ULOC_FULLNAME_CAPACITY];
+
+    if (!do_canonicalize(
+        localeID,
+        localeBuffer,
+        sizeof(localeBuffer),
+        err)) {
+        return -1;
+    }
+    else {
+        return _uloc_addLikelySubtags(
+                    localeBuffer,
+                    maximizedLocaleID,
+                    maximizedLocaleIDCapacity,
+                    err);
+    }    
+}
+
+U_DRAFT int32_t U_EXPORT2
+uloc_minimizeSubtags(const char*    localeID,
+         char* minimizedLocaleID,
+         int32_t minimizedLocaleIDCapacity,
+         UErrorCode* err)
+{
+    char localeBuffer[ULOC_FULLNAME_CAPACITY];
+
+    if (!do_canonicalize(
+        localeID,
+        localeBuffer,
+        sizeof(localeBuffer),
+        err)) {
+        return -1;
+    }
+    else {
+        return _uloc_minimizeSubtags(
+                    localeBuffer,
+                    minimizedLocaleID,
+                    minimizedLocaleIDCapacity,
+                    err);
+    }    
+}
+
+/*eof*/
diff -Nura icu/source/common/unicode/utf8.h icu_new/source/common/unicode/utf8.h
--- icu/source/common/unicode/utf8.h	2008-07-01 09:41:08.000000000 +0800
+++ icu_new/source/common/unicode/utf8.h	2018-05-25 16:40:13.204866302 +0800
@@ -69,6 +69,40 @@
 #define U8_MASK_LEAD_BYTE(leadByte, countTrailBytes) ((leadByte)&=(1<<(6-(countTrailBytes)))-1)
 
 /**
+ * Internal bit vector for 3-byte UTF-8 validity check, for use in U8_IS_VALID_LEAD3_AND_T1.
+ * Each bit indicates whether one lead byte + first trail byte pair starts a valid sequence.
+ * Lead byte E0..EF bits 3..0 are used as byte index,
+ * first trail byte bits 7..5 are used as bit index into that byte.
+ * @see U8_IS_VALID_LEAD3_AND_T1
+ * @internal
+ */
+#define U8_LEAD3_T1_BITS "\x20\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x10\x30\x30"
+
+/**
+ * Internal 3-byte UTF-8 validity check.
+ * Non-zero if lead byte E0..EF and first trail byte 00..FF start a valid sequence.
+ * @internal
+ */
+#define U8_IS_VALID_LEAD3_AND_T1(lead, t1) (U8_LEAD3_T1_BITS[(lead)&0xf]&(1<<((uint8_t)(t1)>>5)))
+
+/**
+ * Internal bit vector for 4-byte UTF-8 validity check, for use in U8_IS_VALID_LEAD4_AND_T1.
+ * Each bit indicates whether one lead byte + first trail byte pair starts a valid sequence.
+ * First trail byte bits 7..4 are used as byte index,
+ * lead byte F0..F4 bits 2..0 are used as bit index into that byte.
+ * @see U8_IS_VALID_LEAD4_AND_T1
+ * @internal
+ */
+#define U8_LEAD4_T1_BITS "\x00\x00\x00\x00\x00\x00\x00\x00\x1E\x0F\x0F\x0F\x00\x00\x00\x00"
+
+/**
+ * Internal 4-byte UTF-8 validity check.
+ * Non-zero if lead byte F0..F4 and first trail byte 00..FF start a valid sequence.
+ * @internal
+ */
+#define U8_IS_VALID_LEAD4_AND_T1(lead, t1) (U8_LEAD4_T1_BITS[(uint8_t)(t1)>>4]&(1<<((lead)&7)))
+
+/**
  * Function for handling "next code point" with error-checking.
  * @internal
  */
diff -Nura icu/source/common/utext.cpp icu_new/source/common/utext.cpp
--- icu/source/common/utext.cpp	2008-07-01 09:41:12.000000000 +0800
+++ icu_new/source/common/utext.cpp	2018-05-25 11:08:35.599723818 +0800
@@ -869,7 +869,7 @@
                                                      //  Requires two extra slots,
                                                      //    one for a supplementary starting in the last normal position,
                                                      //    and one for an entry for the buffer limit position.
-    uint8_t   mapToUChars[UTF8_TEXT_CHUNK_SIZE*3+6]; // Map native offset from bufNativeStart to
+    uint8_t   mapToUChars[UTF8_TEXT_CHUNK_SIZE*6+6]; // Map native offset from bufNativeStart to
                                                      //   correspoding offset in filled part of buf.
     int32_t   align;
 };
@@ -1012,6 +1012,7 @@
             // Requested index is in this buffer.
             u8b = (UTF8Buf *)ut->p;   // the current buffer
             mapIndex = ix - u8b->toUCharsMapStart;
+            U_ASSERT(mapIndex < (int32_t)sizeof(UTF8Buf::mapToUChars));
             ut->chunkOffset = u8b->mapToUChars[mapIndex] - u8b->bufStartIdx;
             return TRUE;
 
@@ -1321,9 +1322,10 @@
             c = s8[srcIx];
             if (c<0x80) {
                 // Special case ASCII range for speed.
-                buf[destIx] = c;
-                mapToUChars[srcIx - toUCharsMapStart] = destIx;
-                mapToNative[destIx] = srcIx - toUCharsMapStart;
+                buf[destIx] = (UChar)c;
+                U_ASSERT(toUCharsMapStart <= srcIx);
+                mapToUChars[srcIx - toUCharsMapStart] = (uint8_t)destIx;
+                mapToNative[destIx] = (uint8_t)(srcIx - toUCharsMapStart);
             } else {
                 // General case, handle everything non-ASCII.
 
@@ -1355,6 +1357,7 @@
                 do {
                     mapToUChars[sIx-- - toUCharsMapStart] = destIx;
                 } while (sIx >= srcIx);
+                U_ASSERT(toUCharsMapStart <= (srcIx+1));
 
                 // Set native indexing limit to be the current position.
                 //   We are processing a non-ascii, non-native-indexing char now;
@@ -1534,6 +1537,7 @@
     U_ASSERT(index>=ut->chunkNativeStart+ut->nativeIndexingLimit);
     U_ASSERT(index<=ut->chunkNativeLimit);
     int32_t mapIndex = index - u8b->toUCharsMapStart;
+    U_ASSERT(mapIndex < (int32_t)sizeof(UTF8Buf::mapToUChars));
     int32_t offset = u8b->mapToUChars[mapIndex] - u8b->bufStartIdx;
     U_ASSERT(offset>=0 && offset<=ut->chunkLength);
     return offset;
diff -Nura icu/source/i18n/astro.cpp icu_new/source/i18n/astro.cpp
--- icu/source/i18n/astro.cpp	2008-07-01 09:40:50.000000000 +0800
+++ icu_new/source/i18n/astro.cpp	2018-05-25 14:46:47.148749018 +0800
@@ -207,7 +207,7 @@
  * The modulus operator.
  */
 inline static double normalize(double value, double range)  {
-    return value - range * Math::floorDivide(value, range);
+    return value - range * ClockMath::floorDivide(value, range);
 }
 
 /**
@@ -417,7 +417,7 @@
     double lt = normalize((lst - getSiderealOffset()) * 0.9972695663, 24);
 
     // Then find local midnight on this day
-    double base = (DAY_MS * Math::floorDivide(fTime + fGmtOffset,(double)DAY_MS)) - fGmtOffset;
+    double base = (DAY_MS * ClockMath::floorDivide(fTime + fGmtOffset,(double)DAY_MS)) - fGmtOffset;
 
     //out("    lt  =" + lt + " hours");
     //out("    base=" + new Date(base));
@@ -742,7 +742,7 @@
     UDate t0 = fTime;
 
     // Make a rough guess: 6am or 6pm local time on the current day
-    double noon = Math::floorDivide(fTime + fGmtOffset, (double)DAY_MS)*DAY_MS - fGmtOffset + (12*HOUR_MS);
+    double noon = ClockMath::floorDivide(fTime + fGmtOffset, (double)DAY_MS)*DAY_MS - fGmtOffset + (12*HOUR_MS);
 
     U_DEBUG_ASTRO_MSG(("Noon=%.2lf, %sL, gmtoff %.2lf\n", noon, debug_astro_date(noon+fGmtOffset), fGmtOffset));
     setTime(noon +  ((rise ? -6 : 6) * HOUR_MS));
diff -Nura icu/source/i18n/calendar.cpp icu_new/source/i18n/calendar.cpp
--- icu/source/i18n/calendar.cpp	2008-07-01 09:40:48.000000000 +0800
+++ icu_new/source/i18n/calendar.cpp	2018-05-25 14:37:11.893932785 +0800
@@ -10,8 +10,8 @@
 *
 *   Date        Name        Description
 *   02/03/97    clhuang     Creation.
-*   04/22/97    aliu        Cleaned up, fixed memory leak, made 
-*                           setWeekCountData() more robust.  
+*   04/22/97    aliu        Cleaned up, fixed memory leak, made
+*                           setWeekCountData() more robust.
 *                           Moved platform code to TPlatformUtilities.
 *   05/01/97    aliu        Made equals(), before(), after() arguments const.
 *   05/20/97    aliu        Changed logic of when to compute fields and time
@@ -76,9 +76,9 @@
 
 #if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
 
-/** 
- * fldName was removed as a duplicate implementation. 
- * use  udbg_ services instead, 
+/**
+ * fldName was removed as a duplicate implementation.
+ * use  udbg_ services instead,
  * which depend on include files and library from ../tools/ctestfw
  */
 #include "unicode/udbgutil.h"
@@ -104,7 +104,7 @@
 void Calendar::dump() const {
     int i;
     fprintf(stderr, "@calendar=%s, timeset=%c, fieldset=%c, allfields=%c, virtualset=%c, t=%.2f",
-        getType(), fIsTimeSet?'y':'n',  fAreFieldsSet?'y':'n',  fAreAllFieldsSet?'y':'n',  
+        getType(), fIsTimeSet?'y':'n',  fAreFieldsSet?'y':'n',  fAreAllFieldsSet?'y':'n',
         fAreFieldsVirtuallySet?'y':'n',
         fTime);
 
@@ -116,9 +116,9 @@
         fprintf(stderr, "  %25s: %-11ld", f, fFields[i]);
         if(fStamp[i] == kUnset) {
             fprintf(stderr, " (unset) ");
-        } else if(fStamp[i] == kInternallySet) { 
+        } else if(fStamp[i] == kInternallySet) {
             fprintf(stderr, " (internally set) ");
-            //} else if(fStamp[i] == kInternalDefault) { 
+            //} else if(fStamp[i] == kInternalDefault) {
             //    fprintf(stderr, " (internal default) ");
         } else {
             fprintf(stderr, " %%%d ", fStamp[i]);
@@ -154,7 +154,7 @@
 
 U_NAMESPACE_BEGIN
 
-static UBool isStandardSupportedKeyword(const char *keyword, UErrorCode& status) { 
+static UBool isStandardSupportedKeyword(const char *keyword, UErrorCode& status) {
     if(U_FAILURE(status)) {
         return FALSE;
     }
@@ -182,7 +182,7 @@
 
 static Calendar *createStandardCalendar(char *calType, const Locale &canLoc, UErrorCode& status) {
 #ifdef U_DEBUG_CALSVC
-    fprintf(stderr, "BasicCalendarFactory %p: creating type for %s\n", 
+    fprintf(stderr, "BasicCalendarFactory %p: creating type for %s\n",
         this, (const char*)curLoc.getName());
     fflush(stderr);
 #endif
@@ -213,7 +213,7 @@
         return new EthiopicCalendar(canLoc, status, EthiopicCalendar::AMETE_MIHRET_ERA);
     } else if(!uprv_strcmp(calType, "ethiopic-amete-alem")) {
         return new EthiopicCalendar(canLoc, status, EthiopicCalendar::AMETE_ALEM_ERA);
-    } else { 
+    } else {
         status = U_UNSUPPORTED_ERROR;
         return NULL;
     }
@@ -224,7 +224,7 @@
 // -------------------------------------
 
 /**
-* a Calendar Factory which creates the "basic" calendar types, that is, those 
+* a Calendar Factory which creates the "basic" calendar types, that is, those
 * shipped with ICU.
 */
 class BasicCalendarFactory : public LocaleKeyFactory {
@@ -238,7 +238,7 @@
         virtual ~BasicCalendarFactory() {}
 
 protected:
-    //virtual UBool isSupportedID( const UnicodeString& id, UErrorCode& status) const { 
+    //virtual UBool isSupportedID( const UnicodeString& id, UErrorCode& status) const {
     //  if(U_FAILURE(status)) {
     //    return FALSE;
     //  }
@@ -295,13 +295,13 @@
 };
 
 
-/** 
+/**
 * A factory which looks up the DefaultCalendar resource to determine which class of calendar to use
 */
 
 class DefaultCalendarFactory : public ICUResourceBundleFactory {
 public:
-    DefaultCalendarFactory():  ICUResourceBundleFactory() { } 
+    DefaultCalendarFactory():  ICUResourceBundleFactory() { }
 protected:
     virtual UObject* create(const ICUServiceKey& key, const ICUService* /*service*/, UErrorCode& status) const  {
 
@@ -319,9 +319,9 @@
             char funcEquiv[ULOC_FULLNAME_CAPACITY];
             ures_getFunctionalEquivalent(funcEquiv, sizeof(funcEquiv)-1,
                 NULL, "calendar", "calendar",
-                loc.getName(), 
+                loc.getName(),
                 NULL, FALSE, &status);
-            uloc_getKeywordValue(funcEquiv, "calendar", keyword, 
+            uloc_getKeywordValue(funcEquiv, "calendar", keyword,
                 sizeof(keyword)-1, &status);
 #ifdef U_DEBUG_CALSVC
             fprintf(stderr, "  getFunctionalEquivalent calendar=%s [%s]\n", keyword, u_errorName(status));
@@ -333,7 +333,7 @@
 
 
         if(U_FAILURE(status)) {
-            return NULL; 
+            return NULL;
         } else {
             UnicodeString *ret = new UnicodeString();
             if (ret == NULL) {
@@ -360,7 +360,7 @@
 
     virtual UObject* cloneInstance(UObject* instance) const {
         if(instance->getDynamicClassID() == UnicodeString::getStaticClassID()) {
-            return ((UnicodeString*)instance)->clone(); 
+            return ((UnicodeString*)instance)->clone();
         } else {
 #ifdef U_DEBUG_CALSVC_F
             UErrorCode status2 = U_ZERO_ERROR;
@@ -407,7 +407,7 @@
 
 // -------------------------------------
 
-static ICULocaleService* 
+static ICULocaleService*
 getCalendarService(UErrorCode &status)
 {
     UBool needInit;
@@ -425,7 +425,7 @@
         fprintf(stderr, "Registering classes..\n");
 #endif
 
-        // Register all basic instances. 
+        // Register all basic instances.
         newservice->registerFactory(new BasicCalendarFactory(),status);
 
 #ifdef U_DEBUG_CALSVC
@@ -593,7 +593,7 @@
         return;
     }
 
-    clear();    
+    clear();
     fZone = zone;
 
     setWeekCountData(aLocale, NULL, success);
@@ -689,7 +689,7 @@
     return createInstance(TimeZone::createDefault(), aLocale, success);
 }
 
-// ------------------------------------- Adopting 
+// ------------------------------------- Adopting
 
 // Note: this is the bottleneck that actually calls the service routines.
 
@@ -717,10 +717,10 @@
             // fetch default calendar id
             ures_getFunctionalEquivalent(funcEquiv, sizeof(funcEquiv)-1,
                 NULL, "calendar", "calendar",
-                aLocale.getName(), 
+                aLocale.getName(),
                 NULL, FALSE, &feErr);
-            keywordCapacity = uloc_getKeywordValue(funcEquiv, "calendar", calLocaleType, 
-                sizeof(calLocaleType)-1, &feErr);  // This can fail if there is no data.  
+            keywordCapacity = uloc_getKeywordValue(funcEquiv, "calendar", calLocaleType,
+                sizeof(calLocaleType)-1, &feErr);  // This can fail if there is no data.
             // Don't want to stop calendar construction just because we couldn't get this type.
             if (keywordCapacity == 0 || U_FAILURE(feErr)) {
                 // no calendar type.  Default to nothing.
@@ -769,14 +769,14 @@
 
         if(U_FAILURE(success) || !c) {
             delete zone;
-            if(U_SUCCESS(success)) { 
+            if(U_SUCCESS(success)) {
                 success = U_INTERNAL_PROGRAM_ERROR; // Propagate some err
             }
             return NULL;
         }
 
         if(c->getDynamicClassID() == UnicodeString::getStaticClassID()) {
-            // recursed! Second lookup returned a UnicodeString. 
+            // recursed! Second lookup returned a UnicodeString.
             // Perhaps DefaultCalendar{} was set to another locale.
 #ifdef U_DEBUG_CALSVC
             char tmp[200];
@@ -825,7 +825,7 @@
     if(U_SUCCESS(success) && c) {
         c->setTimeZone(zone);
     }
-    return c; 
+    return c;
 }
 
 // -------------------------------------
@@ -839,7 +839,7 @@
         U_SUCCESS(status);
 }
 
-UBool 
+UBool
 Calendar::isEquivalentTo(const Calendar& other) const
 {
     return getDynamicClassID() == other.getDynamicClassID() &&
@@ -899,13 +899,13 @@
 * Gets this Calendar's current time as a long.
 * @return the current time as UTC milliseconds from the epoch.
 */
-double 
+double
 Calendar::getTimeInMillis(UErrorCode& status) const
 {
-    if(U_FAILURE(status)) 
+    if(U_FAILURE(status))
         return 0.0;
 
-    if ( ! fIsTimeSet) 
+    if ( ! fIsTimeSet)
         ((Calendar*)this)->updateTime(status);
 
     /* Test for buffer overflows */
@@ -921,9 +921,9 @@
 * Sets this Calendar's current time from the given long value.
 * @param date the new time in UTC milliseconds from the epoch.
 */
-void 
+void
 Calendar::setTimeInMillis( double millis, UErrorCode& status ) {
-    if(U_FAILURE(status)) 
+    if(U_FAILURE(status))
         return;
 
     if (millis > MAX_MILLIS) {
@@ -1125,7 +1125,7 @@
     double localMillis = internalGetTime();
     int32_t rawOffset, dstOffset;
     getTimeZone().getOffset(localMillis, FALSE, rawOffset, dstOffset, ec);
-    localMillis += (rawOffset + dstOffset); 
+    localMillis += (rawOffset + dstOffset);
 
     // Mark fields as set.  Do this before calling handleComputeFields().
     uint32_t mask =   //fInternalSetMask;
@@ -1134,7 +1134,7 @@
         (1 << UCAL_MONTH) |
         (1 << UCAL_DAY_OF_MONTH) | // = UCAL_DATE
         (1 << UCAL_DAY_OF_YEAR) |
-        (1 << UCAL_EXTENDED_YEAR);  
+        (1 << UCAL_EXTENDED_YEAR);
 
     for (int32_t i=0; i<UCAL_FIELD_COUNT; ++i) {
         if ((mask & 1) == 0) {
@@ -1156,14 +1156,14 @@
     // JULIAN_DAY field and also removes some inelegant code. - Liu
     // 11/6/00
 
-    int32_t days =  (int32_t)Math::floorDivide(localMillis, (double)kOneDay);
+    int32_t days =  (int32_t)ClockMath::floorDivide(localMillis, (double)kOneDay);
 
     internalSet(UCAL_JULIAN_DAY,days + kEpochStartAsJulianDay);
 
 #if defined (U_DEBUG_CAL)
     //fprintf(stderr, "%s:%d- Hmm! Jules @ %d, as per %.0lf millis\n",
     //__FILE__, __LINE__, fFields[UCAL_JULIAN_DAY], localMillis);
-#endif  
+#endif
 
     computeGregorianAndDOWFields(fFields[UCAL_JULIAN_DAY], ec);
 
@@ -1264,7 +1264,7 @@
 * proleptic Gregorian calendar, which has no field larger than a year.
 */
 void Calendar::computeWeekFields(UErrorCode &ec) {
-    if(U_FAILURE(ec)) { 
+    if(U_FAILURE(ec)) {
         return;
     }
     int32_t eyear = fFields[UCAL_EXTENDED_YEAR];
@@ -1327,7 +1327,7 @@
     fFields[UCAL_WEEK_OF_MONTH] = weekNumber(dayOfMonth, dayOfWeek);
     fFields[UCAL_DAY_OF_WEEK_IN_MONTH] = (dayOfMonth-1) / 7 + 1;
 #if defined (U_DEBUG_CAL)
-    if(fFields[UCAL_DAY_OF_WEEK_IN_MONTH]==0) fprintf(stderr, "%s:%d: DOWIM %d on %g\n", 
+    if(fFields[UCAL_DAY_OF_WEEK_IN_MONTH]==0) fprintf(stderr, "%s:%d: DOWIM %d on %g\n",
         __FILE__, __LINE__,fFields[UCAL_DAY_OF_WEEK_IN_MONTH], fTime);
 #endif
 }
@@ -1372,7 +1372,7 @@
 // -------------------------------------
 
 
-void Calendar::roll(EDateFields field, int32_t amount, UErrorCode& status) 
+void Calendar::roll(EDateFields field, int32_t amount, UErrorCode& status)
 {
     roll((UCalendarDateFields)field, amount, status);
 }
@@ -1671,7 +1671,7 @@
     default:
         // Other fields cannot be rolled by this method
 #if defined (U_DEBUG_CAL)
-        fprintf(stderr, "%s:%d: ILLEGAL ARG because of roll on non-rollable field %s\n", 
+        fprintf(stderr, "%s:%d: ILLEGAL ARG because of roll on non-rollable field %s\n",
             __FILE__, __LINE__,fldName(field));
 #endif
         status = U_ILLEGAL_ARGUMENT_ERROR;
@@ -1806,7 +1806,7 @@
                 setTimeInMillis(t, status);
             }
         }
-    } 
+    }
 }
 
 // -------------------------------------
@@ -2022,7 +2022,7 @@
 
 // ------------------------------------- limits
 
-int32_t 
+int32_t
 Calendar::getMinimum(EDateFields field) const {
     return getLimit((UCalendarDateFields) field,UCAL_LIMIT_MINIMUM);
 }
@@ -2073,7 +2073,7 @@
 }
 
 // -------------------------------------
-int32_t 
+int32_t
 Calendar::getActualMinimum(EDateFields field, UErrorCode& status) const
 {
     return getActualMinimum((UCalendarDateFields) field, status);
@@ -2149,7 +2149,7 @@
         work->set(field, fieldValue);
         if (work->get(field, status) != fieldValue) {
             break;
-        } 
+        }
         else {
             result = fieldValue;
             fieldValue--;
@@ -2205,7 +2205,7 @@
     case UCAL_DAY_OF_WEEK_IN_MONTH:
         if (internalGet(field) == 0) {
 #if defined (U_DEBUG_CAL)
-            fprintf(stderr, "%s:%d: ILLEGAL ARG because DOW in month cannot be 0\n", 
+            fprintf(stderr, "%s:%d: ILLEGAL ARG because DOW in month cannot be 0\n",
                 __FILE__, __LINE__);
 #endif
             status = U_ILLEGAL_ARGUMENT_ERROR; // "DAY_OF_WEEK_IN_MONTH cannot be zero"
@@ -2231,7 +2231,7 @@
     int32_t value = fFields[field];
     if (value < min || value > max) {
 #if defined (U_DEBUG_CAL)
-        fprintf(stderr, "%s:%d: ILLEGAL ARG because of field %s out of range %d..%d  at %d\n", 
+        fprintf(stderr, "%s:%d: ILLEGAL ARG because of field %s out of range %d..%d  at %d\n",
             __FILE__, __LINE__,fldName(field),min,max,value);
 #endif
         status = U_ILLEGAL_ARGUMENT_ERROR;
@@ -2283,7 +2283,7 @@
 }
 
 const UFieldResolutionTable Calendar::kDatePrecedence[] =
-{ 
+{
     {
         { UCAL_DAY_OF_MONTH, kResolveSTOP },
         { UCAL_WEEK_OF_YEAR, UCAL_DAY_OF_WEEK, kResolveSTOP },
@@ -2304,12 +2304,12 @@
         { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
         { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
         { kResolveSTOP }
-    }, 
+    },
     {{kResolveSTOP}}
 };
 
 
-const UFieldResolutionTable Calendar::kDOWPrecedence[] = 
+const UFieldResolutionTable Calendar::kDOWPrecedence[] =
 {
     {
         { UCAL_DAY_OF_WEEK,kResolveSTOP, kResolveSTOP },
@@ -2320,7 +2320,7 @@
 };
 
 // precedence for calculating a year
-const UFieldResolutionTable Calendar::kYearPrecedence[] = 
+const UFieldResolutionTable Calendar::kYearPrecedence[] =
 {
     {
         { UCAL_YEAR, kResolveSTOP },
@@ -2456,7 +2456,7 @@
     // of cessation is 2:00 am).
 }
 
-int32_t Calendar::computeJulianDay() 
+int32_t Calendar::computeJulianDay()
 {
     // We want to see if any of the date fields is newer than the
     // JULIAN_DAY.  If not, then we use JULIAN_DAY.  If so, then we do
@@ -2498,9 +2498,9 @@
         internalSet(UCAL_EXTENDED_YEAR, year);
     }
 
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
     fprintf(stderr, "%s:%d: bestField= %s - y=%d\n", __FILE__, __LINE__, fldName(bestField), year);
-#endif 
+#endif
 
     // Get the Julian day of the day BEFORE the start of this year.
     // If useMonth is true, get the day before the start of the month.
@@ -2582,9 +2582,9 @@
             date += ((monthLength - date) / 7 + dim + 1) * 7;
         }
     } else {
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
         fprintf(stderr, "%s:%d - bf= %s\n", __FILE__, __LINE__, fldName(bestField));
-#endif 
+#endif
 
         if(bestField == UCAL_WEEK_OF_YEAR) {  // ------------------------------------- WOY -------------
             if(!isSet(UCAL_YEAR_WOY) ||  // YWOY not set at all or
@@ -2595,30 +2595,30 @@
                 int32_t woy = internalGet(bestField);
 
                 int32_t nextJulianDay = handleComputeMonthStart(year+1, 0, FALSE); // jd of day before jan 1
-                int32_t nextFirst = julianDayToDayOfWeek(nextJulianDay + 1) - firstDayOfWeek; 
+                int32_t nextFirst = julianDayToDayOfWeek(nextJulianDay + 1) - firstDayOfWeek;
 
                 if (nextFirst < 0) { // 0..6 ldow of Jan 1
                     nextFirst += 7;
                 }
 
                 if(woy==1) {  // FIRST WEEK ---------------------------------
-#if defined (U_DEBUG_CAL) 
-                    fprintf(stderr, "%s:%d - woy=%d, yp=%d, nj(%d)=%d, nf=%d", __FILE__, __LINE__, 
-                        internalGet(bestField), resolveFields(kYearPrecedence), year+1, 
+#if defined (U_DEBUG_CAL)
+                    fprintf(stderr, "%s:%d - woy=%d, yp=%d, nj(%d)=%d, nf=%d", __FILE__, __LINE__,
+                        internalGet(bestField), resolveFields(kYearPrecedence), year+1,
                         nextJulianDay, nextFirst);
 
                     fprintf(stderr, " next: %d DFW,  min=%d   \n", (7-nextFirst), getMinimalDaysInFirstWeek() );
-#endif 
+#endif
 
                     // nextFirst is now the localized DOW of Jan 1  of y-woy+1
                     if((nextFirst > 0) &&   // Jan 1 starts on FDOW
                         (7-nextFirst) >= getMinimalDaysInFirstWeek()) // or enough days in the week
                     {
                         // Jan 1 of (yearWoy+1) is in yearWoy+1 - recalculate JD to next year
-#if defined (U_DEBUG_CAL) 
-                        fprintf(stderr, "%s:%d - was going to move JD from %d to %d [d%d]\n", __FILE__, __LINE__, 
+#if defined (U_DEBUG_CAL)
+                        fprintf(stderr, "%s:%d - was going to move JD from %d to %d [d%d]\n", __FILE__, __LINE__,
                             julianDay, nextJulianDay, (nextJulianDay-julianDay));
-#endif 
+#endif
                         julianDay = nextJulianDay;
 
                         // recalculate 'first' [0-based local dow of jan 1]
@@ -2629,7 +2629,7 @@
                         // recalculate date.
                         date = 1 - first + dowLocal;
                     }
-                } else if(woy>=getLeastMaximum(bestField)) {          
+                } else if(woy>=getLeastMaximum(bestField)) {
                     // could be in the last week- find out if this JD would overstep
                     int32_t testDate = date;
                     if ((7 - first) < getMinimalDaysInFirstWeek()) {
@@ -2639,7 +2639,7 @@
                     // Now adjust for the week number.
                     testDate += 7 * (woy - 1);
 
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
                     fprintf(stderr, "%s:%d - y=%d, y-1=%d doy%d, njd%d (C.F. %d)\n",
                         __FILE__, __LINE__, year, year-1, testDate, julianDay+testDate, nextJulianDay);
 #endif
@@ -2653,7 +2653,7 @@
                         }
                         date = 1 - first + dowLocal;
 
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
                         fprintf(stderr, "%s:%d - date now %d, jd%d, ywoy%d\n",
                             __FILE__, __LINE__, date, julianDay, year-1);
 #endif
@@ -2678,13 +2678,13 @@
 }
 
 int32_t
-Calendar::getDefaultMonthInYear() 
+Calendar::getDefaultMonthInYear()
 {
     return 0;
 }
 
 int32_t
-Calendar::getDefaultDayInMonth(int32_t /*month*/) 
+Calendar::getDefaultDayInMonth(int32_t /*month*/)
 {
     return 1;
 }
@@ -2714,13 +2714,13 @@
 
 int32_t Calendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy)
 {
-    // We have UCAL_YEAR_WOY and UCAL_WEEK_OF_YEAR - from those, determine 
+    // We have UCAL_YEAR_WOY and UCAL_WEEK_OF_YEAR - from those, determine
     // what year we fall in, so that other code can set it properly.
     // (code borrowed from computeWeekFields and handleComputeJulianDay)
     //return yearWoy;
 
     // First, we need a reliable DOW.
-    UCalendarDateFields bestField = resolveFields(kDatePrecedence); // !! Note: if subclasses have a different table, they should override handleGetExtendedYearFromWeekFields 
+    UCalendarDateFields bestField = resolveFields(kDatePrecedence); // !! Note: if subclasses have a different table, they should override handleGetExtendedYearFromWeekFields
 
     // Now, a local DOW
     int32_t dowLocal = getLocalDOW(); // 0..6
@@ -2751,9 +2751,9 @@
 
     int32_t minDays = getMinimalDaysInFirstWeek();
     UBool jan1InPrevYear = FALSE;  // January 1st in the year of WOY is the 1st week?  (i.e. first week is < minimal )
-    //UBool nextJan1InPrevYear = FALSE; // January 1st of Year of WOY + 1 is in the first week? 
+    //UBool nextJan1InPrevYear = FALSE; // January 1st of Year of WOY + 1 is in the first week?
 
-    if((7 - first) < minDays) { 
+    if((7 - first) < minDays) {
         jan1InPrevYear = TRUE;
     }
 
@@ -2776,8 +2776,8 @@
                     return yearWoy; // in this year
                 }
             }
-        } else if(woy >= getLeastMaximum(bestField)) {  
-            // we _might_ be in the last week.. 
+        } else if(woy >= getLeastMaximum(bestField)) {
+            // we _might_ be in the last week..
             int32_t jd =  // Calculate JD of our target day:
                 jan1Start +  // JD of Jan 1
                 (7-first) + //  days in the first week (Jan 1.. )
@@ -2815,7 +2815,7 @@
             }
 
             //(internalGet(UCAL_DATE) <= (7-first)) /* && in minDow  */ ) {
-            //within 1st week and in this month.. 
+            //within 1st week and in this month..
             //return yearWoy+1;
             return yearWoy;
             break;
@@ -2825,9 +2825,9 @@
         break;
     }
 
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
     fprintf(stderr, "%s:%d - forgot a return on field %s\n", __FILE__, __LINE__, fldName(bestField));
-#endif 
+#endif
 
     return yearWoy;
 }
@@ -2954,7 +2954,7 @@
                     dow += 7;
                 }
             }
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
             fprintf(stderr, "prepareGetActualHelper(WOM/WOY) - dow=%d\n", dow);
 #endif
             set(UCAL_DAY_OF_WEEK, dow);
@@ -2970,7 +2970,7 @@
 
 int32_t Calendar::getActualHelper(UCalendarDateFields field, int32_t startValue, int32_t endValue, UErrorCode &status) const
 {
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
     fprintf(stderr, "getActualHelper(%d,%d .. %d, %s)\n", field, startValue, endValue, u_errorName(status));
 #endif
     if (startValue == endValue) {
@@ -3001,7 +3001,7 @@
     int32_t result = startValue;
     if (work->get(field, status) != startValue
         && field != UCAL_WEEK_OF_MONTH && delta > 0 || U_FAILURE(status)) {
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
         fprintf(stderr, "getActualHelper(fld %d) - got  %d (not %d) - %s\n", field, work->get(field,status), startValue, u_errorName(status));
 #endif
     } else {
@@ -3018,7 +3018,7 @@
         } while (startValue != endValue);
     }
     delete work;
-#if defined (U_DEBUG_CAL) 
+#if defined (U_DEBUG_CAL)
     fprintf(stderr, "getActualHelper(%d) = %d\n", field, result);
 #endif
     return result;
@@ -3091,8 +3091,8 @@
 * and areFieldsSet.  Callers should check isTimeSet and only
 * call this method if isTimeSet is false.
 */
-void 
-Calendar::updateTime(UErrorCode& status) 
+void
+Calendar::updateTime(UErrorCode& status)
 {
     computeTime(status);
     if(U_FAILURE(status))
@@ -3101,14 +3101,14 @@
     // If we are lenient, we need to recompute the fields to normalize
     // the values.  Also, if we haven't set all the fields yet (i.e.,
     // in a newly-created object), we need to fill in the fields. [LIU]
-    if (isLenient() || ! fAreAllFieldsSet) 
+    if (isLenient() || ! fAreAllFieldsSet)
         fAreFieldsSet = FALSE;
 
     fIsTimeSet = TRUE;
     fAreFieldsVirtuallySet = FALSE;
 }
 
-Locale 
+Locale
 Calendar::getLocale(ULocDataLocaleType type, UErrorCode& status) const {
     U_LOCALE_BASED(locBased, *this);
     return locBased.getLocale(type, status);
diff -Nura icu/source/i18n/cecal.cpp icu_new/source/i18n/cecal.cpp
--- icu/source/i18n/cecal.cpp	2008-07-01 09:40:48.000000000 +0800
+++ icu_new/source/i18n/cecal.cpp	2018-05-25 14:57:27.932113879 +0800
@@ -52,7 +52,7 @@
     setTimeInMillis(getNow(), success);
 }
 
-CECalendar::CECalendar (const CECalendar& other) 
+CECalendar::CECalendar (const CECalendar& other)
 :   Calendar(other)
 {
 }
@@ -112,7 +112,7 @@
     return (int32_t) (
         (jdEpochOffset+365)             // difference from Julian epoch to 1,1,1
         + 365 * (year - 1)              // number of days from years
-        + Math::floorDivide(year, 4)    // extra day of leap year
+        + ClockMath::floorDivide(year, 4)    // extra day of leap year
         + 30 * (month + 1)              // number of days from months
         + date                          // number of days for present month
         - 31                            // slack?
@@ -125,7 +125,7 @@
     int32_t c4; // number of 4 year cycle (1461 days)
     int32_t r4; // remainder of 4 year cycle, always positive
 
-    c4 = Math::floorDivide(julianDay - jdEpochOffset, 1461, r4);
+    c4 = ClockMath::floorDivide(julianDay - jdEpochOffset, 1461, r4);
 
     year = 4 * c4 + (r4/365 - r4/1460); // 4 * <number of 4year cycle> + <years within the last cycle>
 
diff -Nura icu/source/i18n/chnsecal.cpp icu_new/source/i18n/chnsecal.cpp
--- icu/source/i18n/chnsecal.cpp	2008-07-01 09:40:50.000000000 +0800
+++ icu_new/source/i18n/chnsecal.cpp	2018-05-25 14:54:52.572813157 +0800
@@ -125,7 +125,7 @@
 {
 }
 
-const char *ChineseCalendar::getType() const { 
+const char *ChineseCalendar::getType() const {
     return "chinese";
 }
 
@@ -218,7 +218,7 @@
  * <li>DAY_OF_MONTH
  * <li>DAY_OF_YEAR
  * <li>EXTENDED_YEAR</ul>
- * 
+ *
  * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
  * method is called.  The getGregorianXxx() methods return Gregorian
  * calendar equivalents for the given Julian day.
@@ -273,7 +273,7 @@
 /**
  * Return the Julian day number of day before the first day of the
  * given month in the given extended year.
- * 
+ *
  * <p>Note: This method reads the IS_LEAP_MONTH field to determine
  * whether the given month is a leap month.
  * @param eyear the extended year
@@ -291,14 +291,14 @@
     // modify the extended year value accordingly.
     if (month < 0 || month > 11) {
         double m = month;
-        eyear += (int32_t)Math::floorDivide(m, 12.0, m);
+        eyear += (int32_t)ClockMath::floorDivide(m, 12.0, m);
         month = (int32_t)m;
     }
 
     int32_t gyear = eyear + CHINESE_EPOCH_YEAR - 1; // Gregorian year
     int32_t theNewYear = newYear(gyear);
     int32_t newMoon = newMoonNear(theNewYear + month * 29, TRUE);
-    
+
     int32_t julianDay = newMoon + kEpochStartAsJulianDay;
 
     // Save fields for later restoration
@@ -312,10 +312,10 @@
     nonConstThis->computeGregorianFields(julianDay, status);
     if (U_FAILURE(status))
         return 0;
-    
+
     // This will modify the MONTH and IS_LEAP_MONTH fields (only)
     nonConstThis->computeChineseFields(newMoon, getGregorianYear(),
-                         getGregorianMonth(), FALSE);        
+                         getGregorianMonth(), FALSE);
 
     if (month != internalGet(UCAL_MONTH) ||
         isLeapMonth != internalGet(UCAL_IS_LEAP_MONTH)) {
@@ -342,7 +342,7 @@
             if (U_FAILURE(status)) break;
             int32_t day = get(UCAL_JULIAN_DAY, status) - kEpochStartAsJulianDay; // Get local day
             if (U_FAILURE(status)) break;
-            int32_t moon = day - dom + 1; // New moon 
+            int32_t moon = day - dom + 1; // New moon
             offsetMonth(moon, dom, amount);
         }
         break;
@@ -446,7 +446,7 @@
  * @return days after January 1, 1970 0:00 Asia/Shanghai
  */
 double ChineseCalendar::millisToDays(double millis) {
-    return Math::floorDivide(millis + CHINA_OFFSET, kOneDay);
+    return ClockMath::floorDivide(millis + CHINA_OFFSET, kOneDay);
 }
 
 //------------------------------------------------------------------
@@ -503,7 +503,7 @@
  * new moon after or before <code>days</code>
  */
 int32_t ChineseCalendar::newMoonNear(double days, UBool after) const {
-    
+
     umtx_lock(&astroLock);
     if(gChineseCalendarAstro == NULL) {
         gChineseCalendarAstro = new CalendarAstronomer();
@@ -512,7 +512,7 @@
     gChineseCalendarAstro->setTime(daysToMillis(days));
     UDate newMoon = gChineseCalendarAstro->getMoonTime(CalendarAstronomer::NEW_MOON(), after);
     umtx_unlock(&astroLock);
-    
+
     return (int32_t) millisToDays(newMoon);
 }
 
@@ -535,7 +535,7 @@
  * @param days days after January 1, 1970 0:00 Asia/Shanghai
  */
 int32_t ChineseCalendar::majorSolarTerm(int32_t days) const {
-    
+
     umtx_lock(&astroLock);
     if(gChineseCalendarAstro == NULL) {
         gChineseCalendarAstro = new CalendarAstronomer();
@@ -662,7 +662,7 @@
 
         // 0->0,60  1->1,1  60->1,60  61->2,1  etc.
         int32_t yearOfCycle;
-        int32_t cycle = Math::floorDivide(year - 1, 60, yearOfCycle);
+        int32_t cycle = ClockMath::floorDivide(year - 1, 60, yearOfCycle);
         internalSet(UCAL_ERA, cycle + 1);
         internalSet(UCAL_YEAR, yearOfCycle + 1);
 
@@ -702,7 +702,7 @@
         int32_t newMoon1 = newMoonNear(solsticeBefore + 1, TRUE);
         int32_t newMoon2 = newMoonNear(newMoon1 + SYNODIC_GAP, TRUE);
         int32_t newMoon11 = newMoonNear(solsticeAfter + 1, FALSE);
-        
+
         if (synodicMonthsBetween(newMoon1, newMoon11) == 12 &&
             (hasNoMajorSolarTerm(newMoon1) || hasNoMajorSolarTerm(newMoon2))) {
             cacheValue = newMoonNear(newMoon2 + SYNODIC_GAP, TRUE);
@@ -765,7 +765,7 @@
 ChineseCalendar::inDaylightTime(UErrorCode& status) const
 {
     // copied from GregorianCalendar
-    if (U_FAILURE(status) || !getTimeZone().useDaylightTime()) 
+    if (U_FAILURE(status) || !getTimeZone().useDaylightTime())
         return FALSE;
 
     // Force an update of the state of the Calendar.
@@ -865,4 +865,3 @@
 U_NAMESPACE_END
 
 #endif
-
diff -Nura icu/source/i18n/gregocal.cpp icu_new/source/i18n/gregocal.cpp
--- icu/source/i18n/gregocal.cpp	2008-07-01 09:40:48.000000000 +0800
+++ icu_new/source/i18n/gregocal.cpp	2018-05-25 14:41:25.500056063 +0800
@@ -25,7 +25,7 @@
 *                           add() from Java source.
 *    07/28/98    stephen        Sync up with JDK 1.2
 *    09/14/98    stephen        Changed type of kOneDay, kOneWeek to double.
-*                            Fixed bug in roll() 
+*                            Fixed bug in roll()
 *   10/15/99    aliu        Fixed j31, incorrect WEEK_OF_YEAR computation.
 *   10/15/99    aliu        Fixed j32, cannot set date to Feb 29 2000 AD.
 *                           {JDK bug 4210209 4209272}
@@ -103,7 +103,7 @@
 
 /*
 * <pre>
-*                            Greatest       Least 
+*                            Greatest       Least
 * Field name        Minimum   Minimum     Maximum     Maximum
 * ----------        -------   -------     -------     -------
 * ERA                     0         0           1           1
@@ -319,7 +319,7 @@
 void
 GregorianCalendar::setGregorianChange(UDate date, UErrorCode& status)
 {
-    if (U_FAILURE(status)) 
+    if (U_FAILURE(status))
         return;
 
     fGregorianCutover = date;
@@ -330,7 +330,7 @@
     // normalized cutover is in pure date milliseconds; it contains no time
     // of day or timezone component, and it used to compare against other
     // pure date values.
-    int32_t cutoverDay = (int32_t)Math::floorDivide(fGregorianCutover, (double)kOneDay);
+    int32_t cutoverDay = (int32_t)ClockMath::floorDivide(fGregorianCutover, (double)kOneDay);
     fNormalizedGregorianCutover = cutoverDay * kOneDay;
 
     // Handle the rare case of numeric overflow.  If the user specifies a
@@ -356,7 +356,7 @@
         return;
     cal->setTime(date, status);
     fGregorianCutoverYear = cal->get(UCAL_YEAR, status);
-    if (cal->get(UCAL_ERA, status) == BC) 
+    if (cal->get(UCAL_ERA, status) == BC)
         fGregorianCutoverYear = 1 - fGregorianCutoverYear;
     fCutoverJulianDay = cutoverDay;
     delete cal;
@@ -367,12 +367,12 @@
     int32_t eyear, month, dayOfMonth, dayOfYear;
 
 
-    if(U_FAILURE(status)) { 
-        return; 
+    if(U_FAILURE(status)) {
+        return;
     }
 
 #if defined (U_DEBUG_CAL)
-    fprintf(stderr, "%s:%d: jd%d- (greg's %d)- [cut=%d]\n", 
+    fprintf(stderr, "%s:%d: jd%d- (greg's %d)- [cut=%d]\n",
         __FILE__, __LINE__, julianDay, getGregorianDayOfYear(), fCutoverJulianDay);
 #endif
 
@@ -386,10 +386,10 @@
         // The Julian epoch day (not the same as Julian Day)
         // is zero on Saturday December 30, 0 (Gregorian).
         int32_t julianEpochDay = julianDay - (kJan1_1JulianDay - 2);
-        eyear = (int32_t) Math::floorDivide(4*julianEpochDay + 1464, 1461);
+        eyear = (int32_t) ClockMath::floorDivide(4*julianEpochDay + 1464, 1461);
 
         // Compute the Julian calendar day number for January 1, eyear
-        int32_t january1 = 365*(eyear-1) + Math::floorDivide(eyear-1, (int32_t)4);
+        int32_t january1 = 365*(eyear-1) + ClockMath::floorDivide(eyear-1, (int32_t)4);
         dayOfYear = (julianEpochDay - january1); // 0-based
 
         // Julian leap years occurred historically every 4 years starting
@@ -411,11 +411,11 @@
         ++dayOfYear;
 #if defined (U_DEBUG_CAL)
         //     fprintf(stderr, "%d - %d[%d] + 1\n", dayOfYear, isLeap?kLeapNumDays[month]:kNumDays[month], month );
-        //           fprintf(stderr, "%s:%d:  greg's HCF %d -> %d/%d/%d not %d/%d/%d\n", 
+        //           fprintf(stderr, "%s:%d:  greg's HCF %d -> %d/%d/%d not %d/%d/%d\n",
         //                   __FILE__, __LINE__,julianDay,
         //          eyear,month,dayOfMonth,
         //          getGregorianYear(), getGregorianMonth(), getGregorianDayOfMonth()  );
-        fprintf(stderr, "%s:%d: doy %d (greg's %d)- [cut=%d]\n", 
+        fprintf(stderr, "%s:%d: doy %d (greg's %d)- [cut=%d]\n",
             __FILE__, __LINE__, dayOfYear, getGregorianDayOfYear(), fCutoverJulianDay);
 #endif
 
@@ -456,7 +456,7 @@
 
 // -------------------------------------
 
-UBool 
+UBool
 GregorianCalendar::isLeapYear(int32_t year) const
 {
     // MSVC complains bitterly if we try to use Grego::isLeapYear here
@@ -468,15 +468,15 @@
 
 // -------------------------------------
 
-int32_t GregorianCalendar::handleComputeJulianDay(UCalendarDateFields bestField) 
+int32_t GregorianCalendar::handleComputeJulianDay(UCalendarDateFields bestField)
 {
     fInvertGregorian = FALSE;
 
     int32_t jd = Calendar::handleComputeJulianDay(bestField);
 
     if((bestField == UCAL_WEEK_OF_YEAR) &&  // if we are doing WOY calculations, we are counting relative to Jan 1 *julian*
-        (internalGet(UCAL_EXTENDED_YEAR)==fGregorianCutoverYear) && 
-        jd >= fCutoverJulianDay) { 
+        (internalGet(UCAL_EXTENDED_YEAR)==fGregorianCutoverYear) &&
+        jd >= fCutoverJulianDay) {
             fInvertGregorian = TRUE;  // So that the Julian Jan 1 will be used in handleComputeMonthStart
             return Calendar::handleComputeJulianDay(bestField);
         }
@@ -487,20 +487,20 @@
         //if ((fIsGregorian==TRUE) != (jd >= fCutoverJulianDay)) {  /*  cutoverJulianDay)) { */
         if ((fIsGregorian==TRUE) != (jd >= fCutoverJulianDay)) {  /*  cutoverJulianDay)) { */
 #if defined (U_DEBUG_CAL)
-            fprintf(stderr, "%s:%d: jd [invert] %d\n", 
+            fprintf(stderr, "%s:%d: jd [invert] %d\n",
                 __FILE__, __LINE__, jd);
 #endif
             fInvertGregorian = TRUE;
             jd = Calendar::handleComputeJulianDay(bestField);
 #if defined (U_DEBUG_CAL)
-            fprintf(stderr, "%s:%d:  fIsGregorian %s, fInvertGregorian %s - ", 
+            fprintf(stderr, "%s:%d:  fIsGregorian %s, fInvertGregorian %s - ",
                 __FILE__, __LINE__,fIsGregorian?"T":"F", fInvertGregorian?"T":"F");
-            fprintf(stderr, " jd NOW %d\n", 
+            fprintf(stderr, " jd NOW %d\n",
                 jd);
 #endif
         } else {
 #if defined (U_DEBUG_CAL)
-            fprintf(stderr, "%s:%d: jd [==] %d - %sfIsGregorian %sfInvertGregorian, %d\n", 
+            fprintf(stderr, "%s:%d: jd [==] %d - %sfIsGregorian %sfInvertGregorian, %d\n",
                 __FILE__, __LINE__, jd, fIsGregorian?"T":"F", fInvertGregorian?"T":"F", bestField);
 #endif
         }
@@ -509,14 +509,14 @@
             int32_t gregShift = Grego::gregorianShift(internalGet(UCAL_EXTENDED_YEAR));
             if (bestField == UCAL_DAY_OF_YEAR) {
 #if defined (U_DEBUG_CAL)
-                fprintf(stderr, "%s:%d: [DOY%d] gregorian shift of JD %d += %d\n", 
+                fprintf(stderr, "%s:%d: [DOY%d] gregorian shift of JD %d += %d\n",
                     __FILE__, __LINE__, fFields[bestField],jd, gregShift);
 #endif
                 jd -= gregShift;
             } else if ( bestField == UCAL_WEEK_OF_MONTH ) {
                 int32_t weekShift = 14;
 #if defined (U_DEBUG_CAL)
-                fprintf(stderr, "%s:%d: [WOY/WOM] gregorian week shift of %d += %d\n", 
+                fprintf(stderr, "%s:%d: [WOY/WOM] gregorian week shift of %d += %d\n",
                     __FILE__, __LINE__, jd, weekShift);
 #endif
                 jd += weekShift; // shift by weeks for week based fields.
@@ -535,16 +535,16 @@
     // If the month is out of range, adjust it into range, and
     // modify the extended year value accordingly.
     if (month < 0 || month > 11) {
-        eyear += Math::floorDivide(month, 12, month);
+        eyear += ClockMath::floorDivide(month, 12, month);
     }
 
     UBool isLeap = eyear%4 == 0;
     int32_t y = eyear-1;
-    int32_t julianDay = 365*y + Math::floorDivide(y, 4) + (kJan1_1JulianDay - 3);
+    int32_t julianDay = 365*y + ClockMath::floorDivide(y, 4) + (kJan1_1JulianDay - 3);
 
     nonConstThis->fIsGregorian = (eyear >= fGregorianCutoverYear);
 #if defined (U_DEBUG_CAL)
-    fprintf(stderr, "%s:%d: (hcms%d/%d) fIsGregorian %s, fInvertGregorian %s\n", 
+    fprintf(stderr, "%s:%d: (hcms%d/%d) fIsGregorian %s, fInvertGregorian %s\n",
         __FILE__, __LINE__, eyear,month, fIsGregorian?"T":"F", fInvertGregorian?"T":"F");
 #endif
     if (fInvertGregorian) {
@@ -556,7 +556,7 @@
         // Julian calendar
         int32_t gregShift = Grego::gregorianShift(eyear);
 #if defined (U_DEBUG_CAL)
-        fprintf(stderr, "%s:%d: (hcms%d/%d) gregorian shift of %d += %d\n", 
+        fprintf(stderr, "%s:%d: (hcms%d/%d) gregorian shift of %d += %d\n",
             __FILE__, __LINE__, eyear, month, julianDay, gregShift);
 #endif
         julianDay += gregShift;
@@ -578,7 +578,7 @@
     // If the month is out of range, adjust it into range, and
     // modify the extended year value accordingly.
     if (month < 0 || month > 11) {
-        extendedYear += Math::floorDivide(month, 12, month);
+        extendedYear += ClockMath::floorDivide(month, 12, month);
     }
 
     return isLeapYear(extendedYear) ? kLeapMonthLength[month] : kMonthLength[month];
@@ -628,12 +628,12 @@
 * 3, we want it to go to Feb 28.  Adjustments which might run into this
 * problem call this method to retain the proper month.
 */
-void 
-GregorianCalendar::pinDayOfMonth() 
+void
+GregorianCalendar::pinDayOfMonth()
 {
     int32_t monthLen = monthLength(internalGet(UCAL_MONTH));
     int32_t dom = internalGet(UCAL_DATE);
-    if(dom > monthLen) 
+    if(dom > monthLen)
         set(UCAL_DATE, monthLen);
 }
 
@@ -689,15 +689,15 @@
 
 // -------------------------------------
 
-UDate 
-GregorianCalendar::getEpochDay(UErrorCode& status) 
+UDate
+GregorianCalendar::getEpochDay(UErrorCode& status)
 {
     complete(status);
     // Divide by 1000 (convert to seconds) in order to prevent overflow when
     // dealing with UDate(Long.MIN_VALUE) and UDate(Long.MAX_VALUE).
     double wallSec = internalGetTime()/1000 + (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET))/1000;
 
-    return Math::floorDivide(wallSec, kOneDay/1000.0);
+    return ClockMath::floorDivide(wallSec, kOneDay/1000.0);
 }
 
 // -------------------------------------
@@ -716,7 +716,7 @@
 {
     isLeap = year%4 == 0;
     int32_t y = year - 1;
-    double julianDay = 365.0*y + Math::floorDivide(y, 4) + (kJan1_1JulianDay - 3);
+    double julianDay = 365.0*y + ClockMath::floorDivide(y, 4) + (kJan1_1JulianDay - 3);
 
     if (isGregorian) {
         isLeap = isLeap && ((year%100 != 0) || (year%400 == 0));
@@ -782,10 +782,10 @@
 
 // -------------------------------------
 
-double 
+double
 GregorianCalendar::millisToJulianDay(UDate millis)
 {
-    return (double)kEpochStartAsJulianDay + Math::floorDivide(millis, (double)kOneDay);
+    return (double)kEpochStartAsJulianDay + ClockMath::floorDivide(millis, (double)kOneDay);
 }
 
 // -------------------------------------
@@ -799,9 +799,9 @@
 // -------------------------------------
 
 int32_t
-GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b) 
+GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b)
 {
-    return (((stamp_a != kUnset && stamp_b != kUnset) 
+    return (((stamp_a != kUnset && stamp_b != kUnset)
         ? uprv_max(stamp_a, stamp_b)
         : (int32_t)kUnset));
 }
@@ -813,9 +813,9 @@
 * Note: This will be made public later. [LIU]
 */
 
-void 
+void
 GregorianCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
-    roll((UCalendarDateFields) field, amount, status); 
+    roll((UCalendarDateFields) field, amount, status);
 }
 
 void
@@ -901,7 +901,7 @@
                             }
 
     case UCAL_DAY_OF_MONTH:
-        if( !inCutoverMonth ) { 
+        if( !inCutoverMonth ) {
             Calendar::roll(field, amount, status);
             return;
         } else {
@@ -916,7 +916,7 @@
                 msIntoMonth += monthLen;
             }
 #if defined (U_DEBUG_CAL)
-            fprintf(stderr, "%s:%d: roll DOM %d  -> %.0lf ms  \n", 
+            fprintf(stderr, "%s:%d: roll DOM %d  -> %.0lf ms  \n",
                 __FILE__, __LINE__,amount, cMonthLen, cMonthStart+msIntoMonth);
 #endif
             setTimeInMillis(cMonthStart + msIntoMonth, status);
@@ -924,16 +924,16 @@
         }
 
     case UCAL_WEEK_OF_MONTH:
-        if( !inCutoverMonth ) { 
+        if( !inCutoverMonth ) {
             Calendar::roll(field, amount, status);
             return;
         } else {
 #if defined (U_DEBUG_CAL)
-            fprintf(stderr, "%s:%d: roll WOM %d ??????????????????? \n", 
+            fprintf(stderr, "%s:%d: roll WOM %d ??????????????????? \n",
                 __FILE__, __LINE__,amount);
 #endif
             // NOTE: following copied from  the old
-            //     GregorianCalendar::roll( WEEK_OF_MONTH )  code 
+            //     GregorianCalendar::roll( WEEK_OF_MONTH )  code
 
             // This is tricky, because during the roll we may have to shift
             // to a different day of the week.  For example:
@@ -971,7 +971,7 @@
             // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
             // in this locale.  We have dow in 0..6.
             int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
-            if (dow < 0) 
+            if (dow < 0)
                 dow += 7;
 
             // Find the day of month, compensating for cutover discontinuity.
@@ -980,7 +980,7 @@
             // Find the day of the week (normalized for locale) for the first
             // of the month.
             int32_t fdm = (dow - dom + 1) % 7;
-            if (fdm < 0) 
+            if (fdm < 0)
                 fdm += 7;
 
             // Get the first day of the first full week of the month,
@@ -1008,14 +1008,14 @@
             // Now roll between start and (limit - 1).
             int32_t gap = limit - start;
             int32_t newDom = (dom + amount*7 - start) % gap;
-            if (newDom < 0) 
+            if (newDom < 0)
                 newDom += gap;
             newDom += start;
 
             // Finally, pin to the real start and end of the month.
-            if (newDom < 1) 
+            if (newDom < 1)
                 newDom = 1;
-            if (newDom > monthLen) 
+            if (newDom > monthLen)
                 newDom = monthLen;
 
             // Set the DAY_OF_MONTH.  We rely on the fact that this field
@@ -1028,7 +1028,7 @@
             // If we are in the cutover month, manipulate ms directly.  Don't do
             // this in general because it doesn't work across DST boundaries
             // (details, details).  This takes care of the discontinuity.
-            setTimeInMillis(cMonthStart + (newDom-1)*kOneDay, status);                
+            setTimeInMillis(cMonthStart + (newDom-1)*kOneDay, status);
             return;
         }
 
@@ -1196,7 +1196,7 @@
         year = handleGetExtendedYearFromWeekFields(internalGet(UCAL_YEAR_WOY), internalGet(UCAL_WEEK_OF_YEAR));
 #if defined (U_DEBUG_CAL)
         //    if(internalGet(UCAL_YEAR_WOY) != year) {
-        fprintf(stderr, "%s:%d: hGEYFWF[%d,%d] ->  %d\n", 
+        fprintf(stderr, "%s:%d: hGEYFWF[%d,%d] ->  %d\n",
             __FILE__, __LINE__,internalGet(UCAL_YEAR_WOY),internalGet(UCAL_WEEK_OF_YEAR),year);
         //}
 #endif
@@ -1224,7 +1224,7 @@
 UBool
 GregorianCalendar::inDaylightTime(UErrorCode& status) const
 {
-    if (U_FAILURE(status) || !getTimeZone().useDaylightTime()) 
+    if (U_FAILURE(status) || !getTimeZone().useDaylightTime())
         return FALSE;
 
     // Force an update of the state of the Calendar.
diff -Nura icu/source/i18n/gregoimp.cpp icu_new/source/i18n/gregoimp.cpp
--- icu/source/i18n/gregoimp.cpp	2008-07-01 09:40:48.000000000 +0800
+++ icu_new/source/i18n/gregoimp.cpp	2018-05-25 14:51:37.728181850 +0800
@@ -24,12 +24,17 @@
 
 U_NAMESPACE_BEGIN
 
-int32_t Math::floorDivide(int32_t numerator, int32_t denominator) {
+int32_t ClockMath::floorDivide(int32_t numerator, int32_t denominator) {
     return (numerator >= 0) ?
         numerator / denominator : ((numerator + 1) / denominator) - 1;
 }
 
-int32_t Math::floorDivide(double numerator, int32_t denominator,
+int64_t ClockMath::floorDivide(int64_t numerator, int64_t denominator) {
+    return (numerator >= 0) ?
+        numerator / denominator : ((numerator + 1) / denominator) - 1;
+}
+
+int32_t ClockMath::floorDivide(double numerator, int32_t denominator,
                           int32_t& remainder) {
     double quotient;
     quotient = uprv_floor(numerator / denominator);
@@ -37,7 +42,7 @@
     return (int32_t) quotient;
 }
 
-double Math::floorDivide(double dividend, double divisor,
+double ClockMath::floorDivide(double dividend, double divisor,
                          double& remainder) {
     // Only designed to work for positive divisors
     U_ASSERT(divisor > 0);
@@ -86,8 +91,8 @@
 
     int32_t y = year - 1;
 
-    double julian = 365 * y + Math::floorDivide(y, 4) + (JULIAN_1_CE - 3) + // Julian cal
-        Math::floorDivide(y, 400) - Math::floorDivide(y, 100) + 2 + // => Gregorian cal
+    double julian = 365 * y + ClockMath::floorDivide(y, 4) + (JULIAN_1_CE - 3) + // Julian cal
+        ClockMath::floorDivide(y, 400) - ClockMath::floorDivide(y, 100) + 2 + // => Gregorian cal
         DAYS_BEFORE[month + (isLeapYear(year) ? 12 : 0)] + dom; // => month/dom
 
     return julian - JULIAN_1970_CE; // JD => epoch day
@@ -103,19 +108,19 @@
     // representation.  We use 400-year, 100-year, and 4-year cycles.
     // For example, the 4-year cycle has 4 years + 1 leap day; giving
     // 1461 == 365*4 + 1 days.
-    int32_t n400 = Math::floorDivide(day, 146097, doy); // 400-year cycle length
-    int32_t n100 = Math::floorDivide(doy, 36524, doy); // 100-year cycle length
-    int32_t n4   = Math::floorDivide(doy, 1461, doy); // 4-year cycle length
-    int32_t n1   = Math::floorDivide(doy, 365, doy);
+    int32_t n400 = ClockMath::floorDivide(day, 146097, doy); // 400-year cycle length
+    int32_t n100 = ClockMath::floorDivide(doy, 36524, doy); // 100-year cycle length
+    int32_t n4   = ClockMath::floorDivide(doy, 1461, doy); // 4-year cycle length
+    int32_t n1   = ClockMath::floorDivide(doy, 365, doy);
     year = 400*n400 + 100*n100 + 4*n4 + n1;
     if (n100 == 4 || n1 == 4) {
         doy = 365; // Dec 31 at end of 4- or 400-year cycle
     } else {
         ++year;
     }
-    
+
     UBool isLeap = isLeapYear(year);
-    
+
     // Gregorian day zero is a Monday.
     dow = (int32_t) uprv_fmod(day + 1, 7);
     dow += (dow < 0) ? (UCAL_SUNDAY + 7) : UCAL_SUNDAY;
@@ -134,14 +139,14 @@
 void Grego::timeToFields(UDate time, int32_t& year, int32_t& month,
                         int32_t& dom, int32_t& dow, int32_t& doy, int32_t& mid) {
     double millisInDay;
-    double day = Math::floorDivide((double)time, (double)U_MILLIS_PER_DAY, millisInDay);
+    double day = ClockMath::floorDivide((double)time, (double)U_MILLIS_PER_DAY, millisInDay);
     mid = (int32_t)millisInDay;
     dayToFields(day, year, month, dom, dow, doy);
 }
 
 int32_t Grego::dayOfWeek(double day) {
     int32_t dow;
-    Math::floorDivide(day + UCAL_THURSDAY, 7, dow);
+    ClockMath::floorDivide(day + UCAL_THURSDAY, 7, dow);
     return (dow == 0) ? UCAL_SATURDAY : dow;
 }
 
@@ -166,7 +171,7 @@
 #define U_CALENDAR_DATA ((char*)0)
 
 
-// CalendarData::CalendarData(const Locale& loc, UErrorCode& status) 
+// CalendarData::CalendarData(const Locale& loc, UErrorCode& status)
 //   : fFillin(NULL), fBundle(NULL), fFallback(NULL) {
 //   initData(loc.getBaseName(), (char*) "???", status);
 // }
@@ -180,16 +185,16 @@
   fOtherFillin = ures_open(U_CALENDAR_DATA, locale, &status);
   fFillin = ures_getByKey(fOtherFillin, U_CALENDAR_KEY, fFillin, &status);
 
-  if((type != NULL) && 
-     (*type != '\0') && 
+  if((type != NULL) &&
+     (*type != '\0') &&
      (uprv_strcmp(type, U_GREGORIAN_KEY)))
   {
     fBundle = ures_getByKeyWithFallback(fFillin, type, NULL, &status);
     fFallback = ures_getByKeyWithFallback(fFillin, U_GREGORIAN_KEY, NULL, &status);
 
 #if defined (U_DEBUG_CALDATA)
-    fprintf(stderr, "%p: CalendarData(%s, %s, %s) -> main(%p, %s)=%s, fallback(%p, %s)=%s\n", 
-            this, locale, type, u_errorName(status), fBundle, type, fBundle?ures_getLocale(fBundle, &status):"", 
+    fprintf(stderr, "%p: CalendarData(%s, %s, %s) -> main(%p, %s)=%s, fallback(%p, %s)=%s\n",
+            this, locale, type, u_errorName(status), fBundle, type, fBundle?ures_getLocale(fBundle, &status):"",
             fFallback, U_GREGORIAN_KEY, fFallback?ures_getLocale(fFallback, &status):"");
 #endif
 
@@ -258,7 +263,7 @@
     }
 
 //// handling of 'default' keyword on failure: Commented out for 3.0.
-//   if((status == U_MISSING_RESOURCE_ERROR) && 
+//   if((status == U_MISSING_RESOURCE_ERROR) &&
 //      uprv_strcmp(subKey,U_DEFAULT_KEY)) { // avoid recursion
 // #if defined (U_DEBUG_CALDATA)
 //     fprintf(stderr, "%p: - attempting fallback -\n", this);
diff -Nura icu/source/i18n/gregoimp.h icu_new/source/i18n/gregoimp.h
--- icu/source/i18n/gregoimp.h	2008-07-01 09:40:50.000000000 +0800
+++ icu_new/source/i18n/gregoimp.h	2018-05-25 14:23:01.324811525 +0800
@@ -24,7 +24,7 @@
  * A utility class providing mathematical functions used by time zone
  * and calendar code.  Do not instantiate.
  */
-class Math {
+class ClockMath {
  public:
     /**
      * Divide two integers, returning the floor of the quotient.
@@ -38,6 +38,17 @@
     static int32_t floorDivide(int32_t numerator, int32_t denominator);
 
     /**
+     * Divide two integers, returning the floor of the quotient.
+     * Unlike the built-in division, this is mathematically
+     * well-behaved.  E.g., <code>-1/4</code> => 0 but
+     * <code>floorDivide(-1,4)</code> => -1.
+     * @param numerator the numerator
+     * @param denominator a divisor which must be != 0
+     * @return the floor of the quotient
+     */
+    static int64_t floorDivide(int64_t numerator, int64_t denominator);
+
+    /**
      * Divide two numbers, returning the floor of the quotient.
      * Unlike the built-in division, this is mathematically
      * well-behaved.  E.g., <code>-1/4</code> => 0 but
@@ -165,7 +176,7 @@
      * @return the day number, with day 0 == Jan 1 1970
      */
     static double fieldsToDay(int32_t year, int32_t month, int32_t dom);
-    
+
     /**
      * Convert a 1970-epoch day number to proleptic Gregorian year,
      * month, day-of-month, and day-of-week.
@@ -238,9 +249,9 @@
      */
     static inline int32_t millisToJulianDay(double millis);
 
-    /** 
+    /**
      * Calculates the Gregorian day shift value for an extended year.
-     * @param eyear Extended year 
+     * @param eyear Extended year
      * @returns number of days to ADD to Julian in order to convert from J->G
      */
     static inline int32_t gregorianShift(int32_t eyear);
@@ -250,7 +261,7 @@
     static const int8_t MONTH_LENGTH[24];
 };
 
-inline double Math::floorDivide(double numerator, double denominator) {
+inline double ClockMath::floorDivide(double numerator, double denominator) {
     return uprv_floor(numerator / denominator);
 }
 
@@ -281,25 +292,25 @@
 }
 
 inline int32_t Grego::millisToJulianDay(double millis) {
-  return (int32_t) (kEpochStartAsJulianDay + Math::floorDivide(millis, (double)kOneDay));
+  return (int32_t) (kEpochStartAsJulianDay + ClockMath::floorDivide(millis, (double)kOneDay));
 }
 
 inline int32_t Grego::gregorianShift(int32_t eyear) {
   int32_t y = eyear-1;
-  int32_t gregShift = Math::floorDivide(y, 400) - Math::floorDivide(y, 100) + 2;
+  int32_t gregShift = ClockMath::floorDivide(y, 400) - ClockMath::floorDivide(y, 100) + 2;
   return gregShift;
 }
 
 /**
- * This utility class provides convenient access to the data needed for a calendar. 
+ * This utility class provides convenient access to the data needed for a calendar.
  * @internal ICU 3.0
  */
 class CalendarData : public UMemory {
-public: 
+public:
     /**
      * Construct a CalendarData from the given locale.
      * @param loc locale to use. The 'calendar' keyword will be ignored.
-     * @param type calendar type. NULL indicates the gregorian calendar. 
+     * @param type calendar type. NULL indicates the gregorian calendar.
      * No default lookup is done.
      * @param status error code
      */
diff -Nura icu/source/i18n/indiancal.cpp icu_new/source/i18n/indiancal.cpp
--- icu/source/i18n/indiancal.cpp	2008-07-01 09:40:48.000000000 +0800
+++ icu_new/source/i18n/indiancal.cpp	2018-05-25 14:53:25.889087411 +0800
@@ -50,10 +50,10 @@
 IndianCalendar::~IndianCalendar()
 {
 }
-const char *IndianCalendar::getType() const { 
+const char *IndianCalendar::getType() const {
    return "indian";
 }
-  
+
 static const int32_t LIMITS[UCAL_FIELD_COUNT][4] = {
     // Minimum  Greatest     Least   Maximum
     //           Minimum   Maximum
@@ -91,13 +91,13 @@
 }
 
 /*
- * Determine whether the given gregorian year is a Leap year 
+ * Determine whether the given gregorian year is a Leap year
  */
 static UBool isGregorianLeap(int32_t year)
 {
-    return ((year % 4) == 0) && (!(((year % 100) == 0) && ((year % 400) != 0))); 
+    return ((year % 4) == 0) && (!(((year % 100) == 0) && ((year % 400) != 0)));
 }
-  
+
 //----------------------------------------------------------------------
 // Calendar framework
 //----------------------------------------------------------------------
@@ -110,7 +110,7 @@
  */
 int32_t IndianCalendar::handleGetMonthLength(int32_t eyear, int32_t month) const {
    if (month < 0 || month > 11) {
-      eyear += Math::floorDivide(month, 12, month);
+      eyear += ClockMath::floorDivide(month, 12, month);
    }
 
    if (isGregorianLeap(eyear + INDIAN_ERA_START) && month == 0) {
@@ -189,7 +189,7 @@
    return gregorianDate;
 }
 
-   
+
 //-------------------------------------------------------------------------
 // Functions for converting from field values to milliseconds....
 //-------------------------------------------------------------------------
@@ -203,7 +203,7 @@
    if(isGregorianLeap(gyear)) {
       leapMonth = 31;
       start = gregorianToJD(gyear, 3, 21);
-   } 
+   }
    else {
       leapMonth = 30;
       start = gregorianToJD(gyear, 3, 22);
@@ -239,20 +239,20 @@
  */
 int32_t IndianCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool useMonth) const {
 
-   //month is 0 based; converting it to 1-based 
+   //month is 0 based; converting it to 1-based
    int32_t imonth;
 
     // If the month is out of range, adjust it into range, and adjust the extended eyar accordingly
    if (month < 0 || month > 11) {
-      eyear += (int32_t)Math::floorDivide(month, 12, month);
+      eyear += (int32_t)ClockMath::floorDivide(month, 12, month);
    }
 
    if(month == 12){
        imonth = 1;
    } else {
-       imonth = month + 1; 
+       imonth = month + 1;
    }
-   
+
    double jd = IndianToJD(eyear ,imonth, 1);
 
    return (int32_t)jd;
@@ -283,7 +283,7 @@
  * <li>MONTH
  * <li>DAY_OF_MONTH
  * <li>EXTENDED_YEAR</ul>
- * 
+ *
  * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
  * method is called. The getGregorianXxx() methods return Gregorian
  * calendar equivalents for the given Julian day.
@@ -330,7 +330,7 @@
    internalSet(UCAL_MONTH, IndianMonth);
    internalSet(UCAL_DAY_OF_MONTH, IndianDayOfMonth);
    internalSet(UCAL_DAY_OF_YEAR, yday + 1); // yday is 0-based
-}    
+}
 
 UBool
 IndianCalendar::inDaylightTime(UErrorCode& status) const
@@ -374,7 +374,7 @@
 {
     // lazy-evaluate systemDefaultCenturyStart
     UBool needsUpdate;
-    { 
+    {
         Mutex m;
         needsUpdate = (fgSystemDefaultCenturyStart == fgSystemDefaultCentury);
     }
@@ -394,7 +394,7 @@
 {
     // lazy-evaluate systemDefaultCenturyStartYear
     UBool needsUpdate;
-    { 
+    {
         Mutex m;
 
         needsUpdate = (fgSystemDefaultCenturyStart == fgSystemDefaultCentury);
@@ -446,4 +446,3 @@
 U_NAMESPACE_END
 
 #endif
-
diff -Nura icu/source/i18n/islamcal.cpp icu_new/source/i18n/islamcal.cpp
--- icu/source/i18n/islamcal.cpp	2008-07-01 09:40:48.000000000 +0800
+++ icu_new/source/i18n/islamcal.cpp	2018-05-25 14:48:25.864575501 +0800
@@ -78,7 +78,7 @@
 // Constructors...
 //-------------------------------------------------------------------------
 
-const char *IslamicCalendar::getType() const { 
+const char *IslamicCalendar::getType() const {
     if(civil==CIVIL) {
         return "islamic-civil";
     } else {
@@ -194,7 +194,7 @@
 */
 int32_t IslamicCalendar::yearStart(int32_t year) {
     if (civil == CIVIL) {
-        return (year-1)*354 + Math::floorDivide((3+11*year),30);
+        return (year-1)*354 + ClockMath::floorDivide((3+11*year),30);
     } else {
         return trueMonthStart(12*(year-1));
     }
@@ -210,7 +210,7 @@
 int32_t IslamicCalendar::monthStart(int32_t year, int32_t month) const {
     if (civil == CIVIL) {
         return (int32_t)uprv_ceil(29.5*month)
-            + (year-1)*354 + (int32_t)Math::floorDivide((3+11*year),30);
+            + (year-1)*354 + (int32_t)ClockMath::floorDivide((3+11*year),30);
     } else {
         return trueMonthStart(12*(year-1) + month);
     }
@@ -231,7 +231,7 @@
 
     if (start==0) {
         // Make a guess at when the month started, using the average length
-        UDate origin = HIJRA_MILLIS 
+        UDate origin = HIJRA_MILLIS
             + uprv_floor(month * CalendarAstronomer::SYNODIC_MONTH - 1) * kOneDay;
 
         // moonAge will fail due to memory allocation error
@@ -260,7 +260,7 @@
                 }
             } while (age < 0);
         }
-        start = (int32_t)Math::floorDivide((origin - HIJRA_MILLIS), (double)kOneDay) + 1;
+        start = (int32_t)ClockMath::floorDivide((origin - HIJRA_MILLIS), (double)kOneDay) + 1;
         CalendarCache::put(&gMonthCache, month, start, status);
     }
 trueMonthStartEnd :
@@ -273,7 +273,7 @@
 /**
 * Return the "age" of the moon at the given time; this is the difference
 * in ecliptic latitude between the moon and the sun.  This method simply
-* calls CalendarAstronomer.moonAge, converts to degrees, 
+* calls CalendarAstronomer.moonAge, converts to degrees,
 * and adjusts the result to be in the range [-180, 180].
 *
 * @param time  The time at which the moon's age is desired,
@@ -355,7 +355,7 @@
 */
 int32_t IslamicCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool /* useMonth */) const {
     return monthStart(eyear, month) + 1948439;
-}    
+}
 
 //-------------------------------------------------------------------------
 // Functions for converting from milliseconds to field values
@@ -384,7 +384,7 @@
 * <li>DAY_OF_MONTH
 * <li>DAY_OF_YEAR
 * <li>EXTENDED_YEAR</ul>
-* 
+*
 * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
 * method is called. The getGregorianXxx() methods return Gregorian
 * calendar equivalents for the given Julian day.
@@ -397,7 +397,7 @@
 
     if (civil == CIVIL) {
         // Use the civil calendar approximation, which is just arithmetic
-        year  = (int)Math::floorDivide( (double)(30 * days + 10646) , 10631.0 );
+        year  = (int)ClockMath::floorDivide( (double)(30 * days + 10646) , 10631.0 );
         month = (int32_t)uprv_ceil((days - 29 - yearStart(year)) / 29.5 );
         month = month<11?month:11;
         startDate = monthStart(year, month);
@@ -438,14 +438,14 @@
     internalSet(UCAL_EXTENDED_YEAR, year);
     internalSet(UCAL_MONTH, month);
     internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
-    internalSet(UCAL_DAY_OF_YEAR, dayOfYear);       
-}    
+    internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
+}
 
 UBool
 IslamicCalendar::inDaylightTime(UErrorCode& status) const
 {
     // copied from GregorianCalendar
-    if (U_FAILURE(status) || (&(getTimeZone()) == NULL && !getTimeZone().useDaylightTime())) 
+    if (U_FAILURE(status) || (&(getTimeZone()) == NULL && !getTimeZone().useDaylightTime()))
         return FALSE;
 
     // Force an update of the state of the Calendar.
@@ -545,4 +545,3 @@
 U_NAMESPACE_END
 
 #endif
-
diff -Nura icu/source/i18n/olsontz.cpp icu_new/source/i18n/olsontz.cpp
--- icu/source/i18n/olsontz.cpp	2008-07-01 09:40:50.000000000 +0800
+++ icu_new/source/i18n/olsontz.cpp	2018-05-25 14:44:13.942466322 +0800
@@ -113,7 +113,7 @@
             ec = U_INVALID_FORMAT_ERROR;
         }
         transitionCount = (int16_t) i;
-        
+
         // Type offsets list must be of even size, with size >= 2
         r = ures_getByIndex(res, 1, r, &ec);
         typeOffsets = ures_getIntVector(r, &i, &ec);
@@ -122,7 +122,7 @@
         }
         typeCount = (int16_t) i >> 1;
 
-        // Type data must be of the same size as the transitions list        
+        // Type data must be of the same size as the transitions list
         r = ures_getByIndex(res, 2, r, &ec);
         int32_t len;
         typeData = ures_getBinary(r, &len, &ec);
@@ -138,8 +138,8 @@
           for(jj=0;jj<transitionCount;jj++) {
             int32_t year, month, dom, dow;
             double millis=0;
-            double days = Math::floorDivide(((double)transitionTimes[jj])*1000.0, (double)U_MILLIS_PER_DAY, millis);
-            
+            double days = ClockMath::floorDivide(((double)transitionTimes[jj])*1000.0, (double)U_MILLIS_PER_DAY, millis);
+
             Grego::dayToFields(days, year, month, dom, dow);
             U_DEBUG_TZ_MSG(("   Transition %d:  time %d (%04d.%02d.%02d+%.1fh), typedata%d\n", jj, transitionTimes[jj],
                             year, month+1, dom, (millis/kOneHour), typeData[jj]));
@@ -185,7 +185,7 @@
                         data = ures_getIntVector(r, &len, &ec);
                         if (U_SUCCESS(ec) && len == 11) {
                             UnicodeString emptyStr;
-                            U_DEBUG_TZ_MSG(("zone%s, rule%s: {%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d}\n", zKey, ures_getKey(r), 
+                            U_DEBUG_TZ_MSG(("zone%s, rule%s: {%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d}\n", zKey, ures_getKey(r),
                                           data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10]));
                             finalZone = new SimpleTimeZone(rawOffset, emptyStr,
                                 (int8_t)data[0], (int8_t)data[1], (int8_t)data[2],
@@ -385,8 +385,8 @@
 void printTime(double ms) {
             int32_t year, month, dom, dow;
             double millis=0;
-            double days = Math::floorDivide(((double)ms), (double)U_MILLIS_PER_DAY, millis);
-            
+            double days = ClockMath::floorDivide(((double)ms), (double)U_MILLIS_PER_DAY, millis);
+
             Grego::dayToFields(days, year, month, dom, dow);
             U_DEBUG_TZ_MSG(("   getHistoricalOffset:  time %.1f (%04d.%02d.%02d+%.1fh)\n", ms,
                             year, month+1, dom, (millis/kOneHour)));
@@ -419,7 +419,7 @@
 
                 UBool dstToStd = dstBefore && !dstAfter;
                 UBool stdToDst = !dstBefore && dstAfter;
-                
+
                 if (offsetAfter - offsetBefore >= 0) {
                     // Positive transition, which makes a non-existing local time range
                     if (((NonExistingTimeOpt & kStdDstMask) == kStandard && dstToStd)
@@ -505,10 +505,10 @@
     // DST is in use in the current year (at any point in the year)
     // and returns TRUE if so.
 
-    int32_t days = (int32_t)Math::floorDivide(uprv_getUTCtime(), (double)U_MILLIS_PER_DAY); // epoch days
+    int32_t days = (int32_t)ClockMath::floorDivide(uprv_getUTCtime(), (double)U_MILLIS_PER_DAY); // epoch days
 
     int32_t year, month, dom, dow;
-    
+
     Grego::dayToFields(days, year, month, dom, dow);
 
     if (year > finalYear) { // [sic] >, not >=; see above
@@ -517,8 +517,8 @@
     }
 
     // Find start of this year, and start of next year
-    int32_t start = (int32_t) Grego::fieldsToDay(year, 0, 1) * SECONDS_PER_DAY;    
-    int32_t limit = (int32_t) Grego::fieldsToDay(year+1, 0, 1) * SECONDS_PER_DAY;    
+    int32_t start = (int32_t) Grego::fieldsToDay(year, 0, 1) * SECONDS_PER_DAY;
+    int32_t limit = (int32_t) Grego::fieldsToDay(year+1, 0, 1) * SECONDS_PER_DAY;
 
     // Return TRUE if DST is observed at any time during the current
     // year.
@@ -533,7 +533,7 @@
     }
     return FALSE;
 }
-int32_t 
+int32_t
 OlsonTimeZone::getDSTSavings() const{
     if(finalZone!=NULL){
         return finalZone->getDSTSavings();
@@ -565,7 +565,7 @@
     if (typeData == z->typeData) {
         return TRUE;
     }
-    
+
      // If the pointers are not equal, the zones may still
      // be equal if their rules and transitions are equal
     return
@@ -573,7 +573,7 @@
           // Don't compare finalMillis; if finalYear is ==, so is finalMillis
           ((finalZone == 0 && z->finalZone == 0) ||
             (finalZone != 0 && z->finalZone != 0 && *finalZone == *z->finalZone)) &&
-          
+
           transitionCount == z->transitionCount &&
           typeCount == z->typeCount &&
           uprv_memcmp(transitionTimes, z->transitionTimes,
@@ -895,7 +895,7 @@
             } else {
                 result = *firstFinalTZTransition;
                 return TRUE;
-            }                
+            }
         }
     }
 
diff -Nura icu/source/i18n/zonemeta.cpp icu_new/source/i18n/zonemeta.cpp
--- icu/source/i18n/zonemeta.cpp	2008-07-01 09:40:48.000000000 +0800
+++ icu_new/source/i18n/zonemeta.cpp	2018-05-23 18:23:21.372299488 +0800
@@ -511,7 +511,6 @@
                 mzMappings = new UVector(deleteOlsonToMetaMappingEntry, NULL, status);
                 if (U_FAILURE(status)) {
                     delete mzMappings;
-                    deleteOlsonToMetaMappingEntry(entry);
                     uprv_free(entry);
                     break;
                 }
diff -Nura icu/source/test/intltest/calregts.cpp icu_new/source/test/intltest/calregts.cpp
--- icu/source/test/intltest/calregts.cpp	2008-07-01 09:40:58.000000000 +0800
+++ icu_new/source/test/intltest/calregts.cpp	2018-05-23 17:18:21.801530898 +0800
@@ -10,6 +10,7 @@
 
 #include "calregts.h"
 
+#include "unicode/calendar.h"
 #include "unicode/gregocal.h"
 #include "unicode/simpletz.h"
 #include "unicode/smpdtfmt.h"
@@ -82,6 +83,7 @@
         CASE(43,TestTimeZoneTransitionAdd);
         CASE(44,TestDeprecates);
         CASE(45,TestT5555);
+        CASE(52,TestPersianCalOverflow);
     default: name = ""; break;
     }
 }
@@ -2654,7 +2656,37 @@
 
     delete c1;
     delete c2;
+
 }
 
+/**
+ * @bug ticket 13454
+ */
+void CalendarRegressionTest::TestPersianCalOverflow(void) {
+    const char* localeID = "bs_Cyrl@calendar=persian";
+    UErrorCode status = U_ZERO_ERROR;
+    Calendar* cal = Calendar::createInstance(Locale(localeID), status);
+    if(U_FAILURE(status)) {
+        dataerrln("FAIL: Calendar::createInstance for localeID %s: %s", localeID, u_errorName(status));
+    } else {
+        int32_t maxMonth = cal->getMaximum(UCAL_MONTH);
+        int32_t maxDayOfMonth = cal->getMaximum(UCAL_DATE);
+        int32_t jd, month, dayOfMonth;
+        for (jd = 67023580; jd <= 67023584; jd++) { // year 178171, int32_t overflow if jd >= 67023582
+            status = U_ZERO_ERROR;
+            cal->clear();
+            cal->set(UCAL_JULIAN_DAY, jd);
+            month = cal->get(UCAL_MONTH, status);
+            dayOfMonth = cal->get(UCAL_DATE, status);
+            if ( U_FAILURE(status) ) {
+                errln("FAIL: Calendar->get MONTH/DATE for localeID %s, julianDay %d, status %s\n", localeID, jd, u_errorName(status)); 
+            } else if (month > maxMonth || dayOfMonth > maxDayOfMonth) {
+                errln("FAIL: localeID %s, julianDay %d; maxMonth %d, got month %d; maxDayOfMonth %d, got dayOfMonth %d\n",
+                        localeID, jd, maxMonth, month, maxDayOfMonth, dayOfMonth); 
+            }
+        }
+        delete cal;
+    }
+}
 
 #endif /* #if !UCONFIG_NO_FORMATTING */
diff -Nura icu/source/test/intltest/calregts.h icu_new/source/test/intltest/calregts.h
--- icu/source/test/intltest/calregts.h	2008-07-01 09:40:58.000000000 +0800
+++ icu_new/source/test/intltest/calregts.h	2018-05-23 17:19:26.512058075 +0800
@@ -70,6 +70,7 @@
     void TestWeekShift(void);
     void TestTimeZoneTransitionAdd(void);
     void TestDeprecates(void);
+    void TestPersianCalOverflow(void);
 
     void printdate(GregorianCalendar *cal, const char *string);
     void dowTest(UBool lenient) ;
diff -Nura icu/source/test/intltest/convtest.cpp icu_new/source/test/intltest/convtest.cpp
--- icu/source/test/intltest/convtest.cpp	2008-07-01 09:40:58.000000000 +0800
+++ icu_new/source/test/intltest/convtest.cpp	2018-05-23 17:57:31.761675292 +0800
@@ -71,6 +71,7 @@
         case 1: name="TestFromUnicode"; if (exec) TestFromUnicode(); break;
         case 2: name="TestGetUnicodeSet"; if (exec) TestGetUnicodeSet(); break;
         case 3: name="TestGetUnicodeSet2"; if (exec) TestGetUnicodeSet2(); break;
+        case 3: name="TestUTF8ToUTF8Overflow"; if (exec) TestUTF8ToUTF8Overflow(); break;
         default: name=""; break; //needed to end loop
     }
 }
@@ -644,6 +645,47 @@
     delete [] s0;
 }
 
+void
+ConversionTest::TestUTF8ToUTF8Overflow() {
+    IcuTestErrorCode errorCode(*this, "TestUTF8ToUTF8Overflow");
+    LocalUConverterPointer cnv1(ucnv_open("UTF-8", errorCode));
+    LocalUConverterPointer cnv2(ucnv_open("UTF-8", errorCode));
+    static const char *text = "aä";
+    const char *source = text;
+    const char *sourceLimit = text + strlen(text);
+    char result[20];
+    char *target = result;
+    const char *targetLimit = result + sizeof(result);
+    UChar buffer16[20];
+    UChar *pivotSource = buffer16;
+    UChar *pivotTarget = buffer16;
+    const UChar *pivotLimit = buffer16 + UPRV_LENGTHOF(buffer16);
+
+    // Convert with insufficient target capacity.
+    result[2] = 5;
+    ucnv_convertEx(cnv2.getAlias(), cnv1.getAlias(),
+                   &target, result + 2, &source, sourceLimit,
+                   buffer16, &pivotSource, &pivotTarget, pivotLimit,
+                   FALSE, FALSE, errorCode);
+    assertEquals("overflow", U_BUFFER_OVERFLOW_ERROR, errorCode.reset());
+    int32_t length = (int32_t)(target - result);
+    assertEquals("number of bytes written", 2, length);
+    assertEquals("next byte not clobbered", 5, result[2]);
+
+    // Convert the rest and flush.
+    ucnv_convertEx(cnv2.getAlias(), cnv1.getAlias(),
+                   &target, targetLimit, &source, sourceLimit,
+                   buffer16, &pivotSource, &pivotTarget, pivotLimit,
+                   FALSE, TRUE, errorCode);
+
+    assertSuccess("UTF-8->UTF-8", errorCode);
+    length = (int32_t)(target - result);
+    assertEquals("3 bytes", 3, length);
+    if (length == 3) {
+        assertTrue("result same as input", memcmp(text, result, length) == 0);
+    }
+}
+
 // open testdata or ICU data converter ------------------------------------- ***
 
 UConverter *
diff -Nura icu/source/test/intltest/convtest.h icu_new/source/test/intltest/convtest.h
--- icu/source/test/intltest/convtest.h	2008-07-01 09:40:58.000000000 +0800
+++ icu_new/source/test/intltest/convtest.h	2018-05-23 17:22:14.444426167 +0800
@@ -73,6 +73,7 @@
     void TestFromUnicode();
     void TestGetUnicodeSet();
     void TestGetUnicodeSet2();
+    void TestUTF8ToUTF8Overflow();
 
 private:
     UBool
diff -Nura icu/source/test/intltest/ustrtest.h icu_new/source/test/intltest/ustrtest.h
--- icu/source/test/intltest/ustrtest.h	2008-07-01 09:40:58.000000000 +0800
+++ icu_new/source/test/intltest/ustrtest.h	2018-05-23 17:59:58.765872890 +0800
@@ -19,6 +19,7 @@
     virtual ~UnicodeStringTest();
     
     void runIndexedTest( int32_t index, UBool exec, const char* &name, char* par = NULL );
+    void Ticket12888();
 
     /**
      * Test some basic methods (insert, remove, replace, ...)
diff -Nura icu/source/test/intltest/utxttest.cpp icu_new/source/test/intltest/utxttest.cpp
--- icu/source/test/intltest/utxttest.cpp	2008-07-01 09:40:58.000000000 +0800
+++ icu_new/source/test/intltest/utxttest.cpp	2018-05-23 18:02:26.895079652 +0800
@@ -54,8 +54,10 @@
             if (exec) ErrorTest();   break;
         case 2: name = "FreezeTest";
             if (exec) FreezeTest();  break;
-		case 3: name = "Ticket5560";
-			if (exec) Ticket5560();  break;
+	      	case 3: name = "Ticket5560";
+			        if (exec) Ticket5560();  break;
+        case 8: name = "Ticket12888";
+            if (exec) Ticket12888(); break;
         default: name = "";          break;
     }
 }
@@ -1398,3 +1400,63 @@
     utext_close(&ut2);
 }
 
+
+// Ticket 12888: bad handling of illegal utf-8 containing many instances of the archaic, now illegal,
+//               six byte utf-8 forms. Original implementation had an assumption that
+//               there would be at most three utf-8 bytes per UTF-16 code unit.
+//               The five and six byte sequences map to a single replacement character.
+
+void UTextTest::Ticket12888() {
+    const char *badString = 
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80"
+            "\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80\xfd\x80\x80\x80\x80\x80";
+
+    UErrorCode status = U_ZERO_ERROR;
+    LocalUTextPointer ut(utext_openUTF8(NULL, badString, -1, &status));
+    TEST_SUCCESS(status);
+    for (;;) {
+        UChar32 c = utext_next32(ut.getAlias());
+        if (c == U_SENTINEL) {
+            break;
+        }
+    }
+    int32_t endIdx = utext_getNativeIndex(ut.getAlias());
+    if (endIdx != (int32_t)strlen(badString)) {
+        errln("%s:%d expected=%d, actual=%d", __FILE__, __LINE__, strlen(badString), endIdx);
+        return;
+    }
+
+    for (int32_t prevIndex = endIdx; prevIndex>0;) {
+        UChar32 c = utext_previous32(ut.getAlias());
+        int32_t currentIndex = utext_getNativeIndex(ut.getAlias());
+        if (c != 0xfffd) {
+            errln("%s:%d (expected, actual, index) = (%d, %d, %d)\n",
+                    __FILE__, __LINE__, 0xfffd, c, currentIndex);
+            break;
+        }
+        if (currentIndex != prevIndex - 6) {
+            errln("%s:%d: wrong index. Expected, actual = %d, %d",
+                    __FILE__, __LINE__, prevIndex - 6, currentIndex);
+            break;
+        }
+        prevIndex = currentIndex;
+    }
+}
