summaryrefslogtreecommitdiff
path: root/tests/setlocale.c
blob: eb263617dc8c83a4aadf6f6620a9682e1b020731 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
/* Set the current locale.  -*- coding: utf-8 -*-
   Copyright (C) 2009, 2011-2024 Free Software Foundation, Inc.

   This file is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as
   published by the Free Software Foundation, either version 3 of the
   License, or (at your option) any later version.

   This file is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */

/* Written by Bruno Haible <bruno@clisp.org>, 2009.  */

#include <config.h>

/* Override setlocale() so that when the default locale is requested
   (locale = ""), the environment variables LC_ALL, LC_*, and LANG are
   considered.
   Also include all the functionality from libintl's setlocale() override.  */

/* Please keep this file in sync with
   gettext/gettext-runtime/intl/setlocale.c !  */

/* Specification.  */
#include <locale.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "localename.h"

#if HAVE_CFLOCALECOPYPREFERREDLANGUAGES || HAVE_CFPREFERENCESCOPYAPPVALUE
# if HAVE_CFLOCALECOPYPREFERREDLANGUAGES
#  include <CoreFoundation/CFLocale.h>
# elif HAVE_CFPREFERENCESCOPYAPPVALUE
#  include <CoreFoundation/CFPreferences.h>
# endif
# include <CoreFoundation/CFPropertyList.h>
# include <CoreFoundation/CFArray.h>
# include <CoreFoundation/CFString.h>
extern void gl_locale_name_canonicalize (char *name);
#endif

#if 1

# undef setlocale

/* Which of the replacements to activate?  */
# if NEED_SETLOCALE_IMPROVED
#  define setlocale_improved rpl_setlocale
# elif NEED_SETLOCALE_MTSAFE
#  define setlocale_mtsafe rpl_setlocale
# else
#  error "This file should only be compiled if NEED_SETLOCALE_IMPROVED || NEED_SETLOCALE_MTSAFE."
# endif

/* Like setlocale, but guaranteed to be multithread-safe if LOCALE == NULL.  */
# if !SETLOCALE_NULL_ALL_MTSAFE || !SETLOCALE_NULL_ONE_MTSAFE /* i.e. if NEED_SETLOCALE_MTSAFE */

#  if NEED_SETLOCALE_IMPROVED
static
#  endif
char *
setlocale_mtsafe (int category, const char *locale)
{
  if (locale == NULL)
    return (char *) setlocale_null (category);
  else
    return setlocale (category, locale);
}
# else /* !NEED_SETLOCALE_MTSAFE */

#  define setlocale_mtsafe setlocale

# endif /* NEED_SETLOCALE_MTSAFE */

# if NEED_SETLOCALE_IMPROVED

/* Return string representation of locale category CATEGORY.  */
static const char *
category_to_name (int category)
{
  const char *retval;

  switch (category)
  {
  case LC_COLLATE:
    retval = "LC_COLLATE";
    break;
  case LC_CTYPE:
    retval = "LC_CTYPE";
    break;
  case LC_MONETARY:
    retval = "LC_MONETARY";
    break;
  case LC_NUMERIC:
    retval = "LC_NUMERIC";
    break;
  case LC_TIME:
    retval = "LC_TIME";
    break;
  case LC_MESSAGES:
    retval = "LC_MESSAGES";
    break;
  default:
    /* If you have a better idea for a default value let me know.  */
    retval = "LC_XXX";
  }

  return retval;
}

#  if defined _WIN32 && ! defined __CYGWIN__

/* The native Windows setlocale() function expects locale names of the form
   "German" or "German_Germany" or "DEU", but not "de" or "de_DE".  We need
   to convert the names from the form with ISO 639 language code and ISO 3166
   country code to the form with English names or with three-letter identifier.
   The three-letter identifiers known by a Windows XP SP2 or SP3 are:
     AFK  Afrikaans_South Africa.1252
     ARA  Arabic_Saudi Arabia.1256
     ARB  Arabic_Lebanon.1256
     ARE  Arabic_Egypt.1256
     ARG  Arabic_Algeria.1256
     ARH  Arabic_Bahrain.1256
     ARI  Arabic_Iraq.1256
     ARJ  Arabic_Jordan.1256
     ARK  Arabic_Kuwait.1256
     ARL  Arabic_Libya.1256
     ARM  Arabic_Morocco.1256
     ARO  Arabic_Oman.1256
     ARQ  Arabic_Qatar.1256
     ARS  Arabic_Syria.1256
     ART  Arabic_Tunisia.1256
     ARU  Arabic_U.A.E..1256
     ARY  Arabic_Yemen.1256
     AZE  Azeri (Latin)_Azerbaijan.1254
     BEL  Belarusian_Belarus.1251
     BGR  Bulgarian_Bulgaria.1251
     BSB  Bosnian_Bosnia and Herzegovina.1250
     BSC  Bosnian (Cyrillic)_Bosnia and Herzegovina.1250  (wrong encoding!)
     CAT  Catalan_Spain.1252
     CHH  Chinese_Hong Kong S.A.R..950
     CHI  Chinese_Singapore.936
     CHS  Chinese_People's Republic of China.936
     CHT  Chinese_Taiwan.950
     CSY  Czech_Czech Republic.1250
     CYM  Welsh_United Kingdom.1252
     DAN  Danish_Denmark.1252
     DEA  German_Austria.1252
     DEC  German_Liechtenstein.1252
     DEL  German_Luxembourg.1252
     DES  German_Switzerland.1252
     DEU  German_Germany.1252
     ELL  Greek_Greece.1253
     ENA  English_Australia.1252
     ENB  English_Caribbean.1252
     ENC  English_Canada.1252
     ENG  English_United Kingdom.1252
     ENI  English_Ireland.1252
     ENJ  English_Jamaica.1252
     ENL  English_Belize.1252
     ENP  English_Republic of the Philippines.1252
     ENS  English_South Africa.1252
     ENT  English_Trinidad and Tobago.1252
     ENU  English_United States.1252
     ENW  English_Zimbabwe.1252
     ENZ  English_New Zealand.1252
     ESA  Spanish_Panama.1252
     ESB  Spanish_Bolivia.1252
     ESC  Spanish_Costa Rica.1252
     ESD  Spanish_Dominican Republic.1252
     ESE  Spanish_El Salvador.1252
     ESF  Spanish_Ecuador.1252
     ESG  Spanish_Guatemala.1252
     ESH  Spanish_Honduras.1252
     ESI  Spanish_Nicaragua.1252
     ESL  Spanish_Chile.1252
     ESM  Spanish_Mexico.1252
     ESN  Spanish_Spain.1252
     ESO  Spanish_Colombia.1252
     ESP  Spanish_Spain.1252
     ESR  Spanish_Peru.1252
     ESS  Spanish_Argentina.1252
     ESU  Spanish_Puerto Rico.1252
     ESV  Spanish_Venezuela.1252
     ESY  Spanish_Uruguay.1252
     ESZ  Spanish_Paraguay.1252
     ETI  Estonian_Estonia.1257
     EUQ  Basque_Spain.1252
     FAR  Farsi_Iran.1256
     FIN  Finnish_Finland.1252
     FOS  Faroese_Faroe Islands.1252
     FPO  Filipino_Philippines.1252
     FRA  French_France.1252
     FRB  French_Belgium.1252
     FRC  French_Canada.1252
     FRL  French_Luxembourg.1252
     FRM  French_Principality of Monaco.1252
     FRS  French_Switzerland.1252
     FYN  Frisian_Netherlands.1252
     GLC  Galician_Spain.1252
     HEB  Hebrew_Israel.1255
     HRB  Croatian_Bosnia and Herzegovina.1250
     HRV  Croatian_Croatia.1250
     HUN  Hungarian_Hungary.1250
     IND  Indonesian_Indonesia.1252
     IRE  Irish_Ireland.1252
     ISL  Icelandic_Iceland.1252
     ITA  Italian_Italy.1252
     ITS  Italian_Switzerland.1252
     IUK  Inuktitut (Latin)_Canada.1252
     JPN  Japanese_Japan.932
     KKZ  Kazakh_Kazakhstan.1251
     KOR  Korean_Korea.949
     KYR  Kyrgyz_Kyrgyzstan.1251
     LBX  Luxembourgish_Luxembourg.1252
     LTH  Lithuanian_Lithuania.1257
     LVI  Latvian_Latvia.1257
     MKI  FYRO Macedonian_Former Yugoslav Republic of Macedonia.1251
     MON  Mongolian_Mongolia.1251
     MPD  Mapudungun_Chile.1252
     MSB  Malay_Brunei Darussalam.1252
     MSL  Malay_Malaysia.1252
     MWK  Mohawk_Canada.1252
     NLB  Dutch_Belgium.1252
     NLD  Dutch_Netherlands.1252
     NON  Norwegian-Nynorsk_Norway.1252
     NOR  Norwegian (Bokmål)_Norway.1252
     NSO  Northern Sotho_South Africa.1252
     PLK  Polish_Poland.1250
     PTB  Portuguese_Brazil.1252
     PTG  Portuguese_Portugal.1252
     QUB  Quechua_Bolivia.1252
     QUE  Quechua_Ecuador.1252
     QUP  Quechua_Peru.1252
     RMC  Romansh_Switzerland.1252
     ROM  Romanian_Romania.1250
     RUS  Russian_Russia.1251
     SKY  Slovak_Slovakia.1250
     SLV  Slovenian_Slovenia.1250
     SMA  Sami (Southern)_Norway.1252
     SMB  Sami (Southern)_Sweden.1252
     SME  Sami (Northern)_Norway.1252
     SMF  Sami (Northern)_Sweden.1252
     SMG  Sami (Northern)_Finland.1252
     SMJ  Sami (Lule)_Norway.1252
     SMK  Sami (Lule)_Sweden.1252
     SMN  Sami (Inari)_Finland.1252
     SMS  Sami (Skolt)_Finland.1252
     SQI  Albanian_Albania.1250
     SRB  Serbian (Cyrillic)_Serbia and Montenegro.1251
     SRL  Serbian (Latin)_Serbia and Montenegro.1250
     SRN  Serbian (Cyrillic)_Bosnia and Herzegovina.1251
     SRS  Serbian (Latin)_Bosnia and Herzegovina.1250
     SVE  Swedish_Sweden.1252
     SVF  Swedish_Finland.1252
     SWK  Swahili_Kenya.1252
     THA  Thai_Thailand.874
     TRK  Turkish_Turkey.1254
     TSN  Tswana_South Africa.1252
     TTT  Tatar_Russia.1251
     UKR  Ukrainian_Ukraine.1251
     URD  Urdu_Islamic Republic of Pakistan.1256
     USA  English_United States.1252
     UZB  Uzbek (Latin)_Uzbekistan.1254
     VIT  Vietnamese_Viet Nam.1258
     XHO  Xhosa_South Africa.1252
     ZHH  Chinese_Hong Kong S.A.R..950
     ZHI  Chinese_Singapore.936
     ZHM  Chinese_Macau S.A.R..950
     ZUL  Zulu_South Africa.1252
 */

/* Table from ISO 639 language code, optionally with country or script suffix,
   to English name.
   Keep in sync with the gl_locale_name_from_win32_LANGID function in
   localename.c!  */
struct table_entry
{
  const char *code;
  const char *english;
};
static const struct table_entry language_table[] =
  {
    { "af", "Afrikaans" },
    { "am", "Amharic" },
    { "ar", "Arabic" },
    { "arn", "Mapudungun" },
    { "as", "Assamese" },
    { "az@cyrillic", "Azeri (Cyrillic)" },
    { "az@latin", "Azeri (Latin)" },
    { "ba", "Bashkir" },
    { "be", "Belarusian" },
    { "ber", "Tamazight" },
    { "ber@arabic", "Tamazight (Arabic)" },
    { "ber@latin", "Tamazight (Latin)" },
    { "bg", "Bulgarian" },
    { "bin", "Edo" },
    { "bn", "Bengali" },
    { "bn_BD", "Bengali (Bangladesh)" },
    { "bn_IN", "Bengali (India)" },
    { "bnt", "Sutu" },
    { "bo", "Tibetan" },
    { "br", "Breton" },
    { "bs", "BSB" }, /* "Bosnian (Latin)" */
    { "bs@cyrillic", "BSC" }, /* Bosnian (Cyrillic) */
    { "ca", "Catalan" },
    { "chr", "Cherokee" },
    { "co", "Corsican" },
    { "cpe", "Hawaiian" },
    { "cs", "Czech" },
    { "cy", "Welsh" },
    { "da", "Danish" },
    { "de", "German" },
    { "dsb", "Lower Sorbian" },
    { "dv", "Divehi" },
    { "el", "Greek" },
    { "en", "English" },
    { "es", "Spanish" },
    { "et", "Estonian" },
    { "eu", "Basque" },
    { "fa", "Farsi" },
    { "ff", "Fulfulde" },
    { "fi", "Finnish" },
    { "fo", "Faroese" }, /* "Faeroese" does not work */
    { "fr", "French" },
    { "fy", "Frisian" },
    { "ga", "IRE" }, /* Gaelic (Ireland) */
    { "gd", "Gaelic (Scotland)" },
    { "gd", "Scottish Gaelic" },
    { "gl", "Galician" },
    { "gn", "Guarani" },
    { "gsw", "Alsatian" },
    { "gu", "Gujarati" },
    { "ha", "Hausa" },
    { "he", "Hebrew" },
    { "hi", "Hindi" },
    { "hr", "Croatian" },
    { "hsb", "Upper Sorbian" },
    { "hu", "Hungarian" },
    { "hy", "Armenian" },
    { "id", "Indonesian" },
    { "ig", "Igbo" },
    { "ii", "Yi" },
    { "is", "Icelandic" },
    { "it", "Italian" },
    { "iu", "IUK" }, /* Inuktitut */
    { "ja", "Japanese" },
    { "ka", "Georgian" },
    { "kk", "Kazakh" },
    { "kl", "Greenlandic" },
    { "km", "Cambodian" },
    { "km", "Khmer" },
    { "kn", "Kannada" },
    { "ko", "Korean" },
    { "kok", "Konkani" },
    { "kr", "Kanuri" },
    { "ks", "Kashmiri" },
    { "ks_IN", "Kashmiri_India" },
    { "ks_PK", "Kashmiri (Arabic)_Pakistan" },
    { "ky", "Kyrgyz" },
    { "la", "Latin" },
    { "lb", "Luxembourgish" },
    { "lo", "Lao" },
    { "lt", "Lithuanian" },
    { "lv", "Latvian" },
    { "mi", "Maori" },
    { "mk", "FYRO Macedonian" },
    { "mk", "Macedonian" },
    { "ml", "Malayalam" },
    { "mn", "Mongolian" },
    { "mni", "Manipuri" },
    { "moh", "Mohawk" },
    { "mr", "Marathi" },
    { "ms", "Malay" },
    { "mt", "Maltese" },
    { "my", "Burmese" },
    { "nb", "NOR" }, /* Norwegian Bokmål */
    { "ne", "Nepali" },
    { "nic", "Ibibio" },
    { "nl", "Dutch" },
    { "nn", "NON" }, /* Norwegian Nynorsk */
    { "no", "Norwegian" },
    { "nso", "Northern Sotho" },
    { "nso", "Sepedi" },
    { "oc", "Occitan" },
    { "om", "Oromo" },
    { "or", "Oriya" },
    { "pa", "Punjabi" },
    { "pap", "Papiamentu" },
    { "pl", "Polish" },
    { "prs", "Dari" },
    { "ps", "Pashto" },
    { "pt", "Portuguese" },
    { "qu", "Quechua" },
    { "qut", "K'iche'" },
    { "rm", "Romansh" },
    { "ro", "Romanian" },
    { "ru", "Russian" },
    { "rw", "Kinyarwanda" },
    { "sa", "Sanskrit" },
    { "sah", "Yakut" },
    { "sd", "Sindhi" },
    { "se", "Sami (Northern)" },
    { "se", "Northern Sami" },
    { "si", "Sinhalese" },
    { "sk", "Slovak" },
    { "sl", "Slovenian" },
    { "sma", "Sami (Southern)" },
    { "sma", "Southern Sami" },
    { "smj", "Sami (Lule)" },
    { "smj", "Lule Sami" },
    { "smn", "Sami (Inari)" },
    { "smn", "Inari Sami" },
    { "sms", "Sami (Skolt)" },
    { "sms", "Skolt Sami" },
    { "so", "Somali" },
    { "sq", "Albanian" },
    { "sr", "Serbian (Latin)" },
    { "sr@cyrillic", "SRB" }, /* Serbian (Cyrillic) */
    { "sv", "Swedish" },
    { "sw", "Swahili" },
    { "syr", "Syriac" },
    { "ta", "Tamil" },
    { "te", "Telugu" },
    { "tg", "Tajik" },
    { "th", "Thai" },
    { "ti", "Tigrinya" },
    { "tk", "Turkmen" },
    { "tl", "Filipino" },
    { "tn", "Tswana" },
    { "tr", "Turkish" },
    { "ts", "Tsonga" },
    { "tt", "Tatar" },
    { "ug", "Uighur" },
    { "uk", "Ukrainian" },
    { "ur", "Urdu" },
    { "uz", "Uzbek" },
    { "uz", "Uzbek (Latin)" },
    { "uz@cyrillic", "Uzbek (Cyrillic)" },
    { "ve", "Venda" },
    { "vi", "Vietnamese" },
    { "wen", "Sorbian" },
    { "wo", "Wolof" },
    { "xh", "Xhosa" },
    { "yi", "Yiddish" },
    { "yo", "Yoruba" },
    { "zh", "Chinese" },
    { "zu", "Zulu" }
  };

/* Table from ISO 3166 country code to English name.
   Keep in sync with the gl_locale_name_from_win32_LANGID function in
   localename.c!  */
static const struct table_entry country_table[] =
  {
    { "AE", "U.A.E." },
    { "AF", "Afghanistan" },
    { "AL", "Albania" },
    { "AM", "Armenia" },
    { "AN", "Netherlands Antilles" },
    { "AR", "Argentina" },
    { "AT", "Austria" },
    { "AU", "Australia" },
    { "AZ", "Azerbaijan" },
    { "BA", "Bosnia and Herzegovina" },
    { "BD", "Bangladesh" },
    { "BE", "Belgium" },
    { "BG", "Bulgaria" },
    { "BH", "Bahrain" },
    { "BN", "Brunei Darussalam" },
    { "BO", "Bolivia" },
    { "BR", "Brazil" },
    { "BT", "Bhutan" },
    { "BY", "Belarus" },
    { "BZ", "Belize" },
    { "CA", "Canada" },
    { "CG", "Congo" },
    { "CH", "Switzerland" },
    { "CI", "Cote d'Ivoire" },
    { "CL", "Chile" },
    { "CM", "Cameroon" },
    { "CN", "People's Republic of China" },
    { "CO", "Colombia" },
    { "CR", "Costa Rica" },
    { "CS", "Serbia and Montenegro" },
    { "CZ", "Czech Republic" },
    { "DE", "Germany" },
    { "DK", "Denmark" },
    { "DO", "Dominican Republic" },
    { "DZ", "Algeria" },
    { "EC", "Ecuador" },
    { "EE", "Estonia" },
    { "EG", "Egypt" },
    { "ER", "Eritrea" },
    { "ES", "Spain" },
    { "ET", "Ethiopia" },
    { "FI", "Finland" },
    { "FO", "Faroe Islands" },
    { "FR", "France" },
    { "GB", "United Kingdom" },
    { "GD", "Caribbean" },
    { "GE", "Georgia" },
    { "GL", "Greenland" },
    { "GR", "Greece" },
    { "GT", "Guatemala" },
    { "HK", "Hong Kong" },
    { "HK", "Hong Kong S.A.R." },
    { "HN", "Honduras" },
    { "HR", "Croatia" },
    { "HT", "Haiti" },
    { "HU", "Hungary" },
    { "ID", "Indonesia" },
    { "IE", "Ireland" },
    { "IL", "Israel" },
    { "IN", "India" },
    { "IQ", "Iraq" },
    { "IR", "Iran" },
    { "IS", "Iceland" },
    { "IT", "Italy" },
    { "JM", "Jamaica" },
    { "JO", "Jordan" },
    { "JP", "Japan" },
    { "KE", "Kenya" },
    { "KG", "Kyrgyzstan" },
    { "KH", "Cambodia" },
    { "KR", "South Korea" },
    { "KW", "Kuwait" },
    { "KZ", "Kazakhstan" },
    { "LA", "Laos" },
    { "LB", "Lebanon" },
    { "LI", "Liechtenstein" },
    { "LK", "Sri Lanka" },
    { "LT", "Lithuania" },
    { "LU", "Luxembourg" },
    { "LV", "Latvia" },
    { "LY", "Libya" },
    { "MA", "Morocco" },
    { "MC", "Principality of Monaco" },
    { "MD", "Moldava" },
    { "MD", "Moldova" },
    { "ME", "Montenegro" },
    { "MK", "Former Yugoslav Republic of Macedonia" },
    { "ML", "Mali" },
    { "MM", "Myanmar" },
    { "MN", "Mongolia" },
    { "MO", "Macau S.A.R." },
    { "MT", "Malta" },
    { "MV", "Maldives" },
    { "MX", "Mexico" },
    { "MY", "Malaysia" },
    { "NG", "Nigeria" },
    { "NI", "Nicaragua" },
    { "NL", "Netherlands" },
    { "NO", "Norway" },
    { "NP", "Nepal" },
    { "NZ", "New Zealand" },
    { "OM", "Oman" },
    { "PA", "Panama" },
    { "PE", "Peru" },
    { "PH", "Philippines" },
    { "PK", "Islamic Republic of Pakistan" },
    { "PL", "Poland" },
    { "PR", "Puerto Rico" },
    { "PT", "Portugal" },
    { "PY", "Paraguay" },
    { "QA", "Qatar" },
    { "RE", "Reunion" },
    { "RO", "Romania" },
    { "RS", "Serbia" },
    { "RU", "Russia" },
    { "RW", "Rwanda" },
    { "SA", "Saudi Arabia" },
    { "SE", "Sweden" },
    { "SG", "Singapore" },
    { "SI", "Slovenia" },
    { "SK", "Slovak" },
    { "SN", "Senegal" },
    { "SO", "Somalia" },
    { "SR", "Suriname" },
    { "SV", "El Salvador" },
    { "SY", "Syria" },
    { "TH", "Thailand" },
    { "TJ", "Tajikistan" },
    { "TM", "Turkmenistan" },
    { "TN", "Tunisia" },
    { "TR", "Turkey" },
    { "TT", "Trinidad and Tobago" },
    { "TW", "Taiwan" },
    { "TZ", "Tanzania" },
    { "UA", "Ukraine" },
    { "US", "United States" },
    { "UY", "Uruguay" },
    { "VA", "Vatican" },
    { "VE", "Venezuela" },
    { "VN", "Viet Nam" },
    { "YE", "Yemen" },
    { "ZA", "South Africa" },
    { "ZW", "Zimbabwe" }
  };

/* Given a string STRING, find the set of indices i such that TABLE[i].code is
   the given STRING.  It is a range [lo,hi-1].  */
typedef struct { size_t lo; size_t hi; } range_t;
static void
search (const struct table_entry *table, size_t table_size, const char *string,
        range_t *result)
{
  /* The table is sorted.  Perform a binary search.  */
  size_t hi = table_size;
  size_t lo = 0;
  while (lo < hi)
    {
      /* Invariant:
         for i < lo, strcmp (table[i].code, string) < 0,
         for i >= hi, strcmp (table[i].code, string) > 0.  */
      size_t mid = (hi + lo) >> 1; /* >= lo, < hi */
      int cmp = strcmp (table[mid].code, string);
      if (cmp < 0)
        lo = mid + 1;
      else if (cmp > 0)
        hi = mid;
      else
        {
          /* Found an i with
               strcmp (language_table[i].code, string) == 0.
             Find the entire interval of such i.  */
          {
            size_t i;

            for (i = mid; i > lo; )
              {
                i--;
                if (strcmp (table[i].code, string) < 0)
                  {
                    lo = i + 1;
                    break;
                  }
              }
          }
          {
            size_t i;

            for (i = mid + 1; i < hi; i++)
              {
                if (strcmp (table[i].code, string) > 0)
                  {
                    hi = i;
                    break;
                  }
              }
          }
          /* The set of i with
               strcmp (language_table[i].code, string) == 0
             is the interval [lo, hi-1].  */
          break;
        }
    }
  result->lo = lo;
  result->hi = hi;
}

/* Like setlocale, but accept also locale names in the form ll or ll_CC,
   where ll is an ISO 639 language code and CC is an ISO 3166 country code.  */
static char *
setlocale_unixlike (int category, const char *locale)
{
  char *result;
  char llCC_buf[64];
  char ll_buf[64];
  char CC_buf[64];

  /* The native Windows implementation of setlocale understands the special
     locale name "C", but not "POSIX".  Therefore map "POSIX" to "C".  */
  if (locale != NULL && strcmp (locale, "POSIX") == 0)
    locale = "C";

  /* First, try setlocale with the original argument unchanged.  */
  result = setlocale_mtsafe (category, locale);
  if (result != NULL)
    return result;

  /* Otherwise, assume the argument is in the form
       language[_territory][.codeset][@modifier]
     and try to map it using the tables.  */
  if (strlen (locale) < sizeof (llCC_buf))
    {
      /* Second try: Remove the codeset part.  */
      {
        const char *p = locale;
        char *q = llCC_buf;

        /* Copy the part before the dot.  */
        for (; *p != '\0' && *p != '.'; p++, q++)
          *q = *p;
        if (*p == '.')
          /* Skip the part up to the '@', if any.  */
          for (; *p != '\0' && *p != '@'; p++)
            ;
        /* Copy the part starting with '@', if any.  */
        for (; *p != '\0'; p++, q++)
          *q = *p;
        *q = '\0';
      }
      /* llCC_buf now contains
           language[_territory][@modifier]
       */
      if (strcmp (llCC_buf, locale) != 0)
        {
          result = setlocale (category, llCC_buf);
          if (result != NULL)
            return result;
        }
      /* Look it up in language_table.  */
      {
        range_t range;
        size_t i;

        search (language_table,
                sizeof (language_table) / sizeof (language_table[0]),
                llCC_buf,
                &range);

        for (i = range.lo; i < range.hi; i++)
          {
            /* Try the replacement in language_table[i].  */
            result = setlocale (category, language_table[i].english);
            if (result != NULL)
              return result;
          }
      }
      /* Split language[_territory][@modifier]
         into  ll_buf = language[@modifier]
         and   CC_buf = territory
       */
      {
        const char *underscore = strchr (llCC_buf, '_');
        if (underscore != NULL)
          {
            const char *territory_start = underscore + 1;
            const char *territory_end = strchr (territory_start, '@');
            if (territory_end == NULL)
              territory_end = territory_start + strlen (territory_start);

            memcpy (ll_buf, llCC_buf, underscore - llCC_buf);
            strcpy (ll_buf + (underscore - llCC_buf), territory_end);

            memcpy (CC_buf, territory_start, territory_end - territory_start);
            CC_buf[territory_end - territory_start] = '\0';

            {
              /* Look up ll_buf in language_table
                 and CC_buf in country_table.  */
              range_t language_range;

              search (language_table,
                      sizeof (language_table) / sizeof (language_table[0]),
                      ll_buf,
                      &language_range);
              if (language_range.lo < language_range.hi)
                {
                  range_t country_range;

                  search (country_table,
                          sizeof (country_table) / sizeof (country_table[0]),
                          CC_buf,
                          &country_range);
                  if (country_range.lo < country_range.hi)
                    {
                      size_t i;
                      size_t j;

                      for (i = language_range.lo; i < language_range.hi; i++)
                        for (j = country_range.lo; j < country_range.hi; j++)
                          {
                            /* Concatenate the replacements.  */
                            const char *part1 = language_table[i].english;
                            size_t part1_len = strlen (part1);
                            const char *part2 = country_table[j].english;
                            size_t part2_len = strlen (part2) + 1;
                            char buf[64+64];

                            if (!(part1_len + 1 + part2_len <= sizeof (buf)))
                              abort ();
                            memcpy (buf, part1, part1_len);
                            buf[part1_len] = '_';
                            memcpy (buf + part1_len + 1, part2, part2_len);

                            /* Try the concatenated replacements.  */
                            result = setlocale (category, buf);
                            if (result != NULL)
                              return result;
                          }
                    }

                  /* Try omitting the country entirely.  This may set a locale
                     corresponding to the wrong country, but is better than
                     failing entirely.  */
                  {
                    size_t i;

                    for (i = language_range.lo; i < language_range.hi; i++)
                      {
                        /* Try only the language replacement.  */
                        result =
                          setlocale (category, language_table[i].english);
                        if (result != NULL)
                          return result;
                      }
                  }
                }
            }
          }
      }
    }

  /* Failed.  */
  return NULL;
}

#  elif defined __ANDROID__

/* Like setlocale, but accept also the locale names "C" and "POSIX".  */
static char *
setlocale_unixlike (int category, const char *locale)
{
  char *result = setlocale_mtsafe (category, locale);
  if (result == NULL)
    switch (category)
      {
      case LC_CTYPE:
      case LC_NUMERIC:
      case LC_TIME:
      case LC_COLLATE:
      case LC_MONETARY:
      case LC_MESSAGES:
      case LC_ALL:
      case LC_PAPER:
      case LC_NAME:
      case LC_ADDRESS:
      case LC_TELEPHONE:
      case LC_MEASUREMENT:
        if (locale == NULL
            || strcmp (locale, "C") == 0 || strcmp (locale, "POSIX") == 0)
          result = (char *) "C";
        break;
      default:
        break;
      }
  return result;
}
#   define setlocale setlocale_unixlike

#  else
#   define setlocale_unixlike setlocale_mtsafe
#  endif

#  if LC_MESSAGES == 1729

/* The system does not store an LC_MESSAGES locale category.  Do it here.  */
static char lc_messages_name[64] = "C";

/* Like setlocale, but support also LC_MESSAGES.  */
static char *
setlocale_single (int category, const char *locale)
{
  if (category == LC_MESSAGES)
    {
      if (locale != NULL)
        {
          lc_messages_name[sizeof (lc_messages_name) - 1] = '\0';
          strncpy (lc_messages_name, locale, sizeof (lc_messages_name) - 1);
        }
      return lc_messages_name;
    }
  else
    return setlocale_unixlike (category, locale);
}

#  else
#   define setlocale_single setlocale_unixlike
#  endif

#  if defined __APPLE__ && defined __MACH__

/* Mapping from language to main territory where that language is spoken.  */
static char const locales_with_principal_territory[][6 + 1] =
  {
                /* Language     Main territory */
    "ace_ID",   /* Achinese     Indonesia */
    "af_ZA",    /* Afrikaans    South Africa */
    "ak_GH",    /* Akan         Ghana */
    "am_ET",    /* Amharic      Ethiopia */
    "an_ES",    /* Aragonese    Spain */
    "ang_GB",   /* Old English  Britain */
    "arn_CL",   /* Mapudungun   Chile */
    "as_IN",    /* Assamese     India */
    "ast_ES",   /* Asturian     Spain */
    "av_RU",    /* Avaric       Russia */
    "awa_IN",   /* Awadhi       India */
    "az_AZ",    /* Azerbaijani  Azerbaijan */
    "ban_ID",   /* Balinese     Indonesia */
    "be_BY",    /* Belarusian   Belarus */
    "bej_SD",   /* Beja         Sudan */
    "bem_ZM",   /* Bemba        Zambia */
    "bg_BG",    /* Bulgarian    Bulgaria */
    "bho_IN",   /* Bhojpuri     India */
    "bi_VU",    /* Bislama      Vanuatu */
    "bik_PH",   /* Bikol        Philippines */
    "bin_NG",   /* Bini         Nigeria */
    "bm_ML",    /* Bambara      Mali */
    "bn_IN",    /* Bengali      India */
    "bo_CN",    /* Tibetan      China */
    "br_FR",    /* Breton       France */
    "bs_BA",    /* Bosnian      Bosnia */
    "bug_ID",   /* Buginese     Indonesia */
    "ca_ES",    /* Catalan      Spain */
    "ce_RU",    /* Chechen      Russia */
    "ceb_PH",   /* Cebuano      Philippines */
    "co_FR",    /* Corsican     France */
    "cr_CA",    /* Cree         Canada */
    /* Don't put "crh_UZ" or "crh_UA" here.  That would be asking for fruitless
       political discussion.  */
    "cs_CZ",    /* Czech        Czech Republic */
    "csb_PL",   /* Kashubian    Poland */
    "cy_GB",    /* Welsh        Britain */
    "da_DK",    /* Danish       Denmark */
    "de_DE",    /* German       Germany */
    "din_SD",   /* Dinka        Sudan */
    "doi_IN",   /* Dogri        India */
    "dsb_DE",   /* Lower Sorbian        Germany */
    "dv_MV",    /* Divehi       Maldives */
    "dz_BT",    /* Dzongkha     Bhutan */
    "ee_GH",    /* Éwé          Ghana */
    "el_GR",    /* Greek        Greece */
    /* Don't put "en_GB" or "en_US" here.  That would be asking for fruitless
       political discussion.  */
    "es_ES",    /* Spanish      Spain */
    "et_EE",    /* Estonian     Estonia */
    "fa_IR",    /* Persian      Iran */
    "fi_FI",    /* Finnish      Finland */
    "fil_PH",   /* Filipino     Philippines */
    "fj_FJ",    /* Fijian       Fiji */
    "fo_FO",    /* Faroese      Faeroe Islands */
    "fon_BJ",   /* Fon          Benin */
    "fr_FR",    /* French       France */
    "fur_IT",   /* Friulian     Italy */
    "fy_NL",    /* Western Frisian      Netherlands */
    "ga_IE",    /* Irish        Ireland */
    "gd_GB",    /* Scottish Gaelic      Britain */
    "gon_IN",   /* Gondi        India */
    "gsw_CH",   /* Swiss German Switzerland */
    "gu_IN",    /* Gujarati     India */
    "he_IL",    /* Hebrew       Israel */
    "hi_IN",    /* Hindi        India */
    "hil_PH",   /* Hiligaynon   Philippines */
    "hr_HR",    /* Croatian     Croatia */
    "hsb_DE",   /* Upper Sorbian        Germany */
    "ht_HT",    /* Haitian      Haiti */
    "hu_HU",    /* Hungarian    Hungary */
    "hy_AM",    /* Armenian     Armenia */
    "id_ID",    /* Indonesian   Indonesia */
    "ig_NG",    /* Igbo         Nigeria */
    "ii_CN",    /* Sichuan Yi   China */
    "ilo_PH",   /* Iloko        Philippines */
    "is_IS",    /* Icelandic    Iceland */
    "it_IT",    /* Italian      Italy */
    "ja_JP",    /* Japanese     Japan */
    "jab_NG",   /* Hyam         Nigeria */
    "jv_ID",    /* Javanese     Indonesia */
    "ka_GE",    /* Georgian     Georgia */
    "kab_DZ",   /* Kabyle       Algeria */
    "kaj_NG",   /* Jju          Nigeria */
    "kam_KE",   /* Kamba        Kenya */
    "kmb_AO",   /* Kimbundu     Angola */
    "kcg_NG",   /* Tyap         Nigeria */
    "kdm_NG",   /* Kagoma       Nigeria */
    "kg_CD",    /* Kongo        Democratic Republic of Congo */
    "kk_KZ",    /* Kazakh       Kazakhstan */
    "kl_GL",    /* Kalaallisut  Greenland */
    "km_KH",    /* Central Khmer        Cambodia */
    "kn_IN",    /* Kannada      India */
    "ko_KR",    /* Korean       Korea (South) */
    "kok_IN",   /* Konkani      India */
    "kr_NG",    /* Kanuri       Nigeria */
    "kru_IN",   /* Kurukh       India */
    "ky_KG",    /* Kyrgyz       Kyrgyzstan */
    "lg_UG",    /* Ganda        Uganda */
    "li_BE",    /* Limburgish   Belgium */
    "lo_LA",    /* Laotian      Laos */
    "lt_LT",    /* Lithuanian   Lithuania */
    "lu_CD",    /* Luba-Katanga Democratic Republic of Congo */
    "lua_CD",   /* Luba-Lulua   Democratic Republic of Congo */
    "luo_KE",   /* Luo          Kenya */
    "lv_LV",    /* Latvian      Latvia */
    "mad_ID",   /* Madurese     Indonesia */
    "mag_IN",   /* Magahi       India */
    "mai_IN",   /* Maithili     India */
    "mak_ID",   /* Makasar      Indonesia */
    "man_ML",   /* Mandingo     Mali */
    "men_SL",   /* Mende        Sierra Leone */
    "mfe_MU",   /* Mauritian Creole     Mauritius */
    "mg_MG",    /* Malagasy     Madagascar */
    "mi_NZ",    /* Maori        New Zealand */
    "min_ID",   /* Minangkabau  Indonesia */
    "mk_MK",    /* Macedonian   North Macedonia */
    "ml_IN",    /* Malayalam    India */
    "mn_MN",    /* Mongolian    Mongolia */
    "mni_IN",   /* Manipuri     India */
    "mos_BF",   /* Mossi        Burkina Faso */
    "mr_IN",    /* Marathi      India */
    "ms_MY",    /* Malay        Malaysia */
    "mt_MT",    /* Maltese      Malta */
    "mwr_IN",   /* Marwari      India */
    "my_MM",    /* Burmese      Myanmar */
    "na_NR",    /* Nauru        Nauru */
    "nah_MX",   /* Nahuatl      Mexico */
    "nap_IT",   /* Neapolitan   Italy */
    "nb_NO",    /* Norwegian Bokmål    Norway */
    "nds_DE",   /* Low Saxon    Germany */
    "ne_NP",    /* Nepali       Nepal */
    "nl_NL",    /* Dutch        Netherlands */
    "nn_NO",    /* Norwegian Nynorsk    Norway */
    "no_NO",    /* Norwegian    Norway */
    "nr_ZA",    /* South Ndebele        South Africa */
    "nso_ZA",   /* Northern Sotho       South Africa */
    "ny_MW",    /* Chichewa     Malawi */
    "nym_TZ",   /* Nyamwezi     Tanzania */
    "nyn_UG",   /* Nyankole     Uganda */
    "oc_FR",    /* Occitan      France */
    "oj_CA",    /* Ojibwa       Canada */
    "or_IN",    /* Oriya        India */
    "pa_IN",    /* Punjabi      India */
    "pag_PH",   /* Pangasinan   Philippines */
    "pam_PH",   /* Pampanga     Philippines */
    "pap_AN",   /* Papiamento   Netherlands Antilles - this line can be removed in 2018 */
    "pbb_CO",   /* Páez         Colombia */
    "pl_PL",    /* Polish       Poland */
    "ps_AF",    /* Pashto       Afghanistan */
    "pt_PT",    /* Portuguese   Portugal */
    "raj_IN",   /* Rajasthani   India */
    "rm_CH",    /* Romansh      Switzerland */
    "rn_BI",    /* Kirundi      Burundi */
    "ro_RO",    /* Romanian     Romania */
    "ru_RU",    /* Russian      Russia */
    "rw_RW",    /* Kinyarwanda  Rwanda */
    "sa_IN",    /* Sanskrit     India */
    "sah_RU",   /* Yakut        Russia */
    "sas_ID",   /* Sasak        Indonesia */
    "sat_IN",   /* Santali      India */
    "sc_IT",    /* Sardinian    Italy */
    "scn_IT",   /* Sicilian     Italy */
    "sg_CF",    /* Sango        Central African Republic */
    "shn_MM",   /* Shan         Myanmar */
    "si_LK",    /* Sinhala      Sri Lanka */
    "sid_ET",   /* Sidamo       Ethiopia */
    "sk_SK",    /* Slovak       Slovakia */
    "sl_SI",    /* Slovenian    Slovenia */
    "sm_WS",    /* Samoan       Samoa */
    "smn_FI",   /* Inari Sami   Finland */
    "sms_FI",   /* Skolt Sami   Finland */
    "so_SO",    /* Somali       Somalia */
    "sq_AL",    /* Albanian     Albania */
    "sr_RS",    /* Serbian      Serbia */
    "srr_SN",   /* Serer        Senegal */
    "suk_TZ",   /* Sukuma       Tanzania */
    "sus_GN",   /* Susu         Guinea */
    "sv_SE",    /* Swedish      Sweden */
    "te_IN",    /* Telugu       India */
    "tem_SL",   /* Timne        Sierra Leone */
    "tet_ID",   /* Tetum        Indonesia */
    "tg_TJ",    /* Tajik        Tajikistan */
    "th_TH",    /* Thai         Thailand */
    "ti_ER",    /* Tigrinya     Eritrea */
    "tiv_NG",   /* Tiv          Nigeria */
    "tk_TM",    /* Turkmen      Turkmenistan */
    "tl_PH",    /* Tagalog      Philippines */
    "to_TO",    /* Tonga        Tonga */
    "tpi_PG",   /* Tok Pisin    Papua New Guinea */
    "tr_TR",    /* Turkish      Türkiye */
    "tum_MW",   /* Tumbuka      Malawi */
    "ug_CN",    /* Uighur       China */
    "uk_UA",    /* Ukrainian    Ukraine */
    "umb_AO",   /* Umbundu      Angola */
    "ur_PK",    /* Urdu         Pakistan */
    "uz_UZ",    /* Uzbek        Uzbekistan */
    "ve_ZA",    /* Venda        South Africa */
    "vi_VN",    /* Vietnamese   Vietnam */
    "wa_BE",    /* Walloon      Belgium */
    "wal_ET",   /* Walamo       Ethiopia */
    "war_PH",   /* Waray        Philippines */
    "wen_DE",   /* Sorbian      Germany */
    "yao_MW",   /* Yao          Malawi */
    "zap_MX"    /* Zapotec      Mexico */
  };

/* Compare just the language part of two locale names.  */
static int
langcmp (const char *locale1, const char *locale2)
{
  size_t locale1_len;
  size_t locale2_len;
  int cmp;

  {
    const char *locale1_end = strchr (locale1, '_');
    if (locale1_end != NULL)
      locale1_len = locale1_end - locale1;
    else
      locale1_len = strlen (locale1);
  }
  {
    const char *locale2_end = strchr (locale2, '_');
    if (locale2_end != NULL)
      locale2_len = locale2_end - locale2;
    else
      locale2_len = strlen (locale2);
  }

  if (locale1_len < locale2_len)
    {
      cmp = memcmp (locale1, locale2, locale1_len);
      if (cmp == 0)
        cmp = -1;
    }
  else
    {
      cmp = memcmp (locale1, locale2, locale2_len);
      if (locale1_len > locale2_len && cmp == 0)
        cmp = 1;
    }

  return cmp;
}

/* Given a locale name, return the main locale with the same language,
   or NULL if not found.
   For example: "fr_DE" -> "fr_FR".  */
static const char *
get_main_locale_with_same_language (const char *locale)
{
#   define table locales_with_principal_territory
  /* The table is sorted.  Perform a binary search.  */
  size_t hi = sizeof (table) / sizeof (table[0]);
  size_t lo = 0;
  while (lo < hi)
    {
      /* Invariant:
         for i < lo, langcmp (table[i], locale) < 0,
         for i >= hi, langcmp (table[i], locale) > 0.  */
      size_t mid = (hi + lo) >> 1; /* >= lo, < hi */
      int cmp = langcmp (table[mid], locale);
      if (cmp < 0)
        lo = mid + 1;
      else if (cmp > 0)
        hi = mid;
      else
        {
          /* Found an i with
               langcmp (language_table[i], locale) == 0.
             Verify that it is the only such i.  */
          if (mid > lo && langcmp (table[mid - 1], locale) >= 0)
            abort ();
          if (mid + 1 < hi && langcmp (table[mid + 1], locale) <= 0)
            abort ();
          return table[mid];
        }
    }
#   undef table
  return NULL;
}

/* Mapping from territory to main language that is spoken in that territory.  */
static char const locales_with_principal_language[][6 + 1] =
  {
    /* This is based on the set of existing locales in glibc, with duplicates
       removed, and on the Wikipedia pages named "Languages of <territory>".
       If in doubt, use the locale that exists in macOS.  For example, the only
       "*_IN" locale in macOS 10.13 is "hi_IN", so use that.  */
    /* A useful shell function for producing a line of this table is:
         func_line ()
         {
           # Usage: func_line ll_CC
           ll=`echo "$1" | sed -e 's|_.*||'`
           cc=`echo "$1" | sed -e 's|^.*_||'`
           llx=`sed -n -e "s|^${ll} ||p" < gettext-tools/doc/ISO_639`
           ccx=`expand gettext-tools/doc/ISO_3166 | sed -n -e "s|^${cc}  *||p"`
           echo "    \"$1\",    /$X* ${llx} ${ccx} *$X/"
         }
     */
              /* Main language  Territory */
    "ca_AD",    /* Catalan      Andorra */
    "ar_AE",    /* Arabic       United Arab Emirates */
    "ps_AF",    /* Pashto       Afghanistan */
    "en_AG",    /* English      Antigua and Barbuda */
    "sq_AL",    /* Albanian     Albania */
    "hy_AM",    /* Armenian     Armenia */
    "pap_AN",   /* Papiamento   Netherlands Antilles - this line can be removed in 2018 */
    "pt_AO",    /* Portuguese   Angola */
    "es_AR",    /* Spanish      Argentina */
    "de_AT",    /* German       Austria */
    "en_AU",    /* English      Australia */
    /* Aruba has two official languages: "nl_AW", "pap_AW".  */
    "az_AZ",    /* Azerbaijani  Azerbaijan */
    "bs_BA",    /* Bosnian      Bosnia */
    "bn_BD",    /* Bengali      Bangladesh */
    "nl_BE",    /* Dutch        Belgium */
    "fr_BF",    /* French       Burkina Faso */
    "bg_BG",    /* Bulgarian    Bulgaria */
    "ar_BH",    /* Arabic       Bahrain */
    "rn_BI",    /* Kirundi      Burundi */
    "fr_BJ",    /* French       Benin */
    "es_BO",    /* Spanish      Bolivia */
    "pt_BR",    /* Portuguese   Brazil */
    "dz_BT",    /* Dzongkha     Bhutan */
    "en_BW",    /* English      Botswana */
    "be_BY",    /* Belarusian   Belarus */
    "en_CA",    /* English      Canada */
    "fr_CD",    /* French       Democratic Republic of Congo */
    "sg_CF",    /* Sango        Central African Republic */
    "de_CH",    /* German       Switzerland */
    "es_CL",    /* Spanish      Chile */
    "zh_CN",    /* Chinese      China */
    "es_CO",    /* Spanish      Colombia */
    "es_CR",    /* Spanish      Costa Rica */
    "es_CU",    /* Spanish      Cuba */
    /* Curaçao has three official languages: "nl_CW", "pap_CW", "en_CW".  */
    "el_CY",    /* Greek        Cyprus */
    "cs_CZ",    /* Czech        Czech Republic */
    "de_DE",    /* German       Germany */
    /* Djibouti has two official languages: "ar_DJ" and "fr_DJ".  */
    "da_DK",    /* Danish       Denmark */
    "es_DO",    /* Spanish      Dominican Republic */
    "ar_DZ",    /* Arabic       Algeria */
    "es_EC",    /* Spanish      Ecuador */
    "et_EE",    /* Estonian     Estonia */
    "ar_EG",    /* Arabic       Egypt */
    "ti_ER",    /* Tigrinya     Eritrea */
    "es_ES",    /* Spanish      Spain */
    "am_ET",    /* Amharic      Ethiopia */
    "fi_FI",    /* Finnish      Finland */
    /* Fiji has three official languages: "en_FJ", "fj_FJ", "hif_FJ".  */
    "fo_FO",    /* Faroese      Faeroe Islands */
    "fr_FR",    /* French       France */
    "en_GB",    /* English      Britain */
    "ka_GE",    /* Georgian     Georgia */
    "en_GH",    /* English      Ghana */
    "kl_GL",    /* Kalaallisut  Greenland */
    "fr_GN",    /* French       Guinea */
    "el_GR",    /* Greek        Greece */
    "es_GT",    /* Spanish      Guatemala */
    "zh_HK",    /* Chinese      Hong Kong */
    "es_HN",    /* Spanish      Honduras */
    "hr_HR",    /* Croatian     Croatia */
    "ht_HT",    /* Haitian      Haiti */
    "hu_HU",    /* Hungarian    Hungary */
    "id_ID",    /* Indonesian   Indonesia */
    "en_IE",    /* English      Ireland */
    "he_IL",    /* Hebrew       Israel */
    "hi_IN",    /* Hindi        India */
    "ar_IQ",    /* Arabic       Iraq */
    "fa_IR",    /* Persian      Iran */
    "is_IS",    /* Icelandic    Iceland */
    "it_IT",    /* Italian      Italy */
    "ar_JO",    /* Arabic       Jordan */
    "ja_JP",    /* Japanese     Japan */
    "sw_KE",    /* Swahili      Kenya */
    "ky_KG",    /* Kyrgyz       Kyrgyzstan */
    "km_KH",    /* Central Khmer        Cambodia */
    "ko_KR",    /* Korean       Korea (South) */
    "ar_KW",    /* Arabic       Kuwait */
    "kk_KZ",    /* Kazakh       Kazakhstan */
    "lo_LA",    /* Laotian      Laos */
    "ar_LB",    /* Arabic       Lebanon */
    "de_LI",    /* German       Liechtenstein */
    "si_LK",    /* Sinhala      Sri Lanka */
    "lt_LT",    /* Lithuanian   Lithuania */
    /* Luxembourg has three official languages: "lb_LU", "fr_LU", "de_LU".  */
    "lv_LV",    /* Latvian      Latvia */
    "ar_LY",    /* Arabic       Libya */
    "ar_MA",    /* Arabic       Morocco */
    "sr_ME",    /* Serbian      Montenegro */
    "mg_MG",    /* Malagasy     Madagascar */
    "mk_MK",    /* Macedonian   North Macedonia */
    "fr_ML",    /* French       Mali */
    "my_MM",    /* Burmese      Myanmar */
    "mn_MN",    /* Mongolian    Mongolia */
    "mt_MT",    /* Maltese      Malta */
    "mfe_MU",   /* Mauritian Creole     Mauritius */
    "dv_MV",    /* Divehi       Maldives */
    "ny_MW",    /* Chichewa     Malawi */
    "es_MX",    /* Spanish      Mexico */
    "ms_MY",    /* Malay        Malaysia */
    "en_NG",    /* English      Nigeria */
    "es_NI",    /* Spanish      Nicaragua */
    "nl_NL",    /* Dutch        Netherlands */
    "no_NO",    /* Norwegian    Norway */
    "ne_NP",    /* Nepali       Nepal */
    "na_NR",    /* Nauru        Nauru */
    "niu_NU",   /* Niuean       Niue */
    "en_NZ",    /* English      New Zealand */
    "ar_OM",    /* Arabic       Oman */
    "es_PA",    /* Spanish      Panama */
    "es_PE",    /* Spanish      Peru */
    "tpi_PG",   /* Tok Pisin    Papua New Guinea */
    "fil_PH",   /* Filipino     Philippines */
    "pa_PK",    /* Punjabi      Pakistan */
    "pl_PL",    /* Polish       Poland */
    "es_PR",    /* Spanish      Puerto Rico */
    "pt_PT",    /* Portuguese   Portugal */
    "es_PY",    /* Spanish      Paraguay */
    "ar_QA",    /* Arabic       Qatar */
    "ro_RO",    /* Romanian     Romania */
    "sr_RS",    /* Serbian      Serbia */
    "ru_RU",    /* Russian      Russia */
    "rw_RW",    /* Kinyarwanda  Rwanda */
    "ar_SA",    /* Arabic       Saudi Arabia */
    "en_SC",    /* English      Seychelles */
    "ar_SD",    /* Arabic       Sudan */
    "sv_SE",    /* Swedish      Sweden */
    "en_SG",    /* English      Singapore */
    "sl_SI",    /* Slovenian    Slovenia */
    "sk_SK",    /* Slovak       Slovakia */
    "en_SL",    /* English      Sierra Leone */
    "fr_SN",    /* French       Senegal */
    "so_SO",    /* Somali       Somalia */
    "ar_SS",    /* Arabic       South Sudan */
    "es_SV",    /* Spanish      El Salvador */
    "ar_SY",    /* Arabic       Syria */
    "th_TH",    /* Thai         Thailand */
    "tg_TJ",    /* Tajik        Tajikistan */
    "tk_TM",    /* Turkmen      Turkmenistan */
    "ar_TN",    /* Arabic       Tunisia */
    "to_TO",    /* Tonga        Tonga */
    "tr_TR",    /* Turkish      Türkiye */
    "zh_TW",    /* Chinese      Taiwan */
    "sw_TZ",    /* Swahili      Tanzania */
    "uk_UA",    /* Ukrainian    Ukraine */
    "lg_UG",    /* Ganda        Uganda */
    "en_US",    /* English      United States of America */
    "es_UY",    /* Spanish      Uruguay */
    "uz_UZ",    /* Uzbek        Uzbekistan */
    "es_VE",    /* Spanish      Venezuela */
    "vi_VN",    /* Vietnamese   Vietnam */
    "bi_VU",    /* Bislama      Vanuatu */
    "sm_WS",    /* Samoan       Samoa */
    "ar_YE",    /* Arabic       Yemen */
    "en_ZA",    /* English      South Africa */
    "en_ZM",    /* English      Zambia */
    "en_ZW"     /* English      Zimbabwe */
  };

/* Compare just the territory part of two locale names.  */
static int
terrcmp (const char *locale1, const char *locale2)
{
  const char *territory1 = strrchr (locale1, '_') + 1;
  const char *territory2 = strrchr (locale2, '_') + 1;

  return strcmp (territory1, territory2);
}

/* Given a locale name, return the locale corresponding to the main language
   with the same territory, or NULL if not found.
   For example: "fr_DE" -> "de_DE".  */
static const char *
get_main_locale_with_same_territory (const char *locale)
{
  if (strrchr (locale, '_') != NULL)
    {
#   define table locales_with_principal_language
      /* The table is sorted.  Perform a binary search.  */
      size_t hi = sizeof (table) / sizeof (table[0]);
      size_t lo = 0;
      while (lo < hi)
        {
          /* Invariant:
             for i < lo, terrcmp (table[i], locale) < 0,
             for i >= hi, terrcmp (table[i], locale) > 0.  */
          size_t mid = (hi + lo) >> 1; /* >= lo, < hi */
          int cmp = terrcmp (table[mid], locale);
          if (cmp < 0)
            lo = mid + 1;
          else if (cmp > 0)
            hi = mid;
          else
            {
              /* Found an i with
                   terrcmp (language_table[i], locale) == 0.
                 Verify that it is the only such i.  */
              if (mid > lo && terrcmp (table[mid - 1], locale) >= 0)
                abort ();
              if (mid + 1 < hi && terrcmp (table[mid + 1], locale) <= 0)
                abort ();
              return table[mid];
            }
        }
#   undef table
    }
  return NULL;
}

#  endif

char *
setlocale_improved (int category, const char *locale)
{
  if (locale != NULL && locale[0] == '\0')
    {
      /* A request to the set the current locale to the default locale.  */
      if (category == LC_ALL)
        {
          /* Set LC_CTYPE first.  Then the other categories.  */
          static int const categories[] =
            {
              LC_CTYPE,
              LC_NUMERIC,
              LC_TIME,
              LC_COLLATE,
              LC_MONETARY,
              LC_MESSAGES
            };
          char *saved_locale;
          const char *base_name;
          unsigned int i;

          /* Back up the old locale, in case one of the steps fails.  */
          saved_locale = setlocale (LC_ALL, NULL);
          if (saved_locale == NULL)
            return NULL;
          saved_locale = strdup (saved_locale);
          if (saved_locale == NULL)
            return NULL;

          /* Set LC_CTYPE category.  Set all other categories (except possibly
             LC_MESSAGES) to the same value in the same call; this is likely to
             save calls.  */
          base_name =
            gl_locale_name_environ (LC_CTYPE, category_to_name (LC_CTYPE));
          if (base_name == NULL)
            base_name = gl_locale_name_default ();

          if (setlocale_unixlike (LC_ALL, base_name) != NULL)
            {
              /* LC_CTYPE category already set.  */
              i = 1;
            }
          else
            {
              /* On Mac OS X, "UTF-8" is a valid locale name for LC_CTYPE but
                 not for LC_ALL.  Therefore this call may fail.  So, try
                 another base_name.  */
              base_name = "C";
              if (setlocale_unixlike (LC_ALL, base_name) == NULL)
                goto fail;
              i = 0;
            }
#  if defined _WIN32 && ! defined __CYGWIN__
          /* On native Windows, setlocale(LC_ALL,...) may succeed but set the
             LC_CTYPE category to an invalid value ("C") when it does not
             support the specified encoding.  Report a failure instead.  */
          if (strchr (base_name, '.') != NULL
              && strcmp (setlocale (LC_CTYPE, NULL), "C") == 0)
            goto fail;
#  endif

          for (; i < sizeof (categories) / sizeof (categories[0]); i++)
            {
              int cat = categories[i];
              const char *name;

              name = gl_locale_name_environ (cat, category_to_name (cat));
              if (name == NULL)
                name = gl_locale_name_default ();

              /* If name is the same as base_name, it has already been set
                 through the setlocale call before the loop.  */
              if (strcmp (name, base_name) != 0
#  if LC_MESSAGES == 1729
                  || cat == LC_MESSAGES
#  endif
                 )
                if (setlocale_single (cat, name) == NULL)
#  if defined __APPLE__ && defined __MACH__
                  {
                    /* On Mac OS X 10.13, some locales can be set through
                       System Preferences > Language & Region, that are not
                       supported by libc.  The system's setlocale() falls
                       back to "C" for these locale categories.  We can do
                       better, by trying an existing locale with the same
                       language or an existing locale with the same territory.
                       If we can't, print a warning, to limit user
                       expectations.  */
                    int warn = 0;

                    if (cat == LC_CTYPE)
                      warn = (setlocale_single (cat, "UTF-8") == NULL);
                    else if (cat == LC_MESSAGES)
                      {
#   if HAVE_CFLOCALECOPYPREFERREDLANGUAGES || HAVE_CFPREFERENCESCOPYAPPVALUE /* MacOS X 10.4 or newer */
                        /* Take the primary language preference.  */
#    if HAVE_CFLOCALECOPYPREFERREDLANGUAGES /* MacOS X 10.5 or newer */
                        CFArrayRef prefArray = CFLocaleCopyPreferredLanguages ();
#    elif HAVE_CFPREFERENCESCOPYAPPVALUE /* MacOS X 10.4 or newer */
                        CFTypeRef preferences =
                          CFPreferencesCopyAppValue (CFSTR ("AppleLanguages"),
                                                     kCFPreferencesCurrentApplication);
                        if (preferences != NULL
                            && CFGetTypeID (preferences) == CFArrayGetTypeID ())
                          {
                            CFArrayRef prefArray = (CFArrayRef)preferences;
#    endif
                            int n = CFArrayGetCount (prefArray);
                            if (n > 0)
                              {
                                char buf[256];
                                CFTypeRef element = CFArrayGetValueAtIndex (prefArray, 0);
                                if (element != NULL
                                    && CFGetTypeID (element) == CFStringGetTypeID ()
                                    && CFStringGetCString ((CFStringRef)element,
                                                           buf, sizeof (buf),
                                                           kCFStringEncodingASCII))
                                  {
                                    /* Remove the country.
                                       E.g. "zh-Hans-DE" -> "zh-Hans".  */
                                    char *last_minus = strrchr (buf, '-');
                                    if (last_minus != NULL)
                                      *last_minus = '\0';

                                    /* Convert to Unix locale name.
                                       E.g. "zh-Hans" -> "zh_CN".  */
                                    gl_locale_name_canonicalize (buf);

                                    /* Try setlocale with this value.  */
                                    if (setlocale_single (cat, buf) == NULL)
                                      {
                                        const char *last_try =
                                          get_main_locale_with_same_language (buf);

                                        if (last_try == NULL
                                            || setlocale_single (cat, last_try) == NULL)
                                          warn = 1;
                                      }
                                  }
                              }
#    if HAVE_CFLOCALECOPYPREFERREDLANGUAGES /* MacOS X 10.5 or newer */
                        CFRelease (prefArray);
#    elif HAVE_CFPREFERENCESCOPYAPPVALUE /* MacOS X 10.4 or newer */
                          }
#    endif
#   else
                        const char *last_try =
                          get_main_locale_with_same_language (name);

                        if (last_try == NULL
                            || setlocale_single (cat, last_try) == NULL)
                          warn = 1;
#   endif
                      }
                    else
                      {
                        /* For LC_NUMERIC, the application should use the locale
                           properties kCFLocaleDecimalSeparator,
                           kCFLocaleGroupingSeparator.
                           For LC_TIME, the application should use the locale
                           property kCFLocaleCalendarIdentifier.
                           For LC_COLLATE, the application should use the locale
                           properties kCFLocaleCollationIdentifier,
                           kCFLocaleCollatorIdentifier.
                           For LC_MONETARY, the application should use the locale
                           properties kCFLocaleCurrencySymbol,
                           kCFLocaleCurrencyCode.
                           But since most applications don't have macOS specific
                           code like this, try an existing locale with the same
                           territory.  */
                        const char *last_try =
                          get_main_locale_with_same_territory (name);

                        if (last_try == NULL
                            || setlocale_single (cat, last_try) == NULL)
                          warn = 1;
                      }

                    if (warn)
                      {
                        /* Warn only if the environment variable
                           SETLOCALE_VERBOSE is set.  Otherwise these warnings
                           are just annoyances, since normal users won't invoke
                           'localedef'.  */
                        const char *verbose = getenv ("SETLOCALE_VERBOSE");
                        if (verbose != NULL && verbose[0] != '\0')
                          fprintf (stderr,
                                   "Warning: Failed to set locale category %s to %s.\n",
                                   category_to_name (cat), name);
                      }
                  }
#  else
                  goto fail;
#  endif
            }

          /* All steps were successful.  */
          free (saved_locale);
          return setlocale (LC_ALL, NULL);

        fail:
          if (saved_locale[0] != '\0') /* don't risk an endless recursion */
            setlocale (LC_ALL, saved_locale);
          free (saved_locale);
          return NULL;
        }
      else
        {
          const char *name =
            gl_locale_name_environ (category, category_to_name (category));
          if (name == NULL)
            name = gl_locale_name_default ();

          return setlocale_single (category, name);
        }
    }
  else
    {
#  if defined _WIN32 && ! defined __CYGWIN__
      if (category == LC_ALL && locale != NULL && strchr (locale, '.') != NULL)
        {
          char *saved_locale;

          /* Back up the old locale.  */
          saved_locale = setlocale (LC_ALL, NULL);
          if (saved_locale == NULL)
            return NULL;
          saved_locale = strdup (saved_locale);
          if (saved_locale == NULL)
            return NULL;

          if (setlocale_unixlike (LC_ALL, locale) == NULL)
            {
              free (saved_locale);
              return NULL;
            }

          /* On native Windows, setlocale(LC_ALL,...) may succeed but set the
             LC_CTYPE category to an invalid value ("C") when it does not
             support the specified encoding.  Report a failure instead.  */
          if (strcmp (setlocale (LC_CTYPE, NULL), "C") == 0)
            {
              if (saved_locale[0] != '\0') /* don't risk an endless recursion */
                setlocale (LC_ALL, saved_locale);
              free (saved_locale);
              return NULL;
            }

          /* It was really successful.  */
          free (saved_locale);
          return setlocale (LC_ALL, NULL);
        }
      else
#  endif
        return setlocale_single (category, locale);
    }
}

# endif /* NEED_SETLOCALE_IMPROVED */

#endif