summaryrefslogtreecommitdiffstats
path: root/tdecore/tdelocale.cpp
blob: 4402dd183b695d95508c8651532f752624515b86 (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
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
// -*- c-basic-offset: 2 -*-
/* This file is part of the KDE libraries
   Copyright (c) 1997,2001 Stephan Kulow <coolo@kde.org>
   Copyright (c) 1999 Preston Brown <pbrown@kde.org>
   Copyright (c) 1999-2002 Hans Petter Bieker <bieker@kde.org>
   Copyright (c) 2002 Lukas Tinkl <lukas@kde.org>

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

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include <config.h>

#include <stdlib.h> // getenv

#include <tqtextcodec.h>
#include <tqfile.h>
#include <tqprinter.h>
#include <tqdatetime.h>
#include <tqfileinfo.h>
#include <tqregexp.h>

#include "kcatalogue.h"
#include "tdeglobal.h"
#include "kstandarddirs.h"
#include "ksimpleconfig.h"
#include "kinstance.h"
#include "tdeconfig.h"
#include "kdebug.h"
#include "kcalendarsystem.h"
#include "kcalendarsystemfactory.h"
#include "tdelocale.h"

#ifdef Q_WS_WIN
#include <windows.h>
#endif

static const char * const SYSTEM_MESSAGES = "tdelibs";

static const char *maincatalogue = 0;

class TDELocalePrivate
{
public:
  int weekStartDay;
  bool nounDeclension;
  bool dateMonthNamePossessive;
  TQStringList languageList;
  TQStringList catalogNames; // list of all catalogs (regardless of language)
  TQValueList<KCatalogue> catalogues; // list of all loaded catalogs, contains one instance per catalog name and language
  TQString encoding;
  TQTextCodec * codecForEncoding;
  TDEConfig * config;
  bool formatInited;
  int /*TQPrinter::PageSize*/ pageSize;
  TDELocale::MeasureSystem measureSystem;
  TQStringList langTwoAlpha;
  TDEConfig *languages;

  TQString calendarType;
  KCalendarSystem * calendar;
  bool utf8FileEncoding;
  TQString appName;
#ifdef Q_WS_WIN
  char win32SystemEncoding[3+7]; //"cp " + lang ID
#endif
  bool useMainCatalogue;
};

static TDELocale *this_klocale = 0;

TDELocale::TDELocale( const TQString & catalog, TDEConfig * config )
{
  d = new TDELocalePrivate;
  d->config = config;
  d->languages = 0;
  d->calendar = 0;
  d->formatInited = false;

  initEncoding(0);
  initFileNameEncoding(0);

  TDEConfig *cfg = d->config;
  this_klocale = this;
  if (!cfg) cfg = TDEGlobal::instance()->config();
  this_klocale = 0;
  Q_ASSERT( cfg );

  d->appName = catalog;
  initLanguageList( cfg, config == 0);
  initMainCatalogues(catalog);
}

TQString TDELocale::_initLanguage(TDEConfigBase *config)
{
  if (this_klocale)
  {
     // ### HPB Why this cast??
     this_klocale->initLanguageList((TDEConfig *) config, true);
     // todo: adapt current catalog list: remove unused languages, insert main catalogs, if not already found
     return this_klocale->language();
  }
  return TQString::null;
}

void TDELocale::initMainCatalogues(const TQString & catalog)
{
  // Use the first non-null string.
  TQString mainCatalogue = catalog;

  // don't use main catalogue if we're looking up .desktop translations
  if (mainCatalogue.contains("desktop") == 0 || mainCatalogue.contains("kdesktop") == 1) {
    if (maincatalogue) {
      mainCatalogue = TQString::fromLatin1(maincatalogue);
    }
  }

  if (mainCatalogue.isEmpty()) {
    kdDebug(173) << "TDELocale instance created called without valid "
                 << "catalog! Give an argument or call setMainCatalogue "
                 << "before init" << endl;
  }
  else {
    // do not use insertCatalogue here, that would already trigger updateCatalogs
    d->catalogNames.append( mainCatalogue );   // application catalog
    if (mainCatalogue.contains("desktop") == 0 || mainCatalogue.contains("kdesktop") == 1) { //don't bother if we're looking up desktop translations
      d->catalogNames.append( SYSTEM_MESSAGES ); // always include tdelibs.mo
      d->catalogNames.append( "kio" );            // always include kio.mo
      d->catalogNames.append( "xdg-user-dirs" );
    }
    updateCatalogues(); // evaluate this for all languages
  }
}

void TDELocale::initLanguageList(TDEConfig * config, bool useEnv)
{
  TDEConfigGroupSaver saver(config, "Locale");

  m_country = config->readEntry( "Country" );
  if ( m_country.isEmpty() )
    m_country = defaultCountry();

  // Reset the list and add the new languages
  TQStringList languageList;
  if ( useEnv )
    languageList += TQStringList::split
      (':', TQFile::decodeName( ::getenv("TDE_LANG") ));

  languageList += config->readListEntry("Language", ':');

  // same order as setlocale use
  if ( useEnv )
    {
      // HPB: Only run splitLocale on the environment variables..
      TQStringList langs;

      langs << TQFile::decodeName( ::getenv("LC_ALL") );
      langs << TQFile::decodeName( ::getenv("LC_MESSAGES") );
      langs << TQFile::decodeName( ::getenv("LANG") );

      for ( TQStringList::Iterator it = langs.begin();
	    it != langs.end();
	    ++it )
	{
	  TQString ln, ct, chrset;
	  splitLocale(*it, ln, ct, chrset);

	  if (!ct.isEmpty()) {
	    langs.insert(it, ln + '_' + ct);
	    if (!chrset.isEmpty())
	      langs.insert(it, ln + '_' + ct + '.' + chrset);
	  }

          langs.insert(it, ln);
	}

      languageList += langs;
    }

  // now we have a language list -- let's use the first OK language
  setLanguage( languageList );
}

void TDELocale::initPluralTypes()
{
  for ( TQValueList<KCatalogue>::Iterator it = d->catalogues.begin();
    it != d->catalogues.end();
    ++it )
  {
    TQString language = (*it).language();
    int pt = pluralType( language );
    (*it).setPluralType( pt );
  }
}


int TDELocale::pluralType( const TQString & language )
{
  for ( TQValueList<KCatalogue>::ConstIterator it = d->catalogues.begin();
    it != d->catalogues.end();
    ++it )
  {
    if ( ((*it).name() == SYSTEM_MESSAGES ) && ((*it).language() == language )) {
      return pluralType( *it );
    }
  }
  // tdelibs.mo does not seem to exist for this language
  return -1;
}

int TDELocale::pluralType( const KCatalogue& catalog )
{
    const char* pluralFormString =
    I18N_NOOP("_: Dear translator, please do not translate this string "
      "in any form, but pick the _right_ value out of "
      "NoPlural/TwoForms/French... If not sure what to do mail "
      "thd@kde.org and coolo@kde.org, they will tell you. "
      "Better leave that out if unsure, the programs will "
      "crash!!\nDefinition of PluralForm - to be set by the "
      "translator of tdelibs.po");
    TQString pf (catalog.translate( pluralFormString));
    if ( pf.isEmpty() ) {
      return -1;
    }
	else if ( pf == "NoPlural" )
      return 0;
    else if ( pf == "TwoForms" )
      return 1;
    else if ( pf == "French" )
      return 2;
    else if ( pf == "OneTwoRest" )
      return 3;
    else if ( pf == "Russian" )
      return 4;
    else if ( pf == "Polish" )
      return 5;
    else if ( pf == "Slovenian" )
      return 6;
    else if ( pf == "Lithuanian" )
      return 7;
    else if ( pf == "Czech" )
      return 8;
    else if ( pf == "Slovak" )
      return 9;
    else if ( pf == "Maltese" )
      return 10;
    else if ( pf == "Arabic" )
      return 11;
    else if ( pf == "Balcan" )
      return 12;
    else if ( pf == "Macedonian" )
      return 13;
    else if ( pf == "Gaeilge" )
        return 14;
    else {
      kdWarning(173) << "Definition of PluralForm is none of "
		       << "NoPlural/"
		       << "TwoForms/"
		       << "French/"
		       << "OneTwoRest/"
		       << "Russian/"
		       << "Polish/"
		       << "Slovenian/"
		       << "Lithuanian/"
		       << "Czech/"
		       << "Slovak/"
		       << "Arabic/"
		       << "Balcan/"
               << "Macedonian/"
               << "Gaeilge/"
		       << "Maltese: " << pf << endl;
      exit(1);
    }
}

void TDELocale::doFormatInit() const
{
  if ( d->formatInited ) return;

  TDELocale * that = const_cast<TDELocale *>(this);
  that->initFormat();

  d->formatInited = true;
}

void TDELocale::initFormat()
{
  TDEConfig *config = d->config;
  if (!config) config = TDEGlobal::instance()->config();
  Q_ASSERT( config );

  kdDebug(173) << "TDELocale::initFormat" << endl;

  // make sure the config files are read using the correct locale
  // ### Why not add a TDEConfigBase::setLocale( const TDELocale * )?
  // ### Then we could remove this hack
  TDELocale *lsave = TDEGlobal::_locale;
  TDEGlobal::_locale = this;

  TDEConfigGroupSaver saver(config, "Locale");

  KSimpleConfig entry(locate("locale",
                             TQString::fromLatin1("l10n/%1/entry.desktop")
                             .arg(m_country)), true);
  entry.setGroup("KCM Locale");

  // Numeric
#define readConfigEntry(key, default, save) \
  save = entry.readEntry(key, TQString::fromLatin1(default)); \
  save = config->readEntry(key, save);

#define readConfigNumEntry(key, default, save, type) \
  save = (type)entry.readNumEntry(key, default); \
  save = (type)config->readNumEntry(key, save);

#define readConfigBoolEntry(key, default, save) \
  save = entry.readBoolEntry(key, default); \
  save = config->readBoolEntry(key, save);

  readConfigEntry("DecimalSymbol", ".", m_decimalSymbol);
  readConfigEntry("ThousandsSeparator", ",", m_thousandsSeparator);
  m_thousandsSeparator.replace( TQString::fromLatin1("$0"), TQString() );
  //kdDebug(173) << "m_thousandsSeparator=" << m_thousandsSeparator << endl;

  readConfigEntry("PositiveSign", "", m_positiveSign);
  readConfigEntry("NegativeSign", "-", m_negativeSign);

  // Monetary
  readConfigEntry("CurrencySymbol", "$", m_currencySymbol);
  readConfigEntry("MonetaryDecimalSymbol", ".", m_monetaryDecimalSymbol);
  readConfigEntry("MonetaryThousandsSeparator", ",",
		  m_monetaryThousandsSeparator);
  m_monetaryThousandsSeparator.replace(TQString::fromLatin1("$0"), TQString());

  readConfigNumEntry("FracDigits", 2, m_fracDigits, int);
  readConfigBoolEntry("PositivePrefixCurrencySymbol", true,
		      m_positivePrefixCurrencySymbol);
  readConfigBoolEntry("NegativePrefixCurrencySymbol", true,
		      m_negativePrefixCurrencySymbol);
  readConfigNumEntry("PositiveMonetarySignPosition", (int)BeforeQuantityMoney,
		     m_positiveMonetarySignPosition, SignPosition);
  readConfigNumEntry("NegativeMonetarySignPosition", (int)ParensAround,
		     m_negativeMonetarySignPosition, SignPosition);


  // Date and time
  readConfigEntry("TimeFormat", "%H:%M:%S", m_timeFormat);
  readConfigEntry("DateFormat", "%A %d %B %Y", m_dateFormat);
  readConfigEntry("DateFormatShort", "%Y-%m-%d", m_dateFormatShort);
  readConfigNumEntry("WeekStartDay", 1, d->weekStartDay, int);

  // other
  readConfigNumEntry("PageSize", (int)TQPrinter::A4, d->pageSize, int);
  readConfigNumEntry("MeasureSystem", (int)Metric, d->measureSystem,
		     MeasureSystem);
  readConfigEntry("CalendarSystem", "gregorian", d->calendarType);
  delete d->calendar;
  d->calendar = 0; // ### HPB Is this the correct place?

  //Grammatical
  //Precedence here is l10n / i18n / config file
  KSimpleConfig language(locate("locale",
			        TQString::fromLatin1("%1/entry.desktop")
                                .arg(m_language)), true);
  language.setGroup("KCM Locale");
#define read3ConfigBoolEntry(key, default, save) \
  save = entry.readBoolEntry(key, default); \
  save = language.readBoolEntry(key, save); \
  save = config->readBoolEntry(key, save);

  read3ConfigBoolEntry("NounDeclension", false, d->nounDeclension);
  read3ConfigBoolEntry("DateMonthNamePossessive", false,
		       d->dateMonthNamePossessive);

  // end of hack
  TDEGlobal::_locale = lsave;
}

bool TDELocale::setCountry(const TQString & country)
{
  // Check if the file exists too??
  if ( country.isEmpty() )
    return false;

  m_country = country;

  d->formatInited = false;

  return true;
}

TQString TDELocale::catalogueFileName(const TQString & language,
				   const KCatalogue & catalog)
{
  TQString path = TQString::fromLatin1("%1/LC_MESSAGES/%2.mo")
    .arg( language )
    .arg( catalog.name() );

  TQString fileName = locate( "locale", path );
  if (fileName.isEmpty())
    fileName = locate( "locale-bundle", path );

  return fileName;
}

bool TDELocale::setLanguage(const TQString & language)
{
  if ( d->languageList.contains( language ) ) {
 	 d->languageList.remove( language );
  }
  d->languageList.prepend( language ); // let us consider this language to be the most important one

  m_language = language; // remember main language for shortcut evaluation

  // important when called from the outside and harmless when called before populating the
  // catalog name list
  updateCatalogues();

  d->formatInited = false;

  return true; // Maybe the mo-files for this language are empty, but in principle we can speak all languages
}

bool TDELocale::setLanguage(const TQStringList & languages)
{
  TQStringList languageList( languages );
  // This list might contain
  // 1) some empty strings that we have to eliminate
  // 2) duplicate entries like in de:fr:de, where we have to keep the first occurrance of a language in order
  //    to preserve the order of precenence of the user => iterate backwards
  // 3) languages into which the application is not translated. For those languages we should not even load tdelibs.mo or kio.po.
  //    these langugage have to be dropped. Otherwise we get strange side effects, e.g. with Hebrew:
  //    the right/left switch for languages that write from
  //    right to left (like Hebrew or Arabic) is set in tdelibs.mo. If you only have tdelibs.mo
  //    but nothing from appname.mo, you get a mostly English app with layout from right to left.
  //    That was considered to be a bug by the Hebrew translators.
  for( TQStringList::Iterator it = languageList.fromLast();
    it != languageList.begin(); --it )
  {
    // kdDebug() << "checking " << (*it) << endl;
    bool bIsTranslated = isApplicationTranslatedInto( *it );
    if ( languageList.contains(*it) > 1 || (*it).isEmpty() || (!bIsTranslated) ) {
      // kdDebug() << "removing " << (*it) << endl;
      it = languageList.remove( it );
    }
  }
  // now this has left the first element of the list unchecked.
  // The question why this is the case is left as an exercise for the reader...
  // Besides the list might have been empty all the way, so check that too.
  if ( languageList.begin() != languageList.end() ) {
     TQStringList::Iterator it = languageList.begin(); // now pointing to the first element
     // kdDebug() << "checking " << (*it) << endl;
     if( (*it).isEmpty() || !(isApplicationTranslatedInto( *it )) ) {
        // kdDebug() << "removing " << (*it) << endl;
     	languageList.remove( it ); // that's what the iterator was for...
     }
  }

  if ( languageList.isEmpty() ) {
	// user picked no language, so we assume he/she speaks English.
	languageList.append( defaultLanguage() );
  }
  m_language = languageList.first(); // keep this for shortcut evaluations

  d->languageList = languageList; // keep this new list of languages to use
  d->langTwoAlpha.clear(); // Flush cache

  // important when called from the outside and harmless when called before populating the
  // catalog name list
  updateCatalogues();

  return true; // we found something. Maybe it's only English, but we found something
}

bool TDELocale::isApplicationTranslatedInto( const TQString & language)
{
  if ( language.isEmpty() ) {
    return false;
  }

  if ( language == defaultLanguage() ) {
    // en_us is always "installed"
    return true;
  }

  TQString appName = d->appName;
  if (maincatalogue) {
    appName = TQString::fromLatin1(maincatalogue);
  }
  // sorry, catalogueFileName requires catalog object,k which we do not have here
  // path finding was supposed to be moved completely to KCatalogue. The interface cannot
  // be changed that far during deep freeze. So in order to fix the bug now, we have
  // duplicated code for file path evaluation. Cleanup will follow later. We could have e.g.
  // a static method in KCataloge that can translate between these file names.
  // a stat
  TQString sFileName = TQString::fromLatin1("%1/LC_MESSAGES/%2.mo")
    .arg( language )
    .arg( appName );
  // kdDebug() << "isApplicationTranslatedInto: filename " << sFileName << endl;

  TQString sAbsFileName = locate( "locale", sFileName );
  if (sAbsFileName.isEmpty())
    sAbsFileName = locate( "locale-bundle", sFileName );

  // kdDebug() << "isApplicationTranslatedInto: absname " << sAbsFileName << endl;
  return ! sAbsFileName.isEmpty();
}

void TDELocale::splitLocale(const TQString & aStr,
			  TQString & language,
			  TQString & country,
			  TQString & chrset)
{
  TQString str = aStr;

  // just in case, there is another language appended
  int f = str.find(':');
  if (f >= 0)
    str.truncate(f);

  country = TQString::null;
  chrset = TQString::null;
  language = TQString::null;

  f = str.find('.');
  if (f >= 0)
    {
      chrset = str.mid(f + 1);
      str.truncate(f);
    }

  f = str.find('_');
  if (f >= 0)
    {
      country = str.mid(f + 1);
      str.truncate(f);
    }

  language = str;
}

TQString TDELocale::language() const
{
  return m_language;
}

TQString TDELocale::country() const
{
  return m_country;
}

TQString TDELocale::monthName(int i, bool shortName) const
{
  if ( shortName )
    switch ( i )
      {
      case 1:   return translate("January", "Jan");
      case 2:   return translate("February", "Feb");
      case 3:   return translate("March", "Mar");
      case 4:   return translate("April", "Apr");
      case 5:   return translate("May short", "May");
      case 6:   return translate("June", "Jun");
      case 7:   return translate("July", "Jul");
      case 8:   return translate("August", "Aug");
      case 9:   return translate("September", "Sep");
      case 10:  return translate("October", "Oct");
      case 11:  return translate("November", "Nov");
      case 12:  return translate("December", "Dec");
      }
  else
    switch (i)
      {
      case 1:   return translate("January");
      case 2:   return translate("February");
      case 3:   return translate("March");
      case 4:   return translate("April");
      case 5:   return translate("May long", "May");
      case 6:   return translate("June");
      case 7:   return translate("July");
      case 8:   return translate("August");
      case 9:   return translate("September");
      case 10:  return translate("October");
      case 11:  return translate("November");
      case 12:  return translate("December");
      }

  return TQString::null;
}

TQString TDELocale::monthNamePossessive(int i, bool shortName) const
{
  if ( shortName )
    switch ( i )
      {
      case 1:   return translate("of January", "of Jan");
      case 2:   return translate("of February", "of Feb");
      case 3:   return translate("of March", "of Mar");
      case 4:   return translate("of April", "of Apr");
      case 5:   return translate("of May short", "of May");
      case 6:   return translate("of June", "of Jun");
      case 7:   return translate("of July", "of Jul");
      case 8:   return translate("of August", "of Aug");
      case 9:   return translate("of September", "of Sep");
      case 10:  return translate("of October", "of Oct");
      case 11:  return translate("of November", "of Nov");
      case 12:  return translate("of December", "of Dec");
      }
  else
    switch (i)
      {
      case 1:   return translate("of January");
      case 2:   return translate("of February");
      case 3:   return translate("of March");
      case 4:   return translate("of April");
      case 5:   return translate("of May long", "of May");
      case 6:   return translate("of June");
      case 7:   return translate("of July");
      case 8:   return translate("of August");
      case 9:   return translate("of September");
      case 10:  return translate("of October");
      case 11:  return translate("of November");
      case 12:  return translate("of December");
      }

  return TQString::null;
}

TQString TDELocale::weekDayName (int i, bool shortName) const
{
  return calendar()->weekDayName(i, shortName);
}

void TDELocale::insertCatalogue( const TQString & catalog )
{
  if ( !d->catalogNames.contains( catalog) ) {
    d->catalogNames.append( catalog );
  }
  updateCatalogues( ); // evaluate the changed list and generate the neccessary KCatalog objects
}

void TDELocale::updateCatalogues( )
{
  // some changes have occured. Maybe we have learned or forgotten some languages.
  // Maybe the language precedence has changed.
  // Maybe we have learned or forgotten some catalog names.
  // Now examine the list of KCatalogue objects and change it according to the new circumstances.

  // this could be optimized: try to reuse old KCatalog objects, but remember that the order of
  // catalogs might have changed: e.g. in this fashion
  // 1) move all catalogs into a temporary list
  // 2) iterate over all languages and catalog names
  // 3.1) pick the catalog from the saved list, if it already exists
  // 3.2) else create a new catalog.
  // but we will do this later.

  for ( TQValueList<KCatalogue>::Iterator it = d->catalogues.begin();
	it != d->catalogues.end(); )
  {
     it = d->catalogues.remove(it);
  }

  // now iterate over all languages and all wanted catalog names and append or create them in the right order
  // the sequence must be e.g. nds/appname nds/tdelibs nds/tdeio de/appname de/tdelibs de/tdeio etc.
  // and not nds/appname de/appname nds/tdelibs de/tdelibs etc. Otherwise we would be in trouble with a language
  // sequende nds,en_US, de. In this case en_US must hide everything below in the language list.
  for ( TQStringList::ConstIterator itLangs =  d->languageList.begin();
	  itLangs != d->languageList.end(); ++itLangs)
  {
    for ( TQStringList::ConstIterator itNames =  d->catalogNames.begin();
	itNames != d->catalogNames.end(); ++itNames)
    {
      KCatalogue cat( *itNames, *itLangs ); // create Catalog for this name and this language
      d->catalogues.append( cat );
	}
  }
  initPluralTypes();  // evaluate the plural type for all languages and remember this in each KCatalogue
}




void TDELocale::removeCatalogue(const TQString &catalog)
{
  if ( d->catalogNames.contains( catalog )) {
    d->catalogNames.remove( catalog );
    if (TDEGlobal::_instance)
      updateCatalogues();  // walk through the KCatalogue instances and weed out everything we no longer need
  }
}

void TDELocale::setActiveCatalogue(const TQString &catalog)
{
  if ( d->catalogNames.contains( catalog ) ) {
    d->catalogNames.remove( catalog );
	d->catalogNames.prepend( catalog );
	updateCatalogues();  // walk through the KCatalogue instances and adapt to the new order
  }
}

TDELocale::~TDELocale()
{
  delete d->calendar;
  delete d->languages;
  delete d;
  d = 0L;
}

TQString TDELocale::translate_priv(const char *msgid,
				const char *fallback,
				const char **translated,
				int* pluralType ) const
{
  if ( pluralType) {
  	*pluralType = -1; // unless we find something more precise
  }
  if (!msgid || !msgid[0])
    {
      kdWarning() << "TDELocale: trying to look up \"\" in catalog. "
		   << "Fix the program" << endl;
      return TQString::null;
    }

  if ( useDefaultLanguage() ) { // shortcut evaluation if en_US is main language: do not consult the catalogs
    return TQString::fromUtf8( fallback );
  }

  for ( TQValueList<KCatalogue>::ConstIterator it = d->catalogues.begin();
	it != d->catalogues.end();
	++it )
    {
	  // shortcut evaluation: once we have arrived at en_US (default language) we cannot consult
	  // the catalog as it will not have an assiciated mo-file. For this default language we can
	  // immediately pick the fallback string.
	  if ( (*it).language() == defaultLanguage() ) {
	  	return TQString::fromUtf8( fallback );
	  }

      const char * text = (*it).translate( msgid );

      if ( text )
	{
	  // we found it
	  if (translated) {
	    *translated = text;
	  }
	  if ( pluralType) {
	  	*pluralType = (*it).pluralType(); // remember the plural type information from the catalog that was used
	  }
	  return TQString::fromUtf8( text );
	}
    }

  // Always use UTF-8 if the string was not found
  return TQString::fromUtf8( fallback );
}

TQString TDELocale::translate(const char* msgid) const
{
  return translate_priv(msgid, msgid);
}

TQString TDELocale::translate( const char *index, const char *fallback) const
{
  if (!index || !index[0] || !fallback || !fallback[0])
    {
      kdDebug(173) << "TDELocale: trying to look up \"\" in catalog. "
		   << "Fix the program" << endl;
      return TQString::null;
    }

  if ( useDefaultLanguage() )
    return TQString::fromUtf8( fallback );

  char *newstring = new char[strlen(index) + strlen(fallback) + 5];
  sprintf(newstring, "_: %s\n%s", index, fallback);
  // as copying TQString is very fast, it looks slower as it is ;/
  TQString r = translate_priv(newstring, fallback);
  delete [] newstring;

  return r;
}

static TQString put_n_in(const TQString &orig, unsigned long n)
{
  TQString ret = orig;
  int index = ret.find("%n");
  if (index == -1)
    return ret;
  ret.replace(index, 2, TQString::number(n));
  return ret;
}

#define EXPECT_LENGTH(x) \
   if (forms.count() != x) { \
      kdError() << "translation of \"" << singular << "\" doesn't contain " << x << " different plural forms as expected\n"; \
      return TQString( "BROKEN TRANSLATION %1" ).arg( singular ); }

TQString TDELocale::translate( const char *singular, const char *plural,
                            unsigned long n ) const
{
  if (!singular || !singular[0] || !plural || !plural[0])
    {
      kdWarning() << "TDELocale: trying to look up \"\" in catalog. "
		   << "Fix the program" << endl;
      return TQString::null;
    }

  char *newstring = new char[strlen(singular) + strlen(plural) + 6];
  sprintf(newstring, "_n: %s\n%s", singular, plural);
  // as copying TQString is very fast, it looks slower as it is ;/
  int pluralType = -1;
  TQString r = translate_priv(newstring, 0, 0, &pluralType);
  delete [] newstring;

  if ( r.isEmpty() || useDefaultLanguage() || pluralType == -1) {
    if ( n == 1 ) {
      return put_n_in( TQString::fromUtf8( singular ),  n );
	} else {
	  TQString tmp = TQString::fromUtf8( plural );
#ifndef NDEBUG
	  if (tmp.find("%n") == -1) {
			  kdDebug() << "the message for i18n should contain a '%n'! " << plural << endl;
	  }
#endif
      return put_n_in( tmp,  n );
	}
  }

  TQStringList forms = TQStringList::split( "\n", r, false );
  switch ( pluralType ) {
  case 0: // NoPlural
    EXPECT_LENGTH( 1 );
    return put_n_in( forms[0], n);
  case 1: // TwoForms
    EXPECT_LENGTH( 2 );
    if ( n == 1 )
      return put_n_in( forms[0], n);
    else
      return put_n_in( forms[1], n);
  case 2: // French
    EXPECT_LENGTH( 2 );
    if ( n == 1 || n == 0 )
      return put_n_in( forms[0], n);
    else
      return put_n_in( forms[1], n);
  case 3: // OneTwoRest
    EXPECT_LENGTH( 3 );
    if ( n == 1 )
      return put_n_in( forms[0], n);
    else if ( n == 2 )
      return put_n_in( forms[1], n);
    else
      return put_n_in( forms[2], n);
  case 4: // Russian, corrected by mok
    EXPECT_LENGTH( 3 );
    if ( n%10 == 1  &&  n%100 != 11)
      return put_n_in( forms[0], n); // odin fail
    else if (( n%10 >= 2 && n%10 <=4 ) && (n%100<10 || n%100>20))
      return put_n_in( forms[1], n); // dva faila
    else
      return put_n_in( forms[2], n); // desyat' failov
  case 5: // Polish
    EXPECT_LENGTH( 3 );
    if ( n == 1 )
      return put_n_in( forms[0], n);
    else if ( n%10 >= 2 && n%10 <=4 && (n%100<10 || n%100>=20) )
      return put_n_in( forms[1], n);
    else
      return put_n_in( forms[2], n);
  case 6: // Slovenian
    EXPECT_LENGTH( 4 );
    if ( n%100 == 1 )
      return put_n_in( forms[1], n); // ena datoteka
    else if ( n%100 == 2 )
      return put_n_in( forms[2], n); // dve datoteki
    else if ( n%100 == 3 || n%100 == 4 )
      return put_n_in( forms[3], n); // tri datoteke
    else
      return put_n_in( forms[0], n); // sto datotek
  case 7: // Lithuanian
    EXPECT_LENGTH( 3 );
    if ( n%10 == 0 || (n%100>=11 && n%100<=19) )
      return put_n_in( forms[2], n);
    else if ( n%10 == 1 )
      return put_n_in( forms[0], n);
    else
      return put_n_in( forms[1], n);
  case 8: // Czech - use modern form which is equivalent to Slovak
  case 9: // Slovak
    EXPECT_LENGTH( 3 );
    if ( n == 1 )
      return put_n_in( forms[0], n);
    else if (( n >= 2 ) && ( n <= 4 ))
      return put_n_in( forms[1], n);
    else
      return put_n_in( forms[2], n);
  case 10: // Maltese
    EXPECT_LENGTH( 4 );
    if ( n == 1 )
      return put_n_in( forms[0], n );
    else if ( ( n == 0 ) || ( n%100 > 0 && n%100 <= 10 ) )
      return put_n_in( forms[1], n );
    else if ( n%100 > 10 && n%100 < 20 )
      return put_n_in( forms[2], n );
    else
      return put_n_in( forms[3], n );
  case 11: // Arabic
    EXPECT_LENGTH( 4 );
    if (n == 1)
      return put_n_in(forms[0], n);
    else if (n == 2)
      return put_n_in(forms[1], n);
    else if ( n < 11)
      return put_n_in(forms[2], n);
    else
      return put_n_in(forms[3], n);
  case 12: // Balcan
     EXPECT_LENGTH( 3 );
     if (n != 11 && n % 10 == 1)
	return put_n_in(forms[0], n);
     else if (n / 10 != 1 && n % 10 >= 2 && n % 10 <= 4)
	return put_n_in(forms[1], n);
     else
	return put_n_in(forms[2], n);
  case 13: // Macedonian
     EXPECT_LENGTH(3);
     if (n % 10 == 1)
	return put_n_in(forms[0], n);
     else if (n % 10 == 2)
	return put_n_in(forms[1], n);
     else
	return put_n_in(forms[2], n);
  case 14: // Gaeilge
      EXPECT_LENGTH(5);
      if (n == 1)                       // "ceann amhain"
          return put_n_in(forms[0], n);
      else if (n == 2)                  // "dha cheann"
          return put_n_in(forms[1], n);
      else if (n < 7)                   // "%n cinn"
          return put_n_in(forms[2], n);
      else if (n < 11)                  // "%n gcinn"
          return put_n_in(forms[3], n);
      else                              // "%n ceann"
          return put_n_in(forms[4], n);
  }
  kdFatal() << "The function should have been returned in another way\n";

  return TQString::null;
}

TQString TDELocale::translateQt( const char *context, const char *source,
			      const char *message) const
{
  if (!source || !source[0]) {
    kdWarning() << "TDELocale: trying to look up \"\" in catalog. "
		<< "Fix the program" << endl;
    return TQString::null;
  }

  if ( useDefaultLanguage() ) {
    return TQString::null;
  }

  char *newstring = 0;
  const char *translation = 0;
  TQString r;

  if ( message && message[0]) {
    char *newstring = new char[strlen(source) + strlen(message) + 5];
    sprintf(newstring, "_: %s\n%s", source, message);
    const char *translation = 0;
    // as copying TQString is very fast, it looks slower as it is ;/
    r = translate_priv(newstring, source, &translation);
    delete [] newstring;
    if (translation)
      return r;
  }

  if ( context && context[0] && message && message[0]) {
    newstring = new char[strlen(context) + strlen(message) + 5];
    sprintf(newstring, "_: %s\n%s", context, message);
    // as copying TQString is very fast, it looks slower as it is ;/
    r = translate_priv(newstring, source, &translation);
    delete [] newstring;
    if (translation)
      return r;
  }

  r = translate_priv(source, source, &translation);
  if (translation)
    return r;
  return TQString::null;
}

bool TDELocale::nounDeclension() const
{
  doFormatInit();
  return d->nounDeclension;
}

bool TDELocale::dateMonthNamePossessive() const
{
  doFormatInit();
  return d->dateMonthNamePossessive;
}

int TDELocale::weekStartDay() const
{
  doFormatInit();
  return d->weekStartDay;
}

bool TDELocale::weekStartsMonday() const //deprecated
{
  doFormatInit();
  return (d->weekStartDay==1);
}

TQString TDELocale::decimalSymbol() const
{
  doFormatInit();
  return m_decimalSymbol;
}

TQString TDELocale::thousandsSeparator() const
{
  doFormatInit();
  return m_thousandsSeparator;
}

TQString TDELocale::currencySymbol() const
{
  doFormatInit();
  return m_currencySymbol;
}

TQString TDELocale::monetaryDecimalSymbol() const
{
  doFormatInit();
  return m_monetaryDecimalSymbol;
}

TQString TDELocale::monetaryThousandsSeparator() const
{
  doFormatInit();
  return m_monetaryThousandsSeparator;
}

TQString TDELocale::positiveSign() const
{
  doFormatInit();
  return m_positiveSign;
}

TQString TDELocale::negativeSign() const
{
  doFormatInit();
  return m_negativeSign;
}

int TDELocale::fracDigits() const
{
  doFormatInit();
  return m_fracDigits;
}

bool TDELocale::positivePrefixCurrencySymbol() const
{
  doFormatInit();
  return m_positivePrefixCurrencySymbol;
}

bool TDELocale::negativePrefixCurrencySymbol() const
{
  doFormatInit();
  return m_negativePrefixCurrencySymbol;
}

TDELocale::SignPosition TDELocale::positiveMonetarySignPosition() const
{
  doFormatInit();
  return m_positiveMonetarySignPosition;
}

TDELocale::SignPosition TDELocale::negativeMonetarySignPosition() const
{
  doFormatInit();
  return m_negativeMonetarySignPosition;
}

static inline void put_it_in( TQChar *buffer, uint& index, const TQString &s )
{
  for ( uint l = 0; l < s.length(); l++ )
    buffer[index++] = s.at( l );
}

static inline void put_it_in( TQChar *buffer, uint& index, int number )
{
  buffer[index++] = number / 10 + '0';
  buffer[index++] = number % 10 + '0';
}

// insert (thousands)-"separator"s into the non-fractional part of str 
static void _insertSeparator(TQString &str, const TQString &separator,
			     const TQString &decimalSymbol)
{
  // leave fractional part untouched
  TQString mainPart = str.section(decimalSymbol, 0, 0);
  TQString fracPart = str.section(decimalSymbol, 1, 1,
				 TQString::SectionIncludeLeadingSep);
  
  for (int pos = mainPart.length() - 3; pos > 0; pos -= 3)
    mainPart.insert(pos, separator);

  str = mainPart + fracPart;
}

TQString TDELocale::formatMoney(double num,
			     const TQString & symbol,
			     int precision) const
{
  // some defaults
  TQString currency = symbol.isNull()
    ? currencySymbol()
    : symbol;
  if (precision < 0) precision = fracDigits();

  // the number itself
  bool neg = num < 0;
  TQString res = TQString::number(neg?-num:num, 'f', precision);

  // Replace dot with locale decimal separator
  res.replace(TQChar('.'), monetaryDecimalSymbol());

  // Insert the thousand separators
  _insertSeparator(res, monetaryThousandsSeparator(), monetaryDecimalSymbol());

  // set some variables we need later
  int signpos = neg
    ? negativeMonetarySignPosition()
    : positiveMonetarySignPosition();
  TQString sign = neg
    ? negativeSign()
    : positiveSign();

  switch (signpos)
    {
    case ParensAround:
      res.prepend('(');
      res.append (')');
      break;
    case BeforeQuantityMoney:
      res.prepend(sign);
      break;
    case AfterQuantityMoney:
      res.append(sign);
      break;
    case BeforeMoney:
      currency.prepend(sign);
      break;
    case AfterMoney:
      currency.append(sign);
      break;
    }

  if (neg?negativePrefixCurrencySymbol():
      positivePrefixCurrencySymbol())
    {
      res.prepend(' ');
      res.prepend(currency);
    } else {
      res.append (' ');
      res.append (currency);
    }

  return res;
}

TQString TDELocale::formatMoney(const TQString &numStr) const
{
  return formatMoney(numStr.toDouble());
}

TQString TDELocale::formatNumber(double num, int precision) const
{
  if (precision == -1) precision = 2;
  // no need to round since TQString::number does this for us
  return formatNumber(TQString::number(num, 'f', precision), false, 0);
}

TQString TDELocale::formatLong(long num) const
{
  return formatNumber((double)num, 0);
}

TQString TDELocale::formatNumber(const TQString &numStr) const
{
  return formatNumber(numStr, true, 2);
}

// increase the digit at 'position' by one
static void _inc_by_one(TQString &str, int position)
{
  for (int i = position; i >= 0; i--)
    {
      char last_char = str[i].latin1();
      switch(last_char)
	{
	case '0':
	  str[i] = (QChar)'1';
	  break;
	case '1':
	  str[i] = (QChar)'2';
	  break;
	case '2':
	  str[i] = (QChar)'3';
	  break;
	case '3':
	  str[i] = (QChar)'4';
	  break;
	case '4':
	  str[i] = (QChar)'5';
	  break;
	case '5':
	  str[i] = (QChar)'6';
	  break;
	case '6':
	  str[i] = (QChar)'7';
	  break;
	case '7':
	  str[i] = (QChar)'8';
	  break;
	case '8':
	  str[i] = (QChar)'9';
	  break;
	case '9':
	  str[i] = (QChar)'0';
	  if (i == 0) str.prepend('1');
	  continue;
	case '.':
	  continue;
	}
      break;
    }
}

// Cut off if more digits in fractional part than 'precision'
static void _round(TQString &str, int precision)
{
  int decimalSymbolPos = str.find('.');

  if (decimalSymbolPos == -1)
    if (precision == 0)  return;
    else if (precision > 0) // add dot if missing (and needed)
      {
	str.append('.');
	decimalSymbolPos = str.length() - 1;
      }

  // fill up with more than enough zeroes (in case fractional part too short)
  str.append(TQString().fill('0', precision));

  // Now decide whether to round up or down
  char last_char = str[decimalSymbolPos + precision + 1].latin1();
  switch (last_char)
    {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
      // nothing to do, rounding down
      break;
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
      _inc_by_one(str, decimalSymbolPos + precision);
      break;
    default:
      break;
    }

  decimalSymbolPos = str.find('.');
  str.truncate(decimalSymbolPos + precision + 1);
  
  // if precision == 0 delete also '.'
  if (precision == 0) str = str.section('.', 0, 0);
}

TQString TDELocale::formatNumber(const TQString &numStr, bool round,
			      int precision) const
{
  TQString tmpString = numStr;
  if ((round  && precision < 0)  ||
      ! TQRegExp("^[+-]?\\d+(\\.\\d+)*(e[+-]?\\d+)?$").exactMatch(tmpString))
    return numStr;

  
  // Skip the sign (for now)
  bool neg = (tmpString[0] == (QChar)'-');
  if (neg  ||  tmpString[0] == (QChar)'+') tmpString.remove(0, 1);

  // Split off exponential part (including 'e'-symbol)
  TQString mantString = tmpString.section('e', 0, 0,
					 TQString::SectionCaseInsensitiveSeps);
  TQString expString = tmpString.section('e', 1, 1,
					TQString::SectionCaseInsensitiveSeps |
					TQString::SectionIncludeLeadingSep);

  if (round) _round(mantString, precision);
 
  // Replace dot with locale decimal separator
  mantString.replace(TQChar('.'), decimalSymbol());
  
  // Insert the thousand separators
  _insertSeparator(mantString, thousandsSeparator(), decimalSymbol());

  // How can we know where we should put the sign?
  mantString.prepend(neg?negativeSign():positiveSign());
  
  return mantString +  expString;
}

TQString TDELocale::formatDate(const TQDate &pDate, bool shortFormat) const
{
  const TQString rst = shortFormat?dateFormatShort():dateFormat();

  TQString buffer;

  if ( ! pDate.isValid() ) return buffer;

  bool escape = false;

  int year = calendar()->year(pDate);
  int month = calendar()->month(pDate);

  for ( uint format_index = 0; format_index < rst.length(); ++format_index )
    {
      if ( !escape )
	{
	  if ( (TQChar(rst.at( format_index )).unicode()) == '%' )
	    escape = true;
	  else
	    buffer.append(rst.at(format_index));
	}
      else
	{
	  switch ( TQChar(rst.at( format_index )).unicode() )
	    {
	    case '%':
	      buffer.append('%');
	      break;
	    case 'Y':
	      buffer.append(calendar()->yearString(pDate, false));
	      break;
	    case 'y':
	      buffer.append(calendar()->yearString(pDate, true));
	      break;
	    case 'n':
              buffer.append(calendar()->monthString(pDate, true));
	      break;
	    case 'e':
              buffer.append(calendar()->dayString(pDate, true));
	      break;
	    case 'm':
              buffer.append(calendar()->monthString(pDate, false));
	      break;
	    case 'b':
	      if (d->nounDeclension && d->dateMonthNamePossessive)
		buffer.append(calendar()->monthNamePossessive(month, year, true));
	      else
		buffer.append(calendar()->monthName(month, year, true));
	      break;
	    case 'B':
	      if (d->nounDeclension && d->dateMonthNamePossessive)
		buffer.append(calendar()->monthNamePossessive(month, year, false));
	      else
		buffer.append(calendar()->monthName(month, year, false));
	      break;
	    case 'd':
              buffer.append(calendar()->dayString(pDate, false));
	      break;
	    case 'a':
	      buffer.append(calendar()->weekDayName(pDate, true));
	      break;
	    case 'A':
	      buffer.append(calendar()->weekDayName(pDate, false));
	      break;
	    default:
	      buffer.append(rst.at(format_index));
	      break;
	    }
	  escape = false;
	}
    }
  return buffer;
}

void TDELocale::setMainCatalogue(const char *catalog)
{
  maincatalogue = catalog;
}

double TDELocale::readNumber(const TQString &_str, bool * ok) const
{
  TQString str = _str.stripWhiteSpace();
  bool neg = str.find(negativeSign()) == 0;
  if (neg)
    str.remove( 0, negativeSign().length() );

  /* will hold the scientific notation portion of the number.
     Example, with 2.34E+23, exponentialPart == "E+23"
  */
  TQString exponentialPart;
  int EPos;

  EPos = str.find('E', 0, false);

  if (EPos != -1)
  {
    exponentialPart = str.mid(EPos);
    str = str.left(EPos);
  }

  int pos = str.find(decimalSymbol());
  TQString major;
  TQString minor;
  if ( pos == -1 )
    major = str;
  else
    {
      major = str.left(pos);
      minor = str.mid(pos + decimalSymbol().length());
    }

  // Remove thousand separators
  int thlen = thousandsSeparator().length();
  int lastpos = 0;
  while ( ( pos = major.find( thousandsSeparator() ) ) > 0 )
  {
    // e.g. 12,,345,,678,,922 Acceptable positions (from the end) are 5, 10, 15... i.e. (3+thlen)*N
    int fromEnd = major.length() - pos;
    if ( fromEnd % (3+thlen) != 0 // Needs to be a multiple, otherwise it's an error
        || pos - lastpos > 3 // More than 3 digits between two separators -> error
        || pos == 0          // Can't start with a separator
        || (lastpos>0 && pos-lastpos!=3))   // Must have exactly 3 digits between two separators
    {
      if (ok) *ok = false;
      return 0.0;
    }

    lastpos = pos;
    major.remove( pos, thlen );
  }
  if (lastpos>0 && major.length()-lastpos!=3)   // Must have exactly 3 digits after the last separator
  {
    if (ok) *ok = false;
    return 0.0;
  }

  TQString tot;
  if (neg) tot = (QChar)'-';

  tot += major + '.' + minor + exponentialPart;

  return tot.toDouble(ok);
}

double TDELocale::readMoney(const TQString &_str, bool * ok) const
{
  TQString str = _str.stripWhiteSpace();
  bool neg = false;
  bool currencyFound = false;
  TQString symbol = currencySymbol();
  // First try removing currency symbol from either end
  int pos = str.find(symbol);
  if ( pos == 0 || pos == (int) str.length()-symbol.length() )
    {
      str.remove(pos,symbol.length());
      str = str.stripWhiteSpace();
      currencyFound = true;
    }
  if (str.isEmpty())
    {
      if (ok) *ok = false;
      return 0;
    }
  // Then try removing negative sign from either end
  // (with a special case for parenthesis)
  if (negativeMonetarySignPosition() == ParensAround)
    {
      if (str[0] == (QChar)'(' && str[str.length()-1] == (QChar)')')
        {
	  neg = true;
	  str.remove(str.length()-1,1);
	  str.remove(0,1);
        }
    }
  else
    {
      int i1 = str.find(negativeSign());
      if ( i1 == 0 || i1 == (int) str.length()-1 )
        {
	  neg = true;
	  str.remove(i1,negativeSign().length());
        }
    }
  if (neg) str = str.stripWhiteSpace();

  // Finally try again for the currency symbol, if we didn't find
  // it already (because of the negative sign being in the way).
  if ( !currencyFound )
    {
      pos = str.find(symbol);
      if ( pos == 0 || pos == (int) str.length()-symbol.length() )
        {
	  str.remove(pos,symbol.length());
	  str = str.stripWhiteSpace();
        }
    }

  // And parse the rest as a number
  pos = str.find(monetaryDecimalSymbol());
  TQString major;
  TQString minior;
  if (pos == -1)
    major = str;
  else
    {
      major = str.left(pos);
      minior = str.mid(pos + monetaryDecimalSymbol().length());
    }

  // Remove thousand separators
  int thlen = monetaryThousandsSeparator().length();
  int lastpos = 0;
  while ( ( pos = major.find( monetaryThousandsSeparator() ) ) > 0 )
  {
    // e.g. 12,,345,,678,,922 Acceptable positions (from the end) are 5, 10, 15... i.e. (3+thlen)*N
    int fromEnd = major.length() - pos;
    if ( fromEnd % (3+thlen) != 0 // Needs to be a multiple, otherwise it's an error
        || pos - lastpos > 3 // More than 3 digits between two separators -> error
        || pos == 0          // Can't start with a separator
        || (lastpos>0 && pos-lastpos!=3))   // Must have exactly 3 digits between two separators
    {
      if (ok) *ok = false;
      return 0.0;
    }
    lastpos = pos;
    major.remove( pos, thlen );
  }
  if (lastpos>0 && major.length()-lastpos!=3)   // Must have exactly 3 digits after the last separator
  {
    if (ok) *ok = false;
    return 0.0;
  }

  TQString tot;
  if (neg) tot = (QChar)'-';
  tot += major + '.' + minior;
  return tot.toDouble(ok);
}

/**
 * helper function to read integers
 * @param str
 * @param pos the position to start at. It will be updated when we parse it.
 * @return the integer read in the string, or -1 if no string
 */
static int readInt(const TQString &str, uint &pos)
{
  if (!str.at(pos).isDigit()) return -1;
  int result = 0;
  for (; str.length() > pos && str.at(pos).isDigit(); pos++)
    {
      result *= 10;
      result += str.at(pos).digitValue();
    }

  return result;
}

TQDate TDELocale::readDate(const TQString &intstr, bool* ok) const
{
  TQDate date;
  date = readDate(intstr, ShortFormat, ok);
  if (date.isValid()) return date;
  return readDate(intstr, NormalFormat, ok);
}

TQDate TDELocale::readDate(const TQString &intstr, ReadDateFlags flags, bool* ok) const
{
  TQString fmt = ((flags & ShortFormat) ? dateFormatShort() : dateFormat()).simplifyWhiteSpace();
  return readDate( intstr, fmt, ok );
}

TQDate TDELocale::readDate(const TQString &intstr, const TQString &fmt, bool* ok) const
{
  //kdDebug() << "TDELocale::readDate intstr=" << intstr << " fmt=" << fmt << endl;
  TQString str = intstr.simplifyWhiteSpace().lower();
  int day = -1, month = -1;
  // allow the year to be omitted if not in the format
  int year = calendar()->year(TQDate::currentDate());
  uint strpos = 0;
  uint fmtpos = 0;

  int iLength; // Temporary variable used when reading input

  bool error = false;

  while (fmt.length() > fmtpos && str.length() > strpos && !error)
  {

    TQChar c = fmt.at(fmtpos++);

    if (c != (QChar)'%') {
      if (c.isSpace() && str.at(strpos).isSpace())
        strpos++;
      else if (c != str.at(strpos++))
        error = true;
    }
    else
    {
      int j;
      // remove space at the beginning
      if (str.length() > strpos && str.at(strpos).isSpace())
        strpos++;

      c = fmt.at(fmtpos++);
      switch (c)
      {
	case 'a':
	case 'A':

          error = true;
	  j = 1;
	  while (error && (j < 8)) {
	    TQString s = calendar()->weekDayName(j, c == (QChar)'a').lower();
	    int len = s.length();
	    if (str.mid(strpos, len) == s)
            {
	      strpos += len;
              error = false;
            }
	    j++;
	  }
	  break;
	case 'b':
	case 'B':

          error = true;
	  if (d->nounDeclension && d->dateMonthNamePossessive) {
	    j = 1;
	    while (error && (j < 13)) {
	      TQString s = calendar()->monthNamePossessive(j, year, c == (QChar)'b').lower();
	      int len = s.length();
	      if (str.mid(strpos, len) == s) {
	        month = j;
	        strpos += len;
                error = false;
	      }
	      j++;
	    }
	  }
	  j = 1;
	  while (error && (j < 13)) {
	    TQString s = calendar()->monthName(j, year, c == (QChar)'b').lower();
	    int len = s.length();
	    if (str.mid(strpos, len) == s) {
	      month = j;
	      strpos += len;
              error = false;
	    }
	    j++;
	  }
	  break;
	case 'd':
	case 'e':
	  day = calendar()->dayStringToInteger(str.mid(strpos), iLength);
	  strpos += iLength;

	  error = iLength <= 0;
	  break;

	case 'n':
	case 'm':
	  month = calendar()->monthStringToInteger(str.mid(strpos), iLength);
	  strpos += iLength;

	  error = iLength <= 0;
	  break;

	case 'Y':
	case 'y':
	  year = calendar()->yearStringToInteger(str.mid(strpos), iLength);
	  strpos += iLength;

	  error = iLength <= 0;
	  break;
      }
    }
  }

  /* for a match, we should reach the end of both strings, not just one of
     them */
  if ( fmt.length() > fmtpos || str.length() > strpos )
  {
    error = true;
  }

  //kdDebug(173) << "TDELocale::readDate day=" << day << " month=" << month << " year=" << year << endl;
  if ( year != -1 && month != -1 && day != -1 && !error)
  {
    if (ok) *ok = true;

    TQDate result;
    calendar()->setYMD(result, year, month, day);

    return result;
  }
  else
  {
    if (ok) *ok = false;
    return TQDate(); // invalid date
  }
}

TQTime TDELocale::readTime(const TQString &intstr, bool *ok) const
{
  TQTime _time;
  _time = readTime(intstr, WithSeconds, ok);
  if (_time.isValid()) return _time;
  return readTime(intstr, WithoutSeconds, ok);
}

TQTime TDELocale::readTime(const TQString &intstr, ReadTimeFlags flags, bool *ok) const
{
  TQString str = intstr.simplifyWhiteSpace().lower();
  TQString Format = timeFormat().simplifyWhiteSpace();
  if (flags & WithoutSeconds)
    Format.remove(TQRegExp(".%S"));

  int hour = -1, minute = -1;
  int second = ( (flags & WithoutSeconds) == 0 ) ? -1 : 0; // don't require seconds
  bool g_12h = false;
  bool pm = false;
  uint strpos = 0;
  uint Formatpos = 0;

  while (Format.length() > Formatpos || str.length() > strpos)
    {
      if ( !(Format.length() > Formatpos && str.length() > strpos) ) goto error;

      TQChar c = Format.at(Formatpos++);

      if (c != (QChar)'%')
	{
	  if (c.isSpace())
	    strpos++;
	  else if (c != str.at(strpos++))
	    goto error;
	  continue;
	}

      // remove space at the beginning
      if (str.length() > strpos && str.at(strpos).isSpace())
	strpos++;

      c = Format.at(Formatpos++);
      switch (c)
	{
	case 'p':
	  {
	    TQString s;
	    s = translate("pm").lower();
	    int len = s.length();
	    if (str.mid(strpos, len) == s)
	      {
		pm = true;
		strpos += len;
	      }
	    else
	      {
		s = translate("am").lower();
		len = s.length();
		if (str.mid(strpos, len) == s) {
		  pm = false;
		  strpos += len;
		}
		else
		  goto error;
	      }
	  }
	  break;

	case 'k':
	case 'H':
	  g_12h = false;
	  hour = readInt(str, strpos);
	  if (hour < 0 || hour > 23)
	    goto error;

	  break;

	case 'l':
	case 'I':
	  g_12h = true;
	  hour = readInt(str, strpos);
	  if (hour < 1 || hour > 12)
	    goto error;

	  break;

	case 'M':
	  minute = readInt(str, strpos);
	  if (minute < 0 || minute > 59)
	    goto error;

	  break;

	case 'S':
	  second = readInt(str, strpos);
	  if (second < 0 || second > 59)
	    goto error;

	  break;
	}
    }
  if (g_12h) {
    hour %= 12;
    if (pm) hour += 12;
  }

  if (ok) *ok = true;
  return TQTime(hour, minute, second);

 error:
  if (ok) *ok = false;
  // ######## KDE4: remove this
  return TQTime(-1, -1, -1); // return invalid date if it didn't work
}

//BIC: merge with below
TQString TDELocale::formatTime(const TQTime &pTime, bool includeSecs) const
{
  return formatTime( pTime, includeSecs, false );
}

TQString TDELocale::formatTime(const TQTime &pTime, bool includeSecs, bool isDuration) const
{
  const TQString rst = timeFormat();

  // only "pm/am" here can grow, the rest shrinks, but
  // I'm rather safe than sorry
  TQChar *buffer = new TQChar[rst.length() * 3 / 2 + 30];

  uint index = 0;
  bool escape = false;
  int number = 0;

  for ( uint format_index = 0; format_index < rst.length(); format_index++ )
    {
      if ( !escape )
	{
	  if ( (TQChar(rst.at( format_index )).unicode()) == '%' )
	    escape = true;
	  else
	    buffer[index++] = rst.at( format_index );
	}
      else
	{
	  switch ( TQChar(rst.at( format_index )).unicode() )
	    {
	    case '%':
	      buffer[index++] = (QChar)'%';
	      break;
	    case 'H':
	      put_it_in( buffer, index, pTime.hour() );
	      break;
	    case 'I':
	      if ( isDuration )
	          put_it_in( buffer, index, pTime.hour() );
	      else
	          put_it_in( buffer, index, ( pTime.hour() + 11) % 12 + 1 );
	      break;
	    case 'M':
	      put_it_in( buffer, index, pTime.minute() );
	      break;
	    case 'S':
	      if (includeSecs)
		put_it_in( buffer, index, pTime.second() );
	      else if ( index > 0 )
		{
		  // we remove the separator sign before the seconds and
		  // assume that works everywhere
		  --index;
		  break;
		}
	      break;
	    case 'k':
	      number = pTime.hour();
	    case 'l':
	      // to share the code
	      if ( (TQChar(rst.at( format_index )).unicode()) == 'l' )
		number = isDuration ? pTime.hour() : (pTime.hour() + 11) % 12 + 1;
	      if ( number / 10 )
		buffer[index++] = number / 10 + '0';
	      buffer[index++] = number % 10 + '0';
	      break;
	    case 'p':
	      if ( !isDuration )
	      {
		TQString s;
		if ( pTime.hour() >= 12 )
		  put_it_in( buffer, index, translate("pm") );
		else
		  put_it_in( buffer, index, translate("am") );
	      }
	      break;
	    default:
	      buffer[index++] = rst.at( format_index );
	      break;
	    }
	  escape = false;
	}
    }
  TQString ret( buffer, index );
  delete [] buffer;
  if ( isDuration ) // eliminate trailing-space due to " %p"
    return ret.stripWhiteSpace();
  else
    return ret;
}

bool TDELocale::use12Clock() const
{
  if ((timeFormat().contains(TQString::fromLatin1("%I")) > 0) ||
      (timeFormat().contains(TQString::fromLatin1("%l")) > 0))
    return true;
  else
    return false;
}

TQString TDELocale::languages() const
{
  return d->languageList.join( TQString::fromLatin1(":") );
}

TQStringList TDELocale::languageList() const
{
  return d->languageList;
}

TQString TDELocale::formatDateTime(const TQDateTime &pDateTime,
				bool shortFormat,
				bool includeSeconds) const
{
  return translate("concatenation of dates and time", "%1 %2")
    .arg( formatDate( TQT_TQDATE_OBJECT(pDateTime.date()), shortFormat ) )
    .arg( formatTime( TQT_TQTIME_OBJECT(pDateTime.time()), includeSeconds ) );
}

TQString i18n(const char* text)
{
  register TDELocale *instance = TDEGlobal::locale();
  if (instance)
    return instance->translate(text);
  return TQString::fromUtf8(text);
}

TQString i18n(const char* index, const char *text)
{
  register TDELocale *instance = TDEGlobal::locale();
  if (instance)
    return instance->translate(index, text);
  return TQString::fromUtf8(text);
}

TQString i18n(const char* singular, const char* plural, unsigned long n)
{
  register TDELocale *instance = TDEGlobal::locale();
  if (instance)
    return instance->translate(singular, plural, n);
  if (n == 1)
    return put_n_in(TQString::fromUtf8(singular), n);
  else
    return put_n_in(TQString::fromUtf8(plural), n);
}

void TDELocale::initInstance()
{
  if (TDEGlobal::_locale)
    return;

  TDEInstance *app = TDEGlobal::instance();
  if (app) {
    TDEGlobal::_locale = new TDELocale(TQString::fromLatin1(app->instanceName()));

    // only do this for the global instance
    TQTextCodec::setCodecForLocale(TDEGlobal::_locale->codecForEncoding());
  }
  else
    kdDebug(173) << "no app name available using TDELocale - nothing to do\n";
}

TQString TDELocale::langLookup(const TQString &fname, const char *rtype)
{
  TQStringList search;

  // assemble the local search paths
  const TQStringList localDoc = TDEGlobal::dirs()->resourceDirs(rtype);

  // look up the different languages
  for (int id=localDoc.count()-1; id >= 0; --id)
    {
      TQStringList langs = TDEGlobal::locale()->languageList();
      langs.append( "en" );
      langs.remove( defaultLanguage() );
      TQStringList::ConstIterator lang;
      for (lang = langs.begin(); lang != langs.end(); ++lang)
	search.append(TQString("%1%2/%3").arg(localDoc[id]).arg(*lang).arg(fname));
    }

  // try to locate the file
  TQStringList::Iterator it;
  for (it = search.begin(); it != search.end(); ++it)
    {
      kdDebug(173) << "Looking for help in: " << *it << endl;

      TQFileInfo info(*it);
      if (info.exists() && info.isFile() && info.isReadable())
	return *it;
    }

  return TQString::null;
}

bool TDELocale::useDefaultLanguage() const
{
  return language() == defaultLanguage();
}

void TDELocale::initEncoding(TDEConfig *)
{
  const int mibDefault = 4; // ISO 8859-1

  // This all made more sense when we still had the EncodingEnum config key.
  setEncoding( TQTextCodec::codecForLocale()->mibEnum() );

  if ( !d->codecForEncoding )
    {
      kdWarning(173) << " Defaulting to ISO 8859-1 encoding." << endl;
      setEncoding(mibDefault);
    }

  Q_ASSERT( d->codecForEncoding );
}

void TDELocale::initFileNameEncoding(TDEConfig *)
{
  // If the following environment variable is set, assume all filenames
  // are in UTF-8 regardless of the current C locale.
  d->utf8FileEncoding = getenv("TDE_UTF8_FILENAMES") != 0;
  if (d->utf8FileEncoding)
  {
    TQFile::setEncodingFunction(TDELocale::encodeFileNameUTF8);
    TQFile::setDecodingFunction(TDELocale::decodeFileNameUTF8);
  }
  // Otherwise, stay with QFile's default filename encoding functions
  // which, on Unix platforms, use the locale's codec.
}

#ifdef USE_QT3
TQCString TDELocale::encodeFileNameUTF8( const TQString & fileName )
#endif // USE_QT3
#ifdef USE_QT4
QByteArray TDELocale::encodeFileNameUTF8( const QString & fileName )
#endif // USE_QT4
{
  return TQString(fileName).utf8();
}

#ifdef USE_QT3
TQString TDELocale::decodeFileNameUTF8( const TQCString & localFileName )
#endif // USE_QT3
#ifdef USE_QT4
QString TDELocale::decodeFileNameUTF8( const QByteArray & localFileName )
#endif // USE_QT4
{
  return TQString::fromUtf8(localFileName);
}

void TDELocale::setDateFormat(const TQString & format)
{
  doFormatInit();
  m_dateFormat = format.stripWhiteSpace();
}

void TDELocale::setDateFormatShort(const TQString & format)
{
  doFormatInit();
  m_dateFormatShort = format.stripWhiteSpace();
}

void TDELocale::setDateMonthNamePossessive(bool possessive)
{
  doFormatInit();
  d->dateMonthNamePossessive = possessive;
}

void TDELocale::setTimeFormat(const TQString & format)
{
  doFormatInit();
  m_timeFormat = format.stripWhiteSpace();
}

void TDELocale::setWeekStartsMonday(bool start) //deprecated
{
  doFormatInit();
  if (start)
    d->weekStartDay = 1;
  else
    d->weekStartDay = 7;
}

void TDELocale::setWeekStartDay(int day)
{
  doFormatInit();
  if (day>7 || day<1)
    d->weekStartDay = 1; //Monday is default
  else
    d->weekStartDay = day;
}

TQString TDELocale::dateFormat() const
{
  doFormatInit();
  return m_dateFormat;
}

TQString TDELocale::dateFormatShort() const
{
  doFormatInit();
  return m_dateFormatShort;
}

TQString TDELocale::timeFormat() const
{
  doFormatInit();
  return m_timeFormat;
}

void TDELocale::setDecimalSymbol(const TQString & symbol)
{
  doFormatInit();
  m_decimalSymbol = symbol.stripWhiteSpace();
}

void TDELocale::setThousandsSeparator(const TQString & separator)
{
  doFormatInit();
  // allow spaces here
  m_thousandsSeparator = separator;
}

void TDELocale::setPositiveSign(const TQString & sign)
{
  doFormatInit();
  m_positiveSign = sign.stripWhiteSpace();
}

void TDELocale::setNegativeSign(const TQString & sign)
{
  doFormatInit();
  m_negativeSign = sign.stripWhiteSpace();
}

void TDELocale::setPositiveMonetarySignPosition(SignPosition signpos)
{
  doFormatInit();
  m_positiveMonetarySignPosition = signpos;
}

void TDELocale::setNegativeMonetarySignPosition(SignPosition signpos)
{
  doFormatInit();
  m_negativeMonetarySignPosition = signpos;
}

void TDELocale::setPositivePrefixCurrencySymbol(bool prefix)
{
  doFormatInit();
  m_positivePrefixCurrencySymbol = prefix;
}

void TDELocale::setNegativePrefixCurrencySymbol(bool prefix)
{
  doFormatInit();
  m_negativePrefixCurrencySymbol = prefix;
}

void TDELocale::setFracDigits(int digits)
{
  doFormatInit();
  m_fracDigits = digits;
}

void TDELocale::setMonetaryThousandsSeparator(const TQString & separator)
{
  doFormatInit();
  // allow spaces here
  m_monetaryThousandsSeparator = separator;
}

void TDELocale::setMonetaryDecimalSymbol(const TQString & symbol)
{
  doFormatInit();
  m_monetaryDecimalSymbol = symbol.stripWhiteSpace();
}

void TDELocale::setCurrencySymbol(const TQString & symbol)
{
  doFormatInit();
  m_currencySymbol = symbol.stripWhiteSpace();
}

int TDELocale::pageSize() const
{
  doFormatInit();
  return d->pageSize;
}

void TDELocale::setPageSize(int pageSize)
{
  // #### check if it's in range??
  doFormatInit();
  d->pageSize = pageSize;
}

TDELocale::MeasureSystem TDELocale::measureSystem() const
{
  doFormatInit();
  return d->measureSystem;
}

void TDELocale::setMeasureSystem(MeasureSystem value)
{
  doFormatInit();
  d->measureSystem = value;
}

TQString TDELocale::defaultLanguage()
{
  return TQString::fromLatin1("en_US");
}

TQString TDELocale::defaultCountry()
{
  return TQString::fromLatin1("C");
}

const char * TDELocale::encoding() const
{
#ifdef Q_WS_WIN
  if (0==qstrcmp("System", codecForEncoding()->name()))
  {
    //win32 returns "System" codec name here but KDE apps expect a real name:
    strcpy(d->win32SystemEncoding, "cp ");
    if (GetLocaleInfoA( MAKELCID(MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), SORT_DEFAULT), 
      LOCALE_IDEFAULTANSICODEPAGE, d->win32SystemEncoding+3, sizeof(d->win32SystemEncoding)-3-1 ))
    {
      return d->win32SystemEncoding;
    }
  }
#endif
  return codecForEncoding()->name();
}

int TDELocale::encodingMib() const
{
  return codecForEncoding()->mibEnum();
}

int TDELocale::fileEncodingMib() const
{
  if (d->utf8FileEncoding)
     return 106;
  return codecForEncoding()->mibEnum();
}

TQTextCodec * TDELocale::codecForEncoding() const
{
  return d->codecForEncoding;
}

bool TDELocale::setEncoding(int mibEnum)
{
  TQTextCodec * codec = TQTextCodec::codecForMib(mibEnum);
  if (codec)
    d->codecForEncoding = codec;

  return codec != 0;
}

TQStringList TDELocale::languagesTwoAlpha() const
{
  if (d->langTwoAlpha.count())
     return d->langTwoAlpha;

  const TQStringList &origList = languageList();

  TQStringList result;

  TDEConfig config(TQString::fromLatin1("language.codes"), true, false);
  config.setGroup("TwoLetterCodes");

  for ( TQStringList::ConstIterator it = origList.begin();
	it != origList.end();
	++it )
    {
      TQString lang = *it;
      TQStringList langLst;
      if (config.hasKey( lang ))
         langLst = config.readListEntry( lang );
      else
      {
         int i = lang.find('_');
         if (i >= 0)
            lang.truncate(i);
         langLst << lang;
      }

      for ( TQStringList::ConstIterator langIt = langLst.begin();
	    langIt != langLst.end();
	    ++langIt )
	{
	  if ( !(*langIt).isEmpty() && !result.contains( *langIt ) )
	    result += *langIt;
	}
    }
  d->langTwoAlpha = result;
  return result;
}

TQStringList TDELocale::allLanguagesTwoAlpha() const
{
  if (!d->languages)
    d->languages = new TDEConfig("all_languages", true, false, "locale");

  return d->languages->groupList();
}

TQString TDELocale::twoAlphaToLanguageName(const TQString &code) const
{
  if (!d->languages)
    d->languages = new TDEConfig("all_languages", true, false, "locale");

  TQString groupName = code;
  const int i = groupName.find('_');
  groupName.replace(0, i, groupName.left(i).lower());

  d->languages->setGroup(groupName);
  return d->languages->readEntry("Name");
}

TQStringList TDELocale::allCountriesTwoAlpha() const
{
  TQStringList countries;
  TQStringList paths = TDEGlobal::dirs()->findAllResources("locale", "l10n/*/entry.desktop");
  for(TQStringList::ConstIterator it = paths.begin();
      it != paths.end(); ++it)
  {
    TQString code = (*it).mid((*it).length()-16, 2);
    if (code != "/C")
       countries.append(code);
  }
  return countries;
}

TQString TDELocale::twoAlphaToCountryName(const TQString &code) const
{
  TDEConfig cfg("l10n/"+code.lower()+"/entry.desktop", true, false, "locale");
  cfg.setGroup("KCM Locale");
  return cfg.readEntry("Name");
}

void TDELocale::setCalendar(const TQString & calType)
{
  doFormatInit();

  d->calendarType = calType;

  delete d->calendar;
  d->calendar = 0;
}

TQString TDELocale::calendarType() const
{
  doFormatInit();

  return d->calendarType;
}

const KCalendarSystem * TDELocale::calendar() const
{
  doFormatInit();

  // Check if it's the correct calendar?!?
  if ( !d->calendar )
    d->calendar = KCalendarSystemFactory::create( d->calendarType, this );

  return d->calendar;
}

TDELocale::TDELocale(const TDELocale & rhs)
{
  d = new TDELocalePrivate;

  *this = rhs;
}

TDELocale & TDELocale::operator=(const TDELocale & rhs)
{
  // Numbers and money
  m_decimalSymbol = rhs.m_decimalSymbol;
  m_thousandsSeparator = rhs.m_thousandsSeparator;
  m_currencySymbol = rhs.m_currencySymbol;
  m_monetaryDecimalSymbol = rhs.m_monetaryDecimalSymbol;
  m_monetaryThousandsSeparator = rhs.m_monetaryThousandsSeparator;
  m_positiveSign = rhs.m_positiveSign;
  m_negativeSign = rhs.m_negativeSign;
  m_fracDigits = rhs.m_fracDigits;
  m_positivePrefixCurrencySymbol = rhs.m_positivePrefixCurrencySymbol;
  m_negativePrefixCurrencySymbol = rhs.m_negativePrefixCurrencySymbol;
  m_positiveMonetarySignPosition = rhs.m_positiveMonetarySignPosition;
  m_negativeMonetarySignPosition = rhs.m_negativeMonetarySignPosition;

  // Date and time
  m_timeFormat = rhs.m_timeFormat;
  m_dateFormat = rhs.m_dateFormat;
  m_dateFormatShort = rhs.m_dateFormatShort;

  m_language = rhs.m_language;
  m_country = rhs.m_country;

  // the assignment operator works here
  *d = *rhs.d;
  d->languages = 0; // Don't copy languages
  d->calendar = 0; // Don't copy the calendar

  return *this;
}

bool TDELocale::setCharset(const TQString & ) { return true; }
TQString TDELocale::charset() const { return TQString::fromLatin1("UTF-8"); }

// KDE4: remove
#if 0
void nothing() { i18n("&Next"); }
#endif