Added regedit unit test, a couple minor changes to regedit.
[wine] / ole / ole2nls.c
1 /*
2  *      National Language Support library
3  *
4  *      Copyright 1995  Martin von Loewis
5  *      Copyright 1998  David Lee Lambert
6  *      Copyright 2000  Julio César Gázquez
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <string.h>
27 #include <stdio.h>
28 #include <ctype.h>
29 #include <stdlib.h>
30 #include <locale.h>
31
32 #include "windef.h"
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "winuser.h"
36 #include "wine/unicode.h"
37 #include "winver.h"
38 #include "winnls.h"
39 #include "winreg.h"
40 #include "winerror.h"
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(string);
44
45 /* Locale name to id map. used by EnumSystemLocales, GetLocaleInfoA
46  * MUST contain all #defines from winnls.h
47  * last entry has NULL name, 0 id.
48  */
49 #define LOCALE_ENTRY(x) {#x,LOCALE_##x}
50 static const struct tagLOCALE_NAME2ID {
51     const char  *name;
52     LCTYPE      id;
53 } locale_name2id[]= {
54         LOCALE_ENTRY(ILANGUAGE),
55         LOCALE_ENTRY(SLANGUAGE),
56         LOCALE_ENTRY(SENGLANGUAGE),
57         LOCALE_ENTRY(SABBREVLANGNAME),
58         LOCALE_ENTRY(SNATIVELANGNAME),
59         LOCALE_ENTRY(ICOUNTRY),
60         LOCALE_ENTRY(SCOUNTRY),
61         LOCALE_ENTRY(SENGCOUNTRY),
62         LOCALE_ENTRY(SABBREVCTRYNAME),
63         LOCALE_ENTRY(SNATIVECTRYNAME),
64         LOCALE_ENTRY(IDEFAULTLANGUAGE),
65         LOCALE_ENTRY(IDEFAULTCOUNTRY),
66         LOCALE_ENTRY(IDEFAULTCODEPAGE),
67         LOCALE_ENTRY(IDEFAULTANSICODEPAGE),
68         LOCALE_ENTRY(IDEFAULTMACCODEPAGE),
69         LOCALE_ENTRY(SLIST),
70         LOCALE_ENTRY(IMEASURE),
71         LOCALE_ENTRY(SDECIMAL),
72         LOCALE_ENTRY(STHOUSAND),
73         LOCALE_ENTRY(SGROUPING),
74         LOCALE_ENTRY(IDIGITS),
75         LOCALE_ENTRY(ILZERO),
76         LOCALE_ENTRY(INEGNUMBER),
77         LOCALE_ENTRY(SNATIVEDIGITS),
78         LOCALE_ENTRY(SCURRENCY),
79         LOCALE_ENTRY(SINTLSYMBOL),
80         LOCALE_ENTRY(SMONDECIMALSEP),
81         LOCALE_ENTRY(SMONTHOUSANDSEP),
82         LOCALE_ENTRY(SMONGROUPING),
83         LOCALE_ENTRY(ICURRDIGITS),
84         LOCALE_ENTRY(IINTLCURRDIGITS),
85         LOCALE_ENTRY(ICURRENCY),
86         LOCALE_ENTRY(INEGCURR),
87         LOCALE_ENTRY(SDATE),
88         LOCALE_ENTRY(STIME),
89         LOCALE_ENTRY(SSHORTDATE),
90         LOCALE_ENTRY(SLONGDATE),
91         LOCALE_ENTRY(STIMEFORMAT),
92         LOCALE_ENTRY(IDATE),
93         LOCALE_ENTRY(ILDATE),
94         LOCALE_ENTRY(ITIME),
95         LOCALE_ENTRY(ITIMEMARKPOSN),
96         LOCALE_ENTRY(ICENTURY),
97         LOCALE_ENTRY(ITLZERO),
98         LOCALE_ENTRY(IDAYLZERO),
99         LOCALE_ENTRY(IMONLZERO),
100         LOCALE_ENTRY(S1159),
101         LOCALE_ENTRY(S2359),
102         LOCALE_ENTRY(ICALENDARTYPE),
103         LOCALE_ENTRY(IOPTIONALCALENDAR),
104         LOCALE_ENTRY(IFIRSTDAYOFWEEK),
105         LOCALE_ENTRY(IFIRSTWEEKOFYEAR),
106         LOCALE_ENTRY(SDAYNAME1),
107         LOCALE_ENTRY(SDAYNAME2),
108         LOCALE_ENTRY(SDAYNAME3),
109         LOCALE_ENTRY(SDAYNAME4),
110         LOCALE_ENTRY(SDAYNAME5),
111         LOCALE_ENTRY(SDAYNAME6),
112         LOCALE_ENTRY(SDAYNAME7),
113         LOCALE_ENTRY(SABBREVDAYNAME1),
114         LOCALE_ENTRY(SABBREVDAYNAME2),
115         LOCALE_ENTRY(SABBREVDAYNAME3),
116         LOCALE_ENTRY(SABBREVDAYNAME4),
117         LOCALE_ENTRY(SABBREVDAYNAME5),
118         LOCALE_ENTRY(SABBREVDAYNAME6),
119         LOCALE_ENTRY(SABBREVDAYNAME7),
120         LOCALE_ENTRY(SMONTHNAME1),
121         LOCALE_ENTRY(SMONTHNAME2),
122         LOCALE_ENTRY(SMONTHNAME3),
123         LOCALE_ENTRY(SMONTHNAME4),
124         LOCALE_ENTRY(SMONTHNAME5),
125         LOCALE_ENTRY(SMONTHNAME6),
126         LOCALE_ENTRY(SMONTHNAME7),
127         LOCALE_ENTRY(SMONTHNAME8),
128         LOCALE_ENTRY(SMONTHNAME9),
129         LOCALE_ENTRY(SMONTHNAME10),
130         LOCALE_ENTRY(SMONTHNAME11),
131         LOCALE_ENTRY(SMONTHNAME12),
132         LOCALE_ENTRY(SMONTHNAME13),
133         LOCALE_ENTRY(SABBREVMONTHNAME1),
134         LOCALE_ENTRY(SABBREVMONTHNAME2),
135         LOCALE_ENTRY(SABBREVMONTHNAME3),
136         LOCALE_ENTRY(SABBREVMONTHNAME4),
137         LOCALE_ENTRY(SABBREVMONTHNAME5),
138         LOCALE_ENTRY(SABBREVMONTHNAME6),
139         LOCALE_ENTRY(SABBREVMONTHNAME7),
140         LOCALE_ENTRY(SABBREVMONTHNAME8),
141         LOCALE_ENTRY(SABBREVMONTHNAME9),
142         LOCALE_ENTRY(SABBREVMONTHNAME10),
143         LOCALE_ENTRY(SABBREVMONTHNAME11),
144         LOCALE_ENTRY(SABBREVMONTHNAME12),
145         LOCALE_ENTRY(SABBREVMONTHNAME13),
146         LOCALE_ENTRY(SPOSITIVESIGN),
147         LOCALE_ENTRY(SNEGATIVESIGN),
148         LOCALE_ENTRY(IPOSSIGNPOSN),
149         LOCALE_ENTRY(INEGSIGNPOSN),
150         LOCALE_ENTRY(IPOSSYMPRECEDES),
151         LOCALE_ENTRY(IPOSSEPBYSPACE),
152         LOCALE_ENTRY(INEGSYMPRECEDES),
153         LOCALE_ENTRY(INEGSEPBYSPACE),
154         LOCALE_ENTRY(FONTSIGNATURE),
155         LOCALE_ENTRY(SISO639LANGNAME),
156         LOCALE_ENTRY(SISO3166CTRYNAME),
157         {NULL,0}
158 };
159
160 static char *GetLocaleSubkeyName( DWORD lctype );
161
162 /***********************************************************************
163  *              GetUserDefaultLCID (KERNEL32.@)
164  */
165 LCID WINAPI GetUserDefaultLCID(void)
166 {
167         return MAKELCID( GetUserDefaultLangID() , SORT_DEFAULT );
168 }
169
170 /***********************************************************************
171  *              GetSystemDefaultLCID (KERNEL32.@)
172  */
173 LCID WINAPI GetSystemDefaultLCID(void)
174 {
175         return GetUserDefaultLCID();
176 }
177
178 #define NLS_MAX_LANGUAGES 20
179 typedef struct {
180     char lang[128];
181     char country[128];
182     LANGID found_lang_id[NLS_MAX_LANGUAGES];
183     char found_language[NLS_MAX_LANGUAGES][3];
184     char found_country[NLS_MAX_LANGUAGES][3];
185     int n_found;
186 } LANG_FIND_DATA;
187
188 static BOOL CALLBACK NLS_FindLanguageID_ProcA(HMODULE hModule, LPCSTR type,
189                                               LPCSTR name, WORD LangID, LONG lParam)
190 {
191     LANG_FIND_DATA *l_data = (LANG_FIND_DATA *)lParam;
192     LCID lcid = MAKELCID(LangID, SORT_DEFAULT);
193     char buf_language[128];
194     char buf_country[128];
195     char buf_en_language[128];
196
197     TRACE("%04X\n", (UINT)LangID);
198     if(PRIMARYLANGID(LangID) == LANG_NEUTRAL)
199         return TRUE; /* continue search */
200
201     buf_language[0] = 0;
202     buf_country[0] = 0;
203
204     GetLocaleInfoA(lcid, LOCALE_SISO639LANGNAME|LOCALE_NOUSEROVERRIDE,
205                    buf_language, sizeof(buf_language));
206     TRACE("LOCALE_SISO639LANGNAME: %s\n", buf_language);
207
208     GetLocaleInfoA(lcid, LOCALE_SISO3166CTRYNAME|LOCALE_NOUSEROVERRIDE,
209                    buf_country, sizeof(buf_country));
210     TRACE("LOCALE_SISO3166CTRYNAME: %s\n", buf_country);
211
212     if(l_data->lang && strlen(l_data->lang) > 0 && !strcasecmp(l_data->lang, buf_language))
213     {
214         if(l_data->country && strlen(l_data->country) > 0)
215         {
216             if(!strcasecmp(l_data->country, buf_country))
217             {
218                 l_data->found_lang_id[0] = LangID;
219                 l_data->n_found = 1;
220                 TRACE("Found lang_id %04X for %s_%s\n", LangID, l_data->lang, l_data->country);
221                 return FALSE; /* stop enumeration */
222             }
223         }
224         else /* l_data->country not specified */
225         {
226             if(l_data->n_found < NLS_MAX_LANGUAGES)
227             {
228                 l_data->found_lang_id[l_data->n_found] = LangID;
229                 strncpy(l_data->found_country[l_data->n_found], buf_country, 3);
230                 strncpy(l_data->found_language[l_data->n_found], buf_language, 3);
231                 l_data->n_found++;
232                 TRACE("Found lang_id %04X for %s\n", LangID, l_data->lang);
233                 return TRUE; /* continue search */
234             }
235         }
236     }
237
238     /* Just in case, check LOCALE_SENGLANGUAGE too,
239      * in hope that possible alias name might have that value.
240      */
241     buf_en_language[0] = 0;
242     GetLocaleInfoA(lcid, LOCALE_SENGLANGUAGE|LOCALE_NOUSEROVERRIDE,
243                    buf_en_language, sizeof(buf_en_language));
244     TRACE("LOCALE_SENGLANGUAGE: %s\n", buf_en_language);
245
246     if(l_data->lang && strlen(l_data->lang) > 0 && !strcasecmp(l_data->lang, buf_en_language))
247     {
248         l_data->found_lang_id[l_data->n_found] = LangID;
249         strncpy(l_data->found_country[l_data->n_found], buf_country, 3);
250         strncpy(l_data->found_language[l_data->n_found], buf_language, 3);
251         l_data->n_found++;
252         TRACE("Found lang_id %04X for %s\n", LangID, l_data->lang);
253     }
254
255     return TRUE; /* continue search */
256 }
257
258 /***********************************************************************
259  *           NLS_GetLanguageID
260  *
261  * INPUT:
262  *      Lang: a string whose two first chars are the iso name of a language.
263  *      Country: a string whose two first chars are the iso name of country
264  *      Charset: a string defining the chossen charset encoding
265  *      Dialect: a string defining a variation of the locale
266  *
267  *      all those values are from the standardized format of locale
268  *      name in unix which is: Lang[_Country][.Charset][@Dialect]
269  *
270  * RETURNS:
271  *      the numeric code of the language used by Windows
272  *
273  * FIXME: Charset and Dialect are not handled
274  */
275 static LANGID NLS_GetLanguageID(LPCSTR Lang, LPCSTR Country, LPCSTR Charset, LPCSTR Dialect)
276 {
277     LANG_FIND_DATA l_data;
278     char lang_string[256];
279
280     if(!Lang)
281     {
282         l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
283         goto END;
284     }
285
286     memset(&l_data, 0, sizeof(LANG_FIND_DATA));
287     strncpy(l_data.lang, Lang, sizeof(l_data.lang));
288
289     if(Country && strlen(Country) > 0)
290         strncpy(l_data.country, Country, sizeof(l_data.country));
291
292     EnumResourceLanguagesA(GetModuleHandleA("KERNEL32"), RT_STRINGA,
293         (LPCSTR)LOCALE_ILANGUAGE, NLS_FindLanguageID_ProcA, (LONG)&l_data);
294
295     strcpy(lang_string, l_data.lang);
296     if(l_data.country && strlen(l_data.country) > 0)
297     {
298         strcat(lang_string, "_");
299         strcat(lang_string, l_data.country);
300     }
301
302     if(!l_data.n_found)
303     {
304         if(l_data.country && strlen(l_data.country) > 0)
305         {
306             MESSAGE("Warning: Language '%s' was not found, retrying without country name...\n", lang_string);
307             l_data.country[0] = 0;
308             EnumResourceLanguagesA(GetModuleHandleA("KERNEL32"), RT_STRINGA,
309                 (LPCSTR)LOCALE_ILANGUAGE, NLS_FindLanguageID_ProcA, (LONG)&l_data);
310         }
311     }
312
313     /* Re-evaluate lang_string */
314     strcpy(lang_string, l_data.lang);
315     if(l_data.country && strlen(l_data.country) > 0)
316     {
317         strcat(lang_string, "_");
318         strcat(lang_string, l_data.country);
319     }
320
321     if(!l_data.n_found)
322     {
323         MESSAGE("Warning: Language '%s' was not recognized, defaulting to English\n", lang_string);
324         l_data.found_lang_id[0] = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
325     }
326     else
327     {
328         if(l_data.n_found == 1)
329             TRACE("For language '%s' lang_id %04X was found\n", lang_string, l_data.found_lang_id[0]);
330         else /* l_data->n_found > 1 */
331         {
332             int i;
333             MESSAGE("For language '%s' several language ids were found:\n", lang_string);
334             for(i = 0; i < l_data.n_found; i++)
335                 MESSAGE("%s_%s - %04X; ", l_data.found_language[i], l_data.found_country[i], l_data.found_lang_id[i]);
336
337             MESSAGE("\nInstead of using first in the list, suggest to define\n"
338                     "your LANG environment variable like this: LANG=%s_%s\n",
339                     l_data.found_language[0], l_data.found_country[0]);
340         }
341     }
342 END:
343     TRACE("Returning %04X\n", l_data.found_lang_id[0]);
344     return l_data.found_lang_id[0];
345 }
346
347 /***********************************************************************
348  *              GetUserDefaultLangID (KERNEL32.@)
349  */
350 LANGID WINAPI GetUserDefaultLangID(void)
351 {
352         /* caching result, if defined from environment, which should (?) not change during a WINE session */
353         static  LANGID  userLCID = 0;
354
355         if (userLCID == 0)
356         {
357                 char buf[256];
358                 char *lang,*country,*charset,*dialect,*next;
359
360                 if (GetEnvironmentVariableA( "LANGUAGE", buf, sizeof(buf) )) goto ok;
361                 if (GetEnvironmentVariableA( "LANG", buf, sizeof(buf) )) goto ok;
362                 if (GetEnvironmentVariableA( "LC_ALL", buf, sizeof(buf) )) goto ok;
363                 if (GetEnvironmentVariableA( "LC_MESSAGES", buf, sizeof(buf) )) goto ok;
364                 if (GetEnvironmentVariableA( "LC_CTYPE", buf, sizeof(buf) )) goto ok;
365
366                 return userLCID = MAKELANGID( LANG_ENGLISH, SUBLANG_DEFAULT );
367
368         ok:
369                 if (!strcmp(buf,"POSIX") || !strcmp(buf,"C"))
370                     return userLCID = MAKELANGID( LANG_ENGLISH, SUBLANG_DEFAULT );
371
372                 lang=buf;
373
374                 do {
375                         next=strchr(lang,':'); if (next) *next++='\0';
376                         dialect=strchr(lang,'@'); if (dialect) *dialect++='\0';
377                         charset=strchr(lang,'.'); if (charset) *charset++='\0';
378                         country=strchr(lang,'_'); if (country) *country++='\0';
379
380                         userLCID = NLS_GetLanguageID(lang, country, charset, dialect);
381
382                         lang=next;
383                 } while (lang && !userLCID);
384
385                 if (!userLCID)
386                 {
387                     MESSAGE( "Warning: language '%s' not recognized, defaulting to English\n",
388                              buf );
389                     userLCID = MAKELANGID( LANG_ENGLISH, SUBLANG_DEFAULT );
390                 }
391         }
392         return userLCID;
393 }
394
395 /***********************************************************************
396  *              GetSystemDefaultLangID (KERNEL32.@)
397  */
398 LANGID WINAPI GetSystemDefaultLangID(void)
399 {
400         return GetUserDefaultLangID();
401 }
402
403 /******************************************************************************
404  *              ConvertDefaultLocale (KERNEL32.@)
405  */
406 LCID WINAPI ConvertDefaultLocale (LCID lcid)
407 {       switch (lcid)
408         {  case LOCALE_SYSTEM_DEFAULT:
409              return GetSystemDefaultLCID();
410            case LOCALE_USER_DEFAULT:
411              return GetUserDefaultLCID();
412            case LOCALE_NEUTRAL:
413              return MAKELCID (LANG_NEUTRAL, SUBLANG_NEUTRAL);
414         }
415         return MAKELANGID( PRIMARYLANGID(lcid), SUBLANG_NEUTRAL);
416 }
417
418 /* Enhanced version of LoadStringW.
419  * It takes LanguageId to find and load language dependant resources.
420  * Resource is copied as is: "binary" strings are not truncated.
421  * Return: length of resource + 1 to distinguish absent resources
422  * from the resources with zero length.
423  */
424 static INT NLS_LoadStringExW(HMODULE hModule, LANGID lang_id, UINT res_id, LPWSTR buffer, INT buflen)
425 {
426     HRSRC hrsrc;
427     HGLOBAL hmem;
428     WCHAR *p;
429     int string_num;
430     int i;
431
432     /* Replace SUBLANG_NEUTRAL by SUBLANG_DEFAULT */
433     if(SUBLANGID(lang_id) == SUBLANG_NEUTRAL)
434         lang_id = MAKELANGID(PRIMARYLANGID(lang_id), SUBLANG_DEFAULT);
435
436     hrsrc = FindResourceExW(hModule, RT_STRINGW, (LPCWSTR)((res_id >> 4) + 1), lang_id);
437
438     if(!hrsrc) return 0;
439     hmem = LoadResource(hModule, hrsrc);
440     if(!hmem) return 0;
441
442     p = LockResource(hmem);
443     string_num = res_id & 0x000f;
444     for(i = 0; i < string_num; i++)
445         p += *p + 1;
446
447     TRACE("strlen = %d\n", (int)*p );
448
449     if (buffer == NULL) return *p;
450     i = min(buflen - 1, *p);
451     if (i > 0) {
452         memcpy(buffer, p + 1, i * sizeof (WCHAR));
453         buffer[i] = (WCHAR) 0;
454     } else {
455         if (buflen > 1)
456             buffer[0] = (WCHAR) 0;
457     }
458
459     FreeResource(hmem);
460     TRACE("%s loaded!\n", debugstr_w(buffer));
461     return (i + 1);
462 }
463
464 /******************************************************************************
465  *              GetLocaleInfoA (KERNEL32.@)
466  *
467  * NOTES
468  *  LANG_NEUTRAL is equal to LOCALE_SYSTEM_DEFAULT
469  *
470  *  MS online documentation states that the string returned is NULL terminated
471  *  except for LOCALE_FONTSIGNATURE  which "will return a non-NULL
472  *  terminated string".
473  */
474 INT WINAPI GetLocaleInfoA(LCID lcid,LCTYPE LCType,LPSTR buf,INT len)
475 {
476     LPCSTR  retString = NULL;
477     int found = 0, i;
478     char    *pacKey;
479     char    acBuffer[128];
480     DWORD   dwBufferSize=128;
481     BOOL NoUserOverride;
482
483   TRACE("(lcid=0x%lx,lctype=0x%lx,%p,%x)\n",lcid,LCType,buf,len);
484
485   if (len && (! buf) ) {
486     SetLastError(ERROR_INSUFFICIENT_BUFFER);
487                 return 0;
488         }
489
490         if (lcid == LOCALE_NEUTRAL || lcid == LANG_SYSTEM_DEFAULT)
491         {
492             lcid = GetSystemDefaultLCID();
493         }
494         else if (lcid == LANG_USER_DEFAULT) /*0x800*/
495         {
496             lcid = GetUserDefaultLCID();
497         }
498
499     /* LOCALE_NOUSEROVERRIDE means: do not get user redefined settings
500        from the registry. Instead, use system default values. */
501     NoUserOverride = (LCType & LOCALE_NOUSEROVERRIDE) != 0;
502
503         LCType &= ~(LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP);
504
505     /* First, check if it's in the registry. */
506     /* All user customized values are stored in the registry by SetLocaleInfo */
507     if ( !NoUserOverride && (pacKey = GetLocaleSubkeyName(LCType)) )
508     {
509         char    acRealKey[128];
510         HKEY    hKey;
511
512         sprintf( acRealKey, "Control Panel\\International\\%s", pacKey );
513
514         if ( RegOpenKeyExA( HKEY_CURRENT_USER, acRealKey,
515                             0, KEY_READ, &hKey) == ERROR_SUCCESS )
516         {
517             if ( RegQueryValueExA( hKey, NULL, NULL, NULL, (LPBYTE)acBuffer,
518                                    &dwBufferSize ) == ERROR_SUCCESS )
519             {
520                 retString = acBuffer;
521                 found = 1;
522             }
523             RegCloseKey(hKey);
524         }
525     }
526
527     /* If not in the registry, get it from the NLS entries. */
528     if(!found) {
529         WCHAR wcBuffer[128];
530         int res_size;
531
532         /* check if language is registered in the kernel32 resources */
533         if((res_size = NLS_LoadStringExW(GetModuleHandleA("KERNEL32"), LANGIDFROMLCID(lcid),
534                 LCType, wcBuffer, sizeof(wcBuffer)/sizeof(wcBuffer[0])))) {
535             WideCharToMultiByte(CP_ACP, 0, wcBuffer, res_size, acBuffer, dwBufferSize, NULL, NULL);
536             retString = acBuffer;
537             found = 1;
538         }
539     }
540
541     /* if not found report a most descriptive error */
542     if(!found) {
543         retString=0;
544         /* If we are through all of this, retLen should not be zero anymore.
545            If it is, the value is not supported */
546         i=0;
547         while (locale_name2id[i].name!=NULL) {
548             if (LCType == locale_name2id[i].id) {
549                 retString = locale_name2id[i].name;
550                 break;
551             }
552             i++;
553         }
554         if(!retString)
555             FIXME("Unkown LC type %lX\n", LCType);
556         else
557             FIXME("'%s' is not defined for your language (%04X).\n"
558                 "Please define it in dlls/kernel/nls/YourLanguage.nls\n"
559                 "and submit patch for inclusion into the next Wine release.\n",
560                         retString, LOWORD(lcid));
561         SetLastError(ERROR_INVALID_PARAMETER);
562         return 0;
563     }
564
565     /* a FONTSIGNATURE is not a string, just 6 DWORDs  */
566     if (LCType == LOCALE_FONTSIGNATURE) {
567         if (len) {
568             len = (len < sizeof(FONTSIGNATURE)) ? len : sizeof(FONTSIGNATURE);
569             memcpy(buf, retString, len);
570             return len;
571         }
572         return sizeof(FONTSIGNATURE);
573     }
574     /* if len=0 return only the length, don't touch the buffer*/
575     if (len) {
576         /* Like Windows we copy len bytes to buffer and we check len after */
577         INT ret = strlen(retString) + 1;
578         memcpy( buf, retString, min(len, ret) );
579         return (len < ret) ? 0 : ret;
580     }
581     return strlen(retString)+1;
582 }
583
584 /******************************************************************************
585  *              GetLocaleInfoW (KERNEL32.@)
586  *
587  * NOTES
588  *  MS documentation states that len "specifies the size, in bytes (ANSI version)
589  *  or characters (Unicode version), of" wbuf. Thus the number returned is
590  *  the same between GetLocaleInfoW and GetLocaleInfoA.
591  */
592 INT WINAPI GetLocaleInfoW(LCID lcid,LCTYPE LCType,LPWSTR wbuf,INT len)
593 {       WORD wlen;
594         LPSTR abuf;
595
596         if (len && (! wbuf) )
597         { SetLastError(ERROR_INSUFFICIENT_BUFFER);
598           return 0;
599         }
600
601         abuf = (LPSTR)HeapAlloc(GetProcessHeap(),0,len);
602         wlen = GetLocaleInfoA(lcid, LCType, abuf, len);
603
604         if (wlen && len)        /* if len=0 return only the length*/
605             MultiByteToWideChar( CP_ACP, 0, abuf, -1, wbuf, len );
606
607         HeapFree(GetProcessHeap(),0,abuf);
608         return wlen;
609 }
610
611 /******************************************************************************
612  *
613  *              GetLocaleSubkeyName [helper function]
614  *
615  *          - For use with the registry.
616  *          - Gets the registry subkey name for a given lctype.
617  */
618 static char *GetLocaleSubkeyName( DWORD lctype )
619 {
620     char    *pacKey=NULL;
621
622     switch ( lctype )
623     {
624     /* These values are used by SetLocaleInfo and GetLocaleInfo, and
625      * the values are stored in the registry, confirmed under Windows,
626      * for the ones that actually assign pacKey. Cases that aren't finished
627      * have not been confirmed, so that must be done before they can be
628      * added.
629      */
630     case LOCALE_SDATE :        /* The date separator. */
631         pacKey = "sDate";
632         break;
633     case LOCALE_ICURRDIGITS:
634         pacKey = "iCurrDigits";
635         break;
636     case LOCALE_SDECIMAL :
637         pacKey = "sDecimal";
638         break;
639     case LOCALE_ICURRENCY:
640         pacKey = "iCurrency";
641         break;
642     case LOCALE_SGROUPING :
643         pacKey = "sGrouping";
644         break;
645     case LOCALE_IDIGITS:
646         pacKey = "iDigits";
647         break;
648     case LOCALE_SLIST :
649         pacKey = "sList";
650         break;
651     /* case LOCALE_ICALENDARTYPE: */
652     /* case LOCALE_IFIRSTDAYOFWEEK: */
653     /* case LOCALE_IFIRSTWEEKOFYEAR: */
654     /* case LOCALE_SYEARMONTH : */
655     /* case LOCALE_SPOSITIVESIGN : */
656     /* case LOCALE_IPAPERSIZE: */
657     /*     break; */
658     case LOCALE_SLONGDATE :
659         pacKey = "sLongDate";
660         break;
661     case LOCALE_SMONDECIMALSEP :
662         pacKey = "sMonDecimalSep";
663         break;
664     case LOCALE_SMONGROUPING:
665         pacKey = "sMonGrouping";
666         break;
667     case LOCALE_IMEASURE:
668         pacKey = "iMeasure";
669         break;
670     case LOCALE_SMONTHOUSANDSEP :
671         pacKey = "sMonThousandSep";
672         break;
673     case LOCALE_INEGCURR:
674         pacKey = "iNegCurr";
675         break;
676     case LOCALE_SNEGATIVESIGN :
677         pacKey = "sNegativeSign";
678         break;
679     case LOCALE_INEGNUMBER:
680         pacKey = "iNegNumber";
681         break;
682     case LOCALE_SSHORTDATE :
683         pacKey = "sShortDate";
684         break;
685     case LOCALE_ILDATE:        /* Long Date format ordering specifier. */
686         pacKey = "iLDate";
687         break;
688     case LOCALE_ILZERO:
689         pacKey = "iLZero";
690         break;
691     case LOCALE_ITLZERO:
692         pacKey = "iTLZero";
693         break;
694     case LOCALE_ITIME:        /* Time format specifier. */
695         pacKey = "iTime";
696         break;
697     case LOCALE_STHOUSAND :
698         pacKey = "sThousand";
699         break;
700     case LOCALE_S1159:        /* AM */
701         pacKey = "s1159";
702         break;
703     case LOCALE_STIME:
704         pacKey = "sTime";
705         break;
706     case LOCALE_S2359:        /* PM */
707         pacKey = "s2359";
708         break;
709     case LOCALE_STIMEFORMAT :
710         pacKey = "sTimeFormat";
711         break;
712     case LOCALE_SCURRENCY:
713         pacKey = "sCurrency";
714         break;
715
716     /* The following are not listed under MSDN as supported,
717      * but seem to be used and also stored in the registry.
718      */
719
720     case LOCALE_IDATE:
721         pacKey = "iDate";
722         break;
723     case LOCALE_SCOUNTRY:
724         pacKey = "sCountry";
725         break;
726     case LOCALE_ICOUNTRY:
727         pacKey = "iCountry";
728         break;
729     case LOCALE_SLANGUAGE:
730         pacKey = "sLanguage";
731         break;
732
733     default:
734         break;
735     }
736
737     return( pacKey );
738 }
739
740 /******************************************************************************
741  *              SetLocaleInfoA  [KERNEL32.@]
742  */
743 BOOL WINAPI SetLocaleInfoA(LCID lcid, LCTYPE lctype, LPCSTR data)
744 {
745     HKEY    hKey;
746     char    *pacKey;
747     char    acRealKey[128];
748
749     if ( (pacKey = GetLocaleSubkeyName(lctype)) )
750     {
751         sprintf( acRealKey, "Control Panel\\International\\%s", pacKey );
752         if ( RegCreateKeyA( HKEY_CURRENT_USER, acRealKey,
753                                &hKey ) == ERROR_SUCCESS )
754         {
755             if ( RegSetValueExA( hKey, NULL, 0, REG_SZ,
756                                  data, strlen(data)+1 ) != ERROR_SUCCESS )
757             {
758                 ERR("SetLocaleInfoA: %s did not work\n", pacKey );
759             }
760             RegCloseKey( hKey );
761         }
762     }
763     else
764     {
765     FIXME("(%ld,%ld,%s): stub\n",lcid,lctype,data);
766     }
767     return TRUE;
768 }
769
770 /******************************************************************************
771  *              IsValidLocale   [KERNEL32.@]
772  */
773 BOOL WINAPI IsValidLocale(LCID lcid,DWORD flags)
774 {
775     /* check if language is registered in the kernel32 resources */
776     if(!FindResourceExW(GetModuleHandleA("KERNEL32"), RT_STRINGW, (LPCWSTR)LOCALE_ILANGUAGE, LOWORD(lcid)))
777         return FALSE;
778     else
779         return TRUE;
780 }
781
782 static BOOL CALLBACK EnumResourceLanguagesProcW(HMODULE hModule, LPCWSTR type,
783                 LPCWSTR name, WORD LangID, LONG lParam)
784 {
785     CHAR bufA[20];
786     WCHAR bufW[20];
787     LOCALE_ENUMPROCW lpfnLocaleEnum = (LOCALE_ENUMPROCW)lParam;
788     sprintf(bufA, "%08X", (UINT)LangID);
789     MultiByteToWideChar(CP_ACP, 0, bufA, -1, bufW, sizeof(bufW)/sizeof(bufW[0]));
790     return lpfnLocaleEnum(bufW);
791 }
792
793 /******************************************************************************
794  *              EnumSystemLocalesW      [KERNEL32.@]
795  */
796 BOOL WINAPI EnumSystemLocalesW( LOCALE_ENUMPROCW lpfnLocaleEnum,
797                                     DWORD flags )
798 {
799     TRACE("(%p,%08lx)\n", lpfnLocaleEnum,flags);
800
801     EnumResourceLanguagesW(GetModuleHandleA("KERNEL32"), RT_STRINGW,
802             (LPCWSTR)LOCALE_ILANGUAGE, EnumResourceLanguagesProcW,
803             (LONG)lpfnLocaleEnum);
804
805     return TRUE;
806 }
807
808 static BOOL CALLBACK EnumResourceLanguagesProcA(HMODULE hModule, LPCSTR type,
809                 LPCSTR name, WORD LangID, LONG lParam)
810 {
811     CHAR bufA[20];
812     LOCALE_ENUMPROCA lpfnLocaleEnum = (LOCALE_ENUMPROCA)lParam;
813     sprintf(bufA, "%08X", (UINT)LangID);
814     return lpfnLocaleEnum(bufA);
815 }
816
817 /******************************************************************************
818  *              EnumSystemLocalesA      [KERNEL32.@]
819  */
820 BOOL WINAPI EnumSystemLocalesA(LOCALE_ENUMPROCA lpfnLocaleEnum,
821                                    DWORD flags)
822 {
823     TRACE("(%p,%08lx)\n", lpfnLocaleEnum,flags);
824
825     EnumResourceLanguagesA(GetModuleHandleA("KERNEL32"), RT_STRINGA,
826             (LPCSTR)LOCALE_ILANGUAGE, EnumResourceLanguagesProcA,
827             (LONG)lpfnLocaleEnum);
828
829     return TRUE;
830 }
831
832 /***********************************************************************
833  *           VerLanguageNameA              [KERNEL32.@]
834  */
835 DWORD WINAPI VerLanguageNameA( UINT wLang, LPSTR szLang, UINT nSize )
836 {
837     if(!szLang)
838         return 0;
839
840     return GetLocaleInfoA(MAKELCID(wLang, SORT_DEFAULT), LOCALE_SENGLANGUAGE, szLang, nSize);
841 }
842
843 /***********************************************************************
844  *           VerLanguageNameW              [KERNEL32.@]
845  */
846 DWORD WINAPI VerLanguageNameW( UINT wLang, LPWSTR szLang, UINT nSize )
847 {
848     if(!szLang)
849         return 0;
850
851     return GetLocaleInfoW(MAKELCID(wLang, SORT_DEFAULT), LOCALE_SENGLANGUAGE, szLang, nSize);
852 }
853
854
855 static const unsigned char LCM_Unicode_LUT[] = {
856   6      ,   3, /*   -   1 */
857   6      ,   4, /*   -   2 */
858   6      ,   5, /*   -   3 */
859   6      ,   6, /*   -   4 */
860   6      ,   7, /*   -   5 */
861   6      ,   8, /*   -   6 */
862   6      ,   9, /*   -   7 */
863   6      ,  10, /*   -   8 */
864   7      ,   5, /*   -   9 */
865   7      ,   6, /*   -  10 */
866   7      ,   7, /*   -  11 */
867   7      ,   8, /*   -  12 */
868   7      ,   9, /*   -  13 */
869   6      ,  11, /*   -  14 */
870   6      ,  12, /*   -  15 */
871   6      ,  13, /*   -  16 */
872   6      ,  14, /*   -  17 */
873   6      ,  15, /*   -  18 */
874   6      ,  16, /*   -  19 */
875   6      ,  17, /*   -  20 */
876   6      ,  18, /*   -  21 */
877   6      ,  19, /*   -  22 */
878   6      ,  20, /*   -  23 */
879   6      ,  21, /*   -  24 */
880   6      ,  22, /*   -  25 */
881   6      ,  23, /*   -  26 */
882   6      ,  24, /*   -  27 */
883   6      ,  25, /*   -  28 */
884   6      ,  26, /*   -  29 */
885   6      ,  27, /*   -  30 */
886   6      ,  28, /*   -  31 */
887   7      ,   2, /*   -  32 */
888   7      ,  28, /* ! -  33 */
889   7      ,  29, /* " -  34 */ /* " */
890   7      ,  31, /* # -  35 */
891   7      ,  33, /* $ -  36 */
892   7      ,  35, /* % -  37 */
893   7      ,  37, /* & -  38 */
894   6      , 128, /* ' -  39 */
895   7      ,  39, /* ( -  40 */
896   7      ,  42, /* ) -  41 */
897   7      ,  45, /* * -  42 */
898   8      ,   3, /* + -  43 */
899   7      ,  47, /* , -  44 */
900   6      , 130, /* - -  45 */
901   7      ,  51, /* . -  46 */
902   7      ,  53, /* / -  47 */
903  12      ,   3, /* 0 -  48 */
904  12      ,  33, /* 1 -  49 */
905  12      ,  51, /* 2 -  50 */
906  12      ,  70, /* 3 -  51 */
907  12      ,  88, /* 4 -  52 */
908  12      , 106, /* 5 -  53 */
909  12      , 125, /* 6 -  54 */
910  12      , 144, /* 7 -  55 */
911  12      , 162, /* 8 -  56 */
912  12      , 180, /* 9 -  57 */
913   7      ,  55, /* : -  58 */
914   7      ,  58, /* ; -  59 */
915   8      ,  14, /* < -  60 */
916   8      ,  18, /* = -  61 */
917   8      ,  20, /* > -  62 */
918   7      ,  60, /* ? -  63 */
919   7      ,  62, /* @ -  64 */
920  14      ,   2, /* A -  65 */
921  14      ,   9, /* B -  66 */
922  14      ,  10, /* C -  67 */
923  14      ,  26, /* D -  68 */
924  14      ,  33, /* E -  69 */
925  14      ,  35, /* F -  70 */
926  14      ,  37, /* G -  71 */
927  14      ,  44, /* H -  72 */
928  14      ,  50, /* I -  73 */
929  14      ,  53, /* J -  74 */
930  14      ,  54, /* K -  75 */
931  14      ,  72, /* L -  76 */
932  14      ,  81, /* M -  77 */
933  14      , 112, /* N -  78 */
934  14      , 124, /* O -  79 */
935  14      , 126, /* P -  80 */
936  14      , 137, /* Q -  81 */
937  14      , 138, /* R -  82 */
938  14      , 145, /* S -  83 */
939  14      , 153, /* T -  84 */
940  14      , 159, /* U -  85 */
941  14      , 162, /* V -  86 */
942  14      , 164, /* W -  87 */
943  14      , 166, /* X -  88 */
944  14      , 167, /* Y -  89 */
945  14      , 169, /* Z -  90 */
946   7      ,  63, /* [ -  91 */
947   7      ,  65, /* \ -  92 */
948   7      ,  66, /* ] -  93 */
949   7      ,  67, /* ^ -  94 */
950   7      ,  68, /* _ -  95 */
951   7      ,  72, /* ` -  96 */
952  14      ,   2, /* a -  97 */
953  14      ,   9, /* b -  98 */
954  14      ,  10, /* c -  99 */
955  14      ,  26, /* d - 100 */
956  14      ,  33, /* e - 101 */
957  14      ,  35, /* f - 102 */
958  14      ,  37, /* g - 103 */
959  14      ,  44, /* h - 104 */
960  14      ,  50, /* i - 105 */
961  14      ,  53, /* j - 106 */
962  14      ,  54, /* k - 107 */
963  14      ,  72, /* l - 108 */
964  14      ,  81, /* m - 109 */
965  14      , 112, /* n - 110 */
966  14      , 124, /* o - 111 */
967  14      , 126, /* p - 112 */
968  14      , 137, /* q - 113 */
969  14      , 138, /* r - 114 */
970  14      , 145, /* s - 115 */
971  14      , 153, /* t - 116 */
972  14      , 159, /* u - 117 */
973  14      , 162, /* v - 118 */
974  14      , 164, /* w - 119 */
975  14      , 166, /* x - 120 */
976  14      , 167, /* y - 121 */
977  14      , 169, /* z - 122 */
978   7      ,  74, /* { - 123 */
979   7      ,  76, /* | - 124 */
980   7      ,  78, /* } - 125 */
981   7      ,  80, /* ~ - 126 */
982   6      ,  29, /* \7f - 127 */
983   6      ,  30, /* \80 - 128 */
984   6      ,  31, /* \81 - 129 */
985   7      , 123, /* \82 - 130 */
986  14      ,  35, /* \83 - 131 */
987   7      , 127, /* \84 - 132 */
988  10      ,  21, /* \85 - 133 */
989  10      ,  15, /* \86 - 134 */
990  10      ,  16, /* \87 - 135 */
991   7      ,  67, /* \88 - 136 */
992  10      ,  22, /* \89 - 137 */
993  14      , 145, /* \8a - 138 */
994   7      , 136, /* \8b - 139 */
995  14 + 16 , 124, /* \8c - 140 */
996   6      ,  43, /* \8d - 141 */
997   6      ,  44, /* \8e - 142 */
998   6      ,  45, /* \8f - 143 */
999   6      ,  46, /* \90 - 144 */
1000   7      , 121, /* \91 - 145 */
1001   7      , 122, /* \92 - 146 */
1002   7      , 125, /* \93 - 147 */
1003   7      , 126, /* \94 - 148 */
1004  10      ,  17, /* \95 - 149 */
1005   6      , 137, /* \96 - 150 */
1006   6      , 139, /* \97 - 151 */
1007   7      ,  93, /* \98 - 152 */
1008  14      , 156, /* \99 - 153 */
1009  14      , 145, /* \9a - 154 */
1010   7      , 137, /* \9b - 155 */
1011  14 + 16 , 124, /* \9c - 156 */
1012   6      ,  59, /* \9d - 157 */
1013   6      ,  60, /* \9e - 158 */
1014  14      , 167, /* \9f - 159 */
1015   7      ,   4, /*   - 160 */
1016   7      ,  81, /* ¡ - 161 */
1017  10      ,   2, /* ¢ - 162 */
1018  10      ,   3, /* £ - 163 */
1019  10      ,   4, /* ¤ - 164 */
1020  10      ,   5, /* ¥ - 165 */
1021   7      ,  82, /* ¦ - 166 */
1022  10      ,   6, /* § - 167 */
1023   7      ,  83, /* ¨ - 168 */
1024  10      ,   7, /* © - 169 */
1025  14      ,   2, /* ª - 170 */
1026   8      ,  24, /* « - 171 */
1027  10      ,   8, /* ¬ - 172 */
1028   6      , 131, /* ­ - 173 */
1029  10      ,   9, /* ® - 174 */
1030   7      ,  84, /* ¯ - 175 */
1031  10      ,  10, /* ° - 176 */
1032   8      ,  23, /* ± - 177 */
1033  12      ,  51, /* ² - 178 */
1034  12      ,  70, /* ³ - 179 */
1035   7      ,  85, /* ´ - 180 */
1036  10      ,  11, /* µ - 181 */
1037  10      ,  12, /* ¶ - 182 */
1038  10      ,  13, /* · - 183 */
1039   7      ,  86, /* ¸ - 184 */
1040  12      ,  33, /* ¹ - 185 */
1041  14      , 124, /* º - 186 */
1042   8      ,  26, /* » - 187 */
1043  12      ,  21, /* ¼ - 188 */
1044  12      ,  25, /* ½ - 189 */
1045  12      ,  29, /* ¾ - 190 */
1046   7      ,  87, /* ¿ - 191 */
1047  14      ,   2, /* À - 192 */
1048  14      ,   2, /* Á - 193 */
1049  14      ,   2, /* Â - 194 */
1050  14      ,   2, /* Ã - 195 */
1051  14      ,   2, /* Ä - 196 */
1052  14      ,   2, /* Å - 197 */
1053  14 + 16 ,   2, /* Æ - 198 */
1054  14      ,  10, /* Ç - 199 */
1055  14      ,  33, /* È - 200 */
1056  14      ,  33, /* É - 201 */
1057  14      ,  33, /* Ê - 202 */
1058  14      ,  33, /* Ë - 203 */
1059  14      ,  50, /* Ì - 204 */
1060  14      ,  50, /* Í - 205 */
1061  14      ,  50, /* Î - 206 */
1062  14      ,  50, /* Ï - 207 */
1063  14      ,  26, /* Ð - 208 */
1064  14      , 112, /* Ñ - 209 */
1065  14      , 124, /* Ò - 210 */
1066  14      , 124, /* Ó - 211 */
1067  14      , 124, /* Ô - 212 */
1068  14      , 124, /* Õ - 213 */
1069  14      , 124, /* Ö - 214 */
1070   8      ,  28, /* × - 215 */
1071  14      , 124, /* Ø - 216 */
1072  14      , 159, /* Ù - 217 */
1073  14      , 159, /* Ú - 218 */
1074  14      , 159, /* Û - 219 */
1075  14      , 159, /* Ü - 220 */
1076  14      , 167, /* Ý - 221 */
1077  14 + 32 , 153, /* Þ - 222 */
1078  14 + 48 , 145, /* ß - 223 */
1079  14      ,   2, /* à - 224 */
1080  14      ,   2, /* á - 225 */
1081  14      ,   2, /* â - 226 */
1082  14      ,   2, /* ã - 227 */
1083  14      ,   2, /* ä - 228 */
1084  14      ,   2, /* å - 229 */
1085  14 + 16 ,   2, /* æ - 230 */
1086  14      ,  10, /* ç - 231 */
1087  14      ,  33, /* è - 232 */
1088  14      ,  33, /* é - 233 */
1089  14      ,  33, /* ê - 234 */
1090  14      ,  33, /* ë - 235 */
1091  14      ,  50, /* ì - 236 */
1092  14      ,  50, /* í - 237 */
1093  14      ,  50, /* î - 238 */
1094  14      ,  50, /* ï - 239 */
1095  14      ,  26, /* ð - 240 */
1096  14      , 112, /* ñ - 241 */
1097  14      , 124, /* ò - 242 */
1098  14      , 124, /* ó - 243 */
1099  14      , 124, /* ô - 244 */
1100  14      , 124, /* õ - 245 */
1101  14      , 124, /* ö - 246 */
1102   8      ,  29, /* ÷ - 247 */
1103  14      , 124, /* ø - 248 */
1104  14      , 159, /* ù - 249 */
1105  14      , 159, /* ú - 250 */
1106  14      , 159, /* û - 251 */
1107  14      , 159, /* ü - 252 */
1108  14      , 167, /* ý - 253 */
1109  14 + 32 , 153, /* þ - 254 */
1110  14      , 167  /* ÿ - 255 */ };
1111
1112 static const unsigned char LCM_Unicode_LUT_2[] = { 33, 44, 145 };
1113
1114 #define LCM_Diacritic_Start 131
1115
1116 static const unsigned char LCM_Diacritic_LUT[] = {
1117 123,  /* \83 - 131 */
1118   2,  /* \84 - 132 */
1119   2,  /* \85 - 133 */
1120   2,  /* \86 - 134 */
1121   2,  /* \87 - 135 */
1122   3,  /* \88 - 136 */
1123   2,  /* \89 - 137 */
1124  20,  /* \8a - 138 */
1125   2,  /* \8b - 139 */
1126   2,  /* \8c - 140 */
1127   2,  /* \8d - 141 */
1128   2,  /* \8e - 142 */
1129   2,  /* \8f - 143 */
1130   2,  /* \90 - 144 */
1131   2,  /* \91 - 145 */
1132   2,  /* \92 - 146 */
1133   2,  /* \93 - 147 */
1134   2,  /* \94 - 148 */
1135   2,  /* \95 - 149 */
1136   2,  /* \96 - 150 */
1137   2,  /* \97 - 151 */
1138   2,  /* \98 - 152 */
1139   2,  /* \99 - 153 */
1140  20,  /* \9a - 154 */
1141   2,  /* \9b - 155 */
1142   2,  /* \9c - 156 */
1143   2,  /* \9d - 157 */
1144   2,  /* \9e - 158 */
1145  19,  /* \9f - 159 */
1146   2,  /*   - 160 */
1147   2,  /* ¡ - 161 */
1148   2,  /* ¢ - 162 */
1149   2,  /* £ - 163 */
1150   2,  /* ¤ - 164 */
1151   2,  /* ¥ - 165 */
1152   2,  /* ¦ - 166 */
1153   2,  /* § - 167 */
1154   2,  /* ¨ - 168 */
1155   2,  /* © - 169 */
1156   3,  /* ª - 170 */
1157   2,  /* « - 171 */
1158   2,  /* ¬ - 172 */
1159   2,  /* ­ - 173 */
1160   2,  /* ® - 174 */
1161   2,  /* ¯ - 175 */
1162   2,  /* ° - 176 */
1163   2,  /* ± - 177 */
1164   2,  /* ² - 178 */
1165   2,  /* ³ - 179 */
1166   2,  /* ´ - 180 */
1167   2,  /* µ - 181 */
1168   2,  /* ¶ - 182 */
1169   2,  /* · - 183 */
1170   2,  /* ¸ - 184 */
1171   2,  /* ¹ - 185 */
1172   3,  /* º - 186 */
1173   2,  /* » - 187 */
1174   2,  /* ¼ - 188 */
1175   2,  /* ½ - 189 */
1176   2,  /* ¾ - 190 */
1177   2,  /* ¿ - 191 */
1178  15,  /* À - 192 */
1179  14,  /* Á - 193 */
1180  18,  /* Â - 194 */
1181  25,  /* Ã - 195 */
1182  19,  /* Ä - 196 */
1183  26,  /* Å - 197 */
1184   2,  /* Æ - 198 */
1185  28,  /* Ç - 199 */
1186  15,  /* È - 200 */
1187  14,  /* É - 201 */
1188  18,  /* Ê - 202 */
1189  19,  /* Ë - 203 */
1190  15,  /* Ì - 204 */
1191  14,  /* Í - 205 */
1192  18,  /* Î - 206 */
1193  19,  /* Ï - 207 */
1194 104,  /* Ð - 208 */
1195  25,  /* Ñ - 209 */
1196  15,  /* Ò - 210 */
1197  14,  /* Ó - 211 */
1198  18,  /* Ô - 212 */
1199  25,  /* Õ - 213 */
1200  19,  /* Ö - 214 */
1201   2,  /* × - 215 */
1202  33,  /* Ø - 216 */
1203  15,  /* Ù - 217 */
1204  14,  /* Ú - 218 */
1205  18,  /* Û - 219 */
1206  19,  /* Ü - 220 */
1207  14,  /* Ý - 221 */
1208   2,  /* Þ - 222 */
1209   2,  /* ß - 223 */
1210  15,  /* à - 224 */
1211  14,  /* á - 225 */
1212  18,  /* â - 226 */
1213  25,  /* ã - 227 */
1214  19,  /* ä - 228 */
1215  26,  /* å - 229 */
1216   2,  /* æ - 230 */
1217  28,  /* ç - 231 */
1218  15,  /* è - 232 */
1219  14,  /* é - 233 */
1220  18,  /* ê - 234 */
1221  19,  /* ë - 235 */
1222  15,  /* ì - 236 */
1223  14,  /* í - 237 */
1224  18,  /* î - 238 */
1225  19,  /* ï - 239 */
1226 104,  /* ð - 240 */
1227  25,  /* ñ - 241 */
1228  15,  /* ò - 242 */
1229  14,  /* ó - 243 */
1230  18,  /* ô - 244 */
1231  25,  /* õ - 245 */
1232  19,  /* ö - 246 */
1233   2,  /* ÷ - 247 */
1234  33,  /* ø - 248 */
1235  15,  /* ù - 249 */
1236  14,  /* ú - 250 */
1237  18,  /* û - 251 */
1238  19,  /* ü - 252 */
1239  14,  /* ý - 253 */
1240   2,  /* þ - 254 */
1241  19,  /* ÿ - 255 */
1242 } ;
1243
1244 /******************************************************************************
1245  * OLE2NLS_isPunctuation [INTERNAL]
1246  */
1247 static int OLE2NLS_isPunctuation(unsigned char c)
1248 {
1249   /* "punctuation character" in this context is a character which is
1250      considered "less important" during word sort comparison.
1251      See LCMapString implementation for the precise definition
1252      of "less important". */
1253
1254   return (LCM_Unicode_LUT[-2+2*c]==6);
1255 }
1256
1257 /******************************************************************************
1258  * OLE2NLS_isNonSpacing [INTERNAL]
1259  */
1260 static int OLE2NLS_isNonSpacing(unsigned char c)
1261 {
1262   /* This function is used by LCMapStringA.  Characters
1263      for which it returns true are ignored when mapping a
1264      string with NORM_IGNORENONSPACE */
1265   return ((c==136) || (c==170) || (c==186));
1266 }
1267
1268 /******************************************************************************
1269  * OLE2NLS_isSymbol [INTERNAL]
1270  * FIXME: handle current locale
1271  */
1272 static int OLE2NLS_isSymbol(unsigned char c)
1273 {
1274   /* This function is used by LCMapStringA.  Characters
1275      for which it returns true are ignored when mapping a
1276      string with NORM_IGNORESYMBOLS */
1277   return ( (c!=0) && !(isalpha(c) || isdigit(c)) );
1278 }
1279
1280 /******************************************************************************
1281  *              identity        [Internal]
1282  */
1283 static int identity(int c)
1284 {
1285   return c;
1286 }
1287
1288 /*************************************************************************
1289  *              LCMapStringA                [KERNEL32.@]
1290  *
1291  * Convert a string, or generate a sort key from it.
1292  *
1293  * If (mapflags & LCMAP_SORTKEY), the function will generate
1294  * a sort key for the source string.  Else, it will convert it
1295  * accordingly to the flags LCMAP_UPPERCASE, LCMAP_LOWERCASE,...
1296  *
1297  * RETURNS
1298  *    Error : 0.
1299  *    Success : length of the result string.
1300  *
1301  * NOTES
1302  *    If called with scrlen = -1, the function will compute the length
1303  *      of the 0-terminated string strsrc by itself.
1304  *
1305  *    If called with dstlen = 0, returns the buffer length that
1306  *      would be required.
1307  *
1308  *    NORM_IGNOREWIDTH means to compare ASCII and wide characters
1309  *    as if they are equal.
1310  *    In the only code page implemented so far, there may not be
1311  *    wide characters in strings passed to LCMapStringA,
1312  *    so there is nothing to be done for this flag.
1313  */
1314 INT WINAPI LCMapStringA(
1315         LCID lcid,      /* [in] locale identifier created with MAKELCID;
1316                                 LOCALE_SYSTEM_DEFAULT and LOCALE_USER_DEFAULT are
1317                                 predefined values. */
1318         DWORD mapflags, /* [in] flags */
1319         LPCSTR srcstr,  /* [in] source buffer */
1320         INT srclen,     /* [in] source length */
1321         LPSTR dststr,   /* [out] destination buffer */
1322         INT dstlen)     /* [in] destination buffer length */
1323 {
1324   int i;
1325
1326   TRACE("(0x%04lx,0x%08lx,%s,%d,%p,%d)\n",
1327         lcid,mapflags,debugstr_an(srcstr,srclen),srclen,dststr,dstlen);
1328
1329   if ( ((dstlen!=0) && (dststr==NULL)) || (srcstr==NULL) )
1330   {
1331     ERR("(src=%s,dest=%s): Invalid NULL string\n",
1332         debugstr_an(srcstr,srclen), dststr);
1333     SetLastError(ERROR_INVALID_PARAMETER);
1334     return 0;
1335   }
1336   if (srclen == -1)
1337     srclen = strlen(srcstr) + 1 ;    /* (include final '\0') */
1338
1339 #define LCMAPSTRINGA_SUPPORTED_FLAGS (LCMAP_UPPERCASE     | \
1340                                         LCMAP_LOWERCASE     | \
1341                                         LCMAP_SORTKEY       | \
1342                                         NORM_IGNORECASE     | \
1343                                         NORM_IGNORENONSPACE | \
1344                                         SORT_STRINGSORT     | \
1345                                         NORM_IGNOREWIDTH    | \
1346                                         NORM_IGNOREKANATYPE)
1347   /* FIXME: as long as we don't support Katakana nor Hiragana
1348    * characters, we can support NORM_IGNOREKANATYPE
1349    */
1350   if (mapflags & ~LCMAPSTRINGA_SUPPORTED_FLAGS)
1351   {
1352     FIXME("(0x%04lx,0x%08lx,%p,%d,%p,%d): "
1353           "unimplemented flags: 0x%08lx\n",
1354           lcid,
1355           mapflags,
1356           srcstr,
1357           srclen,
1358           dststr,
1359           dstlen,
1360           mapflags & ~LCMAPSTRINGA_SUPPORTED_FLAGS
1361      );
1362   }
1363
1364   if ( !(mapflags & LCMAP_SORTKEY) )
1365   {
1366     int i,j;
1367     int (*f)(int) = identity;
1368     int flag_ignorenonspace = mapflags & NORM_IGNORENONSPACE;
1369     int flag_ignoresymbols = mapflags & NORM_IGNORESYMBOLS;
1370
1371     if (flag_ignorenonspace || flag_ignoresymbols)
1372     {
1373       /* For some values of mapflags, the length of the resulting
1374          string is not known at this point.  Windows does map the string
1375          and does not SetLastError ERROR_INSUFFICIENT_BUFFER in
1376          these cases. */
1377       if (dstlen==0)
1378       {
1379         /* Compute required length */
1380         for (i=j=0; i < srclen; i++)
1381         {
1382           if ( !(flag_ignorenonspace && OLE2NLS_isNonSpacing(srcstr[i]))
1383                && !(flag_ignoresymbols && OLE2NLS_isSymbol(srcstr[i])) )
1384             j++;
1385         }
1386         return j;
1387       }
1388     }
1389     else
1390     {
1391       if (dstlen==0)
1392         return srclen;
1393       if (dstlen<srclen)
1394            {
1395              SetLastError(ERROR_INSUFFICIENT_BUFFER);
1396              return 0;
1397            }
1398     }
1399     if (mapflags & LCMAP_UPPERCASE)
1400       f = toupper;
1401     else if (mapflags & LCMAP_LOWERCASE)
1402       f = tolower;
1403     /* FIXME: NORM_IGNORENONSPACE requires another conversion */
1404     for (i=j=0; (i<srclen) && (j<dstlen) ; i++)
1405     {
1406       if ( !(flag_ignorenonspace && OLE2NLS_isNonSpacing(srcstr[i]))
1407            && !(flag_ignoresymbols && OLE2NLS_isSymbol(srcstr[i])) )
1408       {
1409         dststr[j] = (CHAR) f(srcstr[i]);
1410         j++;
1411       }
1412     }
1413     return j;
1414   }
1415
1416   /* FIXME: This function completely ignores the "lcid" parameter. */
1417   /* else ... (mapflags & LCMAP_SORTKEY)  */
1418   {
1419     int unicode_len=0;
1420     int case_len=0;
1421     int diacritic_len=0;
1422     int delayed_punctuation_len=0;
1423     char *case_component;
1424     char *diacritic_component;
1425     char *delayed_punctuation_component;
1426     int room,count;
1427     int flag_stringsort = mapflags & SORT_STRINGSORT;
1428
1429     /* compute how much room we will need */
1430     for (i=0;i<srclen;i++)
1431     {
1432       int ofs;
1433       unsigned char source_char = srcstr[i];
1434       if (source_char!='\0')
1435       {
1436         if (flag_stringsort || !OLE2NLS_isPunctuation(source_char))
1437         {
1438           unicode_len++;
1439           if ( LCM_Unicode_LUT[-2+2*source_char] & ~15 )
1440             unicode_len++;             /* double letter */
1441         }
1442         else
1443         {
1444           delayed_punctuation_len++;
1445         }
1446       }
1447
1448       if (isupper(source_char))
1449         case_len=unicode_len;
1450
1451       ofs = source_char - LCM_Diacritic_Start;
1452       if ((ofs>=0) && (LCM_Diacritic_LUT[ofs]!=2))
1453         diacritic_len=unicode_len;
1454     }
1455
1456     if (mapflags & NORM_IGNORECASE)
1457       case_len=0;
1458     if (mapflags & NORM_IGNORENONSPACE)
1459       diacritic_len=0;
1460
1461     room =  2 * unicode_len              /* "unicode" component */
1462       +     diacritic_len                /* "diacritic" component */
1463       +     case_len                     /* "case" component */
1464       +     4 * delayed_punctuation_len  /* punctuation in word sort mode */
1465       +     4                            /* four '\1' separators */
1466       +     1  ;                         /* terminal '\0' */
1467     if (dstlen==0)
1468       return room;
1469     else if (dstlen<room)
1470     {
1471       SetLastError(ERROR_INSUFFICIENT_BUFFER);
1472       return 0;
1473     }
1474 #if 0
1475     /*FIXME the Pointercheck should not be nessesary */
1476     if (IsBadWritePtr (dststr,room))
1477     { ERR("bad destination buffer (dststr) : %p,%d\n",dststr,dstlen);
1478       SetLastError(ERROR_INSUFFICIENT_BUFFER);
1479       return 0;
1480     }
1481 #endif
1482     /* locate each component, write separators */
1483     diacritic_component = dststr + 2*unicode_len ;
1484     *diacritic_component++ = '\1';
1485     case_component = diacritic_component + diacritic_len ;
1486     *case_component++ = '\1';
1487     delayed_punctuation_component = case_component + case_len ;
1488     *delayed_punctuation_component++ = '\1';
1489     *delayed_punctuation_component++ = '\1';
1490
1491     /* read source string char by char, write
1492        corresponding weight in each component. */
1493     for (i=0,count=0;i<srclen;i++)
1494     {
1495       unsigned char source_char=srcstr[i];
1496       if (source_char!='\0')
1497       {
1498         int type,longcode;
1499         type = LCM_Unicode_LUT[-2+2*source_char];
1500         longcode = type >> 4;
1501         type &= 15;
1502         if (!flag_stringsort && OLE2NLS_isPunctuation(source_char))
1503         {
1504           WORD encrypted_location = (1<<15) + 7 + 4*count;
1505           *delayed_punctuation_component++ = (unsigned char) (encrypted_location>>8);
1506           *delayed_punctuation_component++ = (unsigned char) (encrypted_location&255);
1507                      /* big-endian is used here because it lets string comparison be
1508                         compatible with numerical comparison */
1509
1510           *delayed_punctuation_component++ = type;
1511           *delayed_punctuation_component++ = LCM_Unicode_LUT[-1+2*source_char];
1512                      /* assumption : a punctuation character is never a
1513                         double or accented letter */
1514         }
1515         else
1516         {
1517           dststr[2*count] = type;
1518           dststr[2*count+1] = LCM_Unicode_LUT[-1+2*source_char];
1519           if (longcode)
1520           {
1521             if (count<case_len)
1522               case_component[count] = ( isupper(source_char) ? 18 : 2 ) ;
1523             if (count<diacritic_len)
1524               diacritic_component[count] = 2; /* assumption: a double letter
1525                                                  is never accented */
1526             count++;
1527
1528             dststr[2*count] = type;
1529             dststr[2*count+1] = *(LCM_Unicode_LUT_2 - 1 + longcode);
1530             /* 16 in the first column of LCM_Unicode_LUT  -->  longcode = 1
1531                32 in the first column of LCM_Unicode_LUT  -->  longcode = 2
1532                48 in the first column of LCM_Unicode_LUT  -->  longcode = 3 */
1533           }
1534
1535           if (count<case_len)
1536             case_component[count] = ( isupper(source_char) ? 18 : 2 ) ;
1537           if (count<diacritic_len)
1538           {
1539             int ofs = source_char - LCM_Diacritic_Start;
1540             diacritic_component[count] = (ofs>=0 ? LCM_Diacritic_LUT[ofs] : 2);
1541           }
1542           count++;
1543         }
1544       }
1545     }
1546     dststr[room-1] = '\0';
1547     return room;
1548   }
1549 }
1550
1551 /*************************************************************************
1552  *              LCMapStringW                [KERNEL32.@]
1553  *
1554  * Convert a string, or generate a sort key from it.
1555  *
1556  * NOTE
1557  *
1558  * See LCMapStringA for documentation
1559  */
1560 INT WINAPI LCMapStringW(
1561         LCID lcid,DWORD mapflags,LPCWSTR srcstr,INT srclen,LPWSTR dststr,
1562         INT dstlen)
1563 {
1564   int i;
1565
1566   TRACE("(0x%04lx,0x%08lx,%p,%d,%p,%d)\n",
1567                  lcid, mapflags, srcstr, srclen, dststr, dstlen);
1568
1569   if ( ((dstlen!=0) && (dststr==NULL)) || (srcstr==NULL) )
1570   {
1571     ERR("(src=%p,dst=%p): Invalid NULL string\n", srcstr, dststr);
1572     SetLastError(ERROR_INVALID_PARAMETER);
1573     return 0;
1574   }
1575   if (srclen==-1)
1576     srclen = strlenW(srcstr)+1;
1577
1578   /* FIXME: Both this function and it's companion LCMapStringA()
1579    * completely ignore the "lcid" parameter.  In place of the "lcid"
1580    * parameter the application must set the "LC_COLLATE" or "LC_ALL"
1581    * environment variable prior to invoking this function.  */
1582   if (mapflags & LCMAP_SORTKEY)
1583   {
1584       /* Possible values of LC_COLLATE. */
1585       char *lc_collate_default = 0; /* value prior to this function */
1586       char *lc_collate_env = 0;     /* value retrieved from the environment */
1587
1588       /* General purpose index into strings of any type. */
1589       int str_idx = 0;
1590
1591       /* Lengths of various strings where the length is measured in
1592        * wide characters for wide character strings and in bytes for
1593        * native strings.  The lengths include the NULL terminator.  */
1594       size_t returned_len    = 0;
1595       size_t src_native_len  = 0;
1596       size_t dst_native_len  = 0;
1597       size_t dststr_libc_len = 0;
1598
1599       /* Native (character set determined by locale) versions of the
1600        * strings source and destination strings.  */
1601       LPSTR src_native = 0;
1602       LPSTR dst_native = 0;
1603
1604       /* Version of the source and destination strings using the
1605        * "wchar_t" Unicode data type needed by various libc functions.  */
1606       wchar_t *srcstr_libc = 0;
1607       wchar_t *dststr_libc = 0;
1608
1609       if(!(srcstr_libc = (wchar_t *)HeapAlloc(GetProcessHeap(), 0,
1610                                        srclen * sizeof(wchar_t))))
1611       {
1612           ERR("Unable to allocate %d bytes for srcstr_libc\n",
1613               srclen * sizeof(wchar_t));
1614           SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1615           return 0;
1616       }
1617
1618       /* Convert source string to a libc Unicode string. */
1619       for(str_idx = 0; str_idx < srclen; str_idx++)
1620       {
1621           srcstr_libc[str_idx] = srcstr[str_idx];
1622       }
1623
1624       /* src_native should contain at most 3 bytes for each
1625        * multibyte characters in the original srcstr string.  */
1626       src_native_len = 3 * srclen;
1627       if(!(src_native = (LPSTR)HeapAlloc(GetProcessHeap(), 0,
1628                                           src_native_len)))
1629       {
1630           ERR("Unable to allocate %d bytes for src_native\n", src_native_len);
1631           SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1632           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1633           return 0;
1634       }
1635
1636       /* FIXME: Prior to to setting the LC_COLLATE locale category the
1637        * current value is backed up so it can be restored after the
1638        * last LC_COLLATE sensitive function returns.
1639        *
1640        * Even though the locale is adjusted for a minimum amount of
1641        * time a race condition exists where other threads may be
1642        * affected if they invoke LC_COLLATE sensitive functions.  One
1643        * possible solution is to wrap all LC_COLLATE sensitive Wine
1644        * functions, like LCMapStringW(), in a mutex.
1645        *
1646        * Another enhancement to the following would be to set the
1647        * LC_COLLATE locale category as a function of the "lcid"
1648        * parameter instead of the "LC_COLLATE" environment variable. */
1649       if(!(lc_collate_default = setlocale(LC_COLLATE, NULL)))
1650       {
1651           ERR("Unable to query the LC_COLLATE catagory\n");
1652           SetLastError(ERROR_INVALID_PARAMETER);
1653           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1654           if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1655           return 0;
1656       }
1657
1658       if(!(lc_collate_env = setlocale(LC_COLLATE, "")))
1659       {
1660           ERR("Unable to inherit the LC_COLLATE locale category from the "
1661               "environment.  The \"LC_COLLATE\" environment variable is "
1662               "\"%s\".\n", getenv("LC_COLLATE") ?
1663               getenv("LC_COLLATE") : "<unset>");
1664           SetLastError(ERROR_INVALID_PARAMETER);
1665           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1666           if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1667           return 0;
1668       }
1669
1670       TRACE("lc_collate_default = %s\n", lc_collate_default);
1671       TRACE("lc_collate_env = %s\n", lc_collate_env);
1672
1673       /* Convert the libc Unicode string to a native multibyte character
1674        * string. */
1675       returned_len = wcstombs(src_native, srcstr_libc, src_native_len) + 1;
1676       if(returned_len == 0)
1677       {
1678           ERR("wcstombs failed.  The string specified (%s) may contain an invalid character.\n",
1679               debugstr_w(srcstr));
1680           SetLastError(ERROR_INVALID_PARAMETER);
1681           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1682           if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1683           setlocale(LC_COLLATE, lc_collate_default);
1684           return 0;
1685       }
1686       else if(returned_len > src_native_len)
1687       {
1688           src_native[src_native_len - 1] = 0;
1689           ERR("wcstombs returned a string (%s) that was longer (%d bytes) "
1690               "than expected (%d bytes).\n", src_native, returned_len,
1691               dst_native_len);
1692
1693           /* Since this is an internal error I'm not sure what the correct
1694            * error code is.  */
1695           SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1696
1697           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1698           if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1699           setlocale(LC_COLLATE, lc_collate_default);
1700           return 0;
1701       }
1702       src_native_len = returned_len;
1703
1704       TRACE("src_native = %s  src_native_len = %d\n",
1705              src_native, src_native_len);
1706
1707       /* dst_native seems to contain at most 4 bytes for each byte in
1708        * the original src_native string.  Change if need be since this
1709        * isn't documented by the strxfrm() man page. */
1710       dst_native_len = 4 * src_native_len;
1711       if(!(dst_native = (LPSTR)HeapAlloc(GetProcessHeap(), 0, dst_native_len)))
1712       {
1713           ERR("Unable to allocate %d bytes for dst_native\n", dst_native_len);
1714           SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1715           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1716           if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1717           setlocale(LC_COLLATE, lc_collate_default);
1718           return 0;
1719       }
1720
1721       /* The actual translation is done by the following call to
1722        * strxfrm().  The surrounding code could have been simplified
1723        * by calling wcsxfrm() instead except that wcsxfrm() is not
1724        * available on older Linux systems (RedHat 4.1 with
1725        * libc-5.3.12-17).
1726        *
1727        * Also, it is possible that the translation could be done by
1728        * various tables as it is done in LCMapStringA().  However, I'm
1729        * not sure what those tables are. */
1730       returned_len = strxfrm(dst_native, src_native, dst_native_len) + 1;
1731
1732       if(returned_len > dst_native_len)
1733       {
1734           dst_native[dst_native_len - 1] = 0;
1735           ERR("strxfrm returned a string (%s) that was longer (%d bytes) "
1736               "than expected (%d bytes).\n", dst_native, returned_len,
1737               dst_native_len);
1738
1739           /* Since this is an internal error I'm not sure what the correct
1740            * error code is.  */
1741           SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1742
1743           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1744           if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1745           if(dst_native) HeapFree(GetProcessHeap(), 0, dst_native);
1746           setlocale(LC_COLLATE, lc_collate_default);
1747           return 0;
1748       }
1749       dst_native_len = returned_len;
1750
1751       TRACE("dst_native = %s  dst_native_len = %d\n",
1752              dst_native, dst_native_len);
1753
1754       dststr_libc_len = dst_native_len;
1755       if(!(dststr_libc = (wchar_t *)HeapAlloc(GetProcessHeap(), 0,
1756                                        dststr_libc_len * sizeof(wchar_t))))
1757       {
1758           ERR("Unable to allocate %d bytes for dststr_libc\n",
1759               dststr_libc_len * sizeof(wchar_t));
1760           SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1761           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1762           if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1763           if(dst_native) HeapFree(GetProcessHeap(), 0, dst_native);
1764           setlocale(LC_COLLATE, lc_collate_default);
1765           return 0;
1766       }
1767
1768       /* Convert the native multibyte string to a libc Unicode string. */
1769       returned_len = mbstowcs(dststr_libc, dst_native, dst_native_len) + 1;
1770
1771       /* Restore LC_COLLATE now that the last LC_COLLATE sensitive
1772        * function has returned. */
1773       setlocale(LC_COLLATE, lc_collate_default);
1774
1775       if(returned_len == 0)
1776       {
1777           ERR("mbstowcs failed.  The native version of the translated string "
1778               "(%s) may contain an invalid character.\n", dst_native);
1779           SetLastError(ERROR_INVALID_PARAMETER);
1780           if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1781           if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1782           if(dst_native) HeapFree(GetProcessHeap(), 0, dst_native);
1783           if(dststr_libc) HeapFree(GetProcessHeap(), 0, dststr_libc);
1784           return 0;
1785       }
1786       if(dstlen)
1787       {
1788           if(returned_len > dstlen)
1789           {
1790               ERR("mbstowcs returned a string that was longer (%d chars) "
1791                   "than the buffer provided (%d chars).\n", returned_len,
1792                   dstlen);
1793               SetLastError(ERROR_INSUFFICIENT_BUFFER);
1794               if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1795               if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1796               if(dst_native) HeapFree(GetProcessHeap(), 0, dst_native);
1797               if(dststr_libc) HeapFree(GetProcessHeap(), 0, dststr_libc);
1798               return 0;
1799           }
1800           dstlen = returned_len;
1801
1802           /* Convert a libc Unicode string to the destination string. */
1803           for(str_idx = 0; str_idx < dstlen; str_idx++)
1804           {
1805               dststr[str_idx] = dststr_libc[str_idx];
1806           }
1807           TRACE("1st 4 int sized chunks of dststr = %x %x %x %x\n",
1808                          *(((int *)dststr) + 0),
1809                          *(((int *)dststr) + 1),
1810                          *(((int *)dststr) + 2),
1811                          *(((int *)dststr) + 3));
1812       }
1813       else
1814       {
1815           dstlen = returned_len;
1816       }
1817       TRACE("dstlen (return) = %d\n", dstlen);
1818       if(srcstr_libc) HeapFree(GetProcessHeap(), 0, srcstr_libc);
1819       if(src_native) HeapFree(GetProcessHeap(), 0, src_native);
1820       if(dst_native) HeapFree(GetProcessHeap(), 0, dst_native);
1821       if(dststr_libc) HeapFree(GetProcessHeap(), 0, dststr_libc);
1822       return dstlen;
1823   }
1824   else
1825   {
1826     int (*f)(int)=identity;
1827
1828     if (dstlen==0)
1829         return srclen;
1830     if (dstlen<srclen)
1831     {
1832         SetLastError(ERROR_INSUFFICIENT_BUFFER);
1833         return 0;
1834     }
1835
1836     if (mapflags & LCMAP_UPPERCASE)
1837       f = toupper;
1838     else if (mapflags & LCMAP_LOWERCASE)
1839       f = tolower;
1840     for (i=0; i < srclen; i++)
1841       dststr[i] = (WCHAR) f(srcstr[i]);
1842     return srclen;
1843   }
1844 }
1845
1846
1847 /***********************************************************************
1848  *           OLE2NLS_EstimateMappingLength
1849  *
1850  * Estimates the number of characters required to hold the string
1851  * computed by LCMapStringA.
1852  *
1853  * The size is always over-estimated, with a fixed limit on the
1854  * amount of estimation error.
1855  *
1856  * Note that len == -1 is not permitted.
1857  */
1858 static inline int OLE2NLS_EstimateMappingLength(LCID lcid, DWORD dwMapFlags,
1859                                                 LPCSTR str, DWORD len)
1860 {
1861     /* Estimate only for small strings to keep the estimation error from
1862      * becoming too large. */
1863     if (len < 128) return len * 8 + 5;
1864     else return LCMapStringA(lcid, dwMapFlags, str, len, NULL, 0);
1865 }
1866
1867 /******************************************************************************
1868  *              CompareStringA  [KERNEL32.@]
1869  * Compares two strings using locale
1870  *
1871  * RETURNS
1872  *
1873  * success: CSTR_LESS_THAN, CSTR_EQUAL, CSTR_GREATER_THAN
1874  * failure: 0
1875  *
1876  * NOTES
1877  *
1878  * Defaults to a word sort, but uses a string sort if
1879  * SORT_STRINGSORT is set.
1880  * Calls SetLastError for ERROR_INVALID_FLAGS, ERROR_INVALID_PARAMETER.
1881  *
1882  * BUGS
1883  *
1884  * This implementation ignores the locale
1885  *
1886  * FIXME
1887  *
1888  * Quite inefficient.
1889  */
1890 int WINAPI CompareStringA(
1891     LCID lcid,      /* [in] locale ID */
1892     DWORD fdwStyle, /* [in] comparison-style options */
1893     LPCSTR s1,      /* [in] first string */
1894     int l1,         /* [in] length of first string */
1895     LPCSTR s2,      /* [in] second string */
1896     int l2)         /* [in] length of second string */
1897 {
1898   int mapstring_flags;
1899   int len1,len2;
1900   int result;
1901   LPSTR sk1,sk2;
1902   TRACE("%s and %s\n",
1903         debugstr_an (s1,l1), debugstr_an (s2,l2));
1904
1905   if ( (s1==NULL) || (s2==NULL) )
1906   {
1907     ERR("(s1=%s,s2=%s): Invalid NULL string\n",
1908         debugstr_an(s1,l1), debugstr_an(s2,l2));
1909     SetLastError(ERROR_INVALID_PARAMETER);
1910     return 0;
1911   }
1912
1913   if(fdwStyle & NORM_IGNORESYMBOLS)
1914     FIXME("IGNORESYMBOLS not supported\n");
1915
1916   if (l1 == -1) l1 = strlen(s1);
1917   if (l2 == -1) l2 = strlen(s2);
1918
1919   mapstring_flags = LCMAP_SORTKEY | fdwStyle ;
1920   len1 = OLE2NLS_EstimateMappingLength(lcid, mapstring_flags, s1, l1);
1921   len2 = OLE2NLS_EstimateMappingLength(lcid, mapstring_flags, s2, l2);
1922
1923   if ((len1==0)||(len2==0))
1924     return 0;     /* something wrong happened */
1925
1926   sk1 = (LPSTR)HeapAlloc(GetProcessHeap(), 0, len1 + len2);
1927   sk2 = sk1 + len1;
1928   if ( (!LCMapStringA(lcid,mapstring_flags,s1,l1,sk1,len1))
1929          || (!LCMapStringA(lcid,mapstring_flags,s2,l2,sk2,len2)) )
1930   {
1931     ERR("Bug in LCmapStringA.\n");
1932     result = 0;
1933   }
1934   else
1935   {
1936     /* strcmp doesn't necessarily return -1, 0, or 1 */
1937     result = strcmp(sk1,sk2);
1938   }
1939   HeapFree(GetProcessHeap(),0,sk1);
1940
1941   if (result < 0)
1942     return 1;
1943   if (result == 0)
1944     return 2;
1945
1946   /* must be greater, if we reach this point */
1947   return 3;
1948 }
1949
1950 /******************************************************************************
1951  *              CompareStringW  [KERNEL32.@]
1952  * This implementation ignores the locale
1953  * FIXME :  Does only string sort.  Should
1954  * be reimplemented the same way as CompareStringA.
1955  */
1956 int WINAPI CompareStringW(LCID lcid, DWORD fdwStyle,
1957                           LPCWSTR s1, int l1, LPCWSTR s2, int l2)
1958 {
1959         int len,ret;
1960         if(fdwStyle & NORM_IGNORENONSPACE)
1961                 FIXME("IGNORENONSPACE not supported\n");
1962         if(fdwStyle & NORM_IGNORESYMBOLS)
1963                 FIXME("IGNORESYMBOLS not supported\n");
1964
1965         /* Is strcmp defaulting to string sort or to word sort?? */
1966         /* FIXME: Handle NORM_STRINGSORT */
1967         l1 = (l1==-1)?strlenW(s1):l1;
1968         l2 = (l2==-1)?strlenW(s2):l2;
1969         len = l1<l2 ? l1:l2;
1970         ret = (fdwStyle & NORM_IGNORECASE) ? strncmpiW(s1,s2,len) : strncmpW(s1,s2,len);
1971         /* not equal, return 1 or 3 */
1972         if(ret!=0) {
1973                 /* need to translate result */
1974                 return ((int)ret < 0) ? 1 : 3;
1975         }
1976         /* same len, return 2 */
1977         if(l1==l2) return 2;
1978         /* the longer one is lexically greater */
1979         return (l1<l2)? 1 : 3;
1980 }
1981
1982 /******************************************************************************
1983  *              OLE_GetFormatA  [Internal]
1984  *
1985  * FIXME
1986  *    If datelen == 0, it should return the reguired string length.
1987  *
1988  This function implements stuff for GetDateFormat() and
1989  GetTimeFormat().
1990
1991   d    single-digit (no leading zero) day (of month)
1992   dd   two-digit day (of month)
1993   ddd  short day-of-week name
1994   dddd long day-of-week name
1995   M    single-digit month
1996   MM   two-digit month
1997   MMM  short month name
1998   MMMM full month name
1999   y    two-digit year, no leading 0
2000   yy   two-digit year
2001   yyyy four-digit year
2002   gg   era string
2003   h    hours with no leading zero (12-hour)
2004   hh   hours with full two digits
2005   H    hours with no leading zero (24-hour)
2006   HH   hours with full two digits
2007   m    minutes with no leading zero
2008   mm   minutes with full two digits
2009   s    seconds with no leading zero
2010   ss   seconds with full two digits
2011   t    time marker (A or P)
2012   tt   time marker (AM, PM)
2013   ''   used to quote literal characters
2014   ''   (within a quoted string) indicates a literal '
2015
2016  These functions REQUIRE valid locale, date,  and format.
2017  */
2018 static INT OLE_GetFormatA(LCID locale,
2019                             DWORD flags,
2020                             DWORD tflags,
2021                             const SYSTEMTIME* xtime,
2022                             LPCSTR _format,     /*in*/
2023                             LPSTR date,         /*out*/
2024                             INT datelen)
2025 {
2026    INT inpos, outpos;
2027    int count, type, inquote, Overflow;
2028    char buf[40];
2029    char format[40];
2030    char * pos;
2031    int buflen;
2032
2033    const char * _dgfmt[] = { "%d", "%02d" };
2034    const char ** dgfmt = _dgfmt - 1;
2035
2036    /* report, for debugging */
2037    TRACE("(0x%lx,0x%lx, 0x%lx, time(y=%d m=%d wd=%d d=%d,h=%d,m=%d,s=%d), fmt=%p \'%s\' , %p, len=%d)\n",
2038          locale, flags, tflags,
2039          xtime->wYear,xtime->wMonth,xtime->wDayOfWeek,xtime->wDay, xtime->wHour, xtime->wMinute, xtime->wSecond,
2040          _format, _format, date, datelen);
2041
2042    if(datelen == 0) {
2043      FIXME("datelen = 0, returning 255\n");
2044      return 255;
2045    }
2046
2047    /* initalize state variables and output buffer */
2048    inpos = outpos = 0;
2049    count = 0; inquote = 0; Overflow = 0;
2050    type = '\0';
2051    date[0] = buf[0] = '\0';
2052
2053    strcpy(format,_format);
2054
2055    /* alter the formatstring, while it works for all languages now in wine
2056    its possible that it fails when the time looks like ss:mm:hh as example*/
2057    if (tflags & (TIME_NOMINUTESORSECONDS))
2058    { if ((pos = strstr ( format, ":mm")))
2059      { memcpy ( pos, pos+3, strlen(format)-(pos-format)-2 );
2060      }
2061    }
2062    if (tflags & (TIME_NOSECONDS))
2063    { if ((pos = strstr ( format, ":ss")))
2064      { memcpy ( pos, pos+3, strlen(format)-(pos-format)-2 );
2065      }
2066    }
2067
2068    for (inpos = 0;; inpos++) {
2069       /* TRACE("STATE inpos=%2d outpos=%2d count=%d inquote=%d type=%c buf,date = %c,%c\n", inpos, outpos, count, inquote, type, buf[inpos], date[outpos]); */
2070       if (inquote) {
2071          if (format[inpos] == '\'') {
2072             if (format[inpos+1] == '\'') {
2073                inpos += 1;
2074                date[outpos++] = '\'';
2075             } else {
2076                inquote = 0;
2077                continue; /* we did nothing to the output */
2078             }
2079          } else if (format[inpos] == '\0') {
2080             date[outpos++] = '\0';
2081             if (outpos > datelen) Overflow = 1;
2082             break;
2083          } else {
2084             date[outpos++] = format[inpos];
2085             if (outpos > datelen) {
2086                Overflow = 1;
2087                date[outpos-1] = '\0'; /* this is the last place where
2088                                          it's safe to write */
2089                break;
2090             }
2091          }
2092       } else if (  (count && (format[inpos] != type))
2093                    || count == 4
2094                    || (count == 2 && strchr("ghHmst", type)) ) {
2095             if (type == 'h' && (tflags & TIME_FORCE24HOURFORMAT)) type= 'H';
2096             if (type == 'd') {
2097                if (count == 4) {
2098                   GetLocaleInfoA(locale,
2099                                    LOCALE_SDAYNAME1
2100                                    + (xtime->wDayOfWeek+6)%7,
2101                                    buf, sizeof(buf));
2102                } else if (count == 3) {
2103                            GetLocaleInfoA(locale,
2104                                             LOCALE_SABBREVDAYNAME1
2105                                             + (xtime->wDayOfWeek+6)%7,
2106                                             buf, sizeof(buf));
2107                       } else {
2108                   sprintf(buf, dgfmt[count], xtime->wDay);
2109                }
2110             } else if (type == 'M') {
2111                if (count == 3) {
2112                   GetLocaleInfoA(locale,
2113                                    LOCALE_SABBREVMONTHNAME1
2114                                    + xtime->wMonth - 1,
2115                                    buf, sizeof(buf));
2116                } else if (count == 4) {
2117                   GetLocaleInfoA(locale,
2118                                    LOCALE_SMONTHNAME1
2119                                    + xtime->wMonth - 1,
2120                                    buf, sizeof(buf));
2121                  } else {
2122                   sprintf(buf, dgfmt[count], xtime->wMonth);
2123                }
2124             } else if (type == 'y') {
2125                if (count == 4) {
2126                       sprintf(buf, "%d", xtime->wYear);
2127                } else if (count == 3) {
2128                   strcpy(buf, "yyy");
2129                   WARN("unknown format, c=%c, n=%d\n",  type, count);
2130                  } else {
2131                   sprintf(buf, dgfmt[count], xtime->wYear % 100);
2132                }
2133             } else if (type == 'g') {
2134                if        (count == 2) {
2135                   FIXME("LOCALE_ICALENDARTYPE unimp.\n");
2136                   strcpy(buf, "AD");
2137             } else {
2138                   strcpy(buf, "g");
2139                   WARN("unknown format, c=%c, n=%d\n", type, count);
2140                }
2141             } else if (type == 'h') {
2142                /* gives us hours 1:00 -- 12:00 */
2143                sprintf(buf, dgfmt[count], (xtime->wHour-1)%12 +1);
2144             } else if (type == 'H') {
2145                /* 24-hour time */
2146                sprintf(buf, dgfmt[count], xtime->wHour);
2147             } else if ( type == 'm') {
2148                sprintf(buf, dgfmt[count], xtime->wMinute);
2149             } else if ( type == 's') {
2150                sprintf(buf, dgfmt[count], xtime->wSecond);
2151             } else if (type == 't') {
2152                if ((tflags & TIME_NOTIMEMARKER))
2153                   buf[0]='\0';
2154                else if (count == 1) {
2155                   sprintf(buf, "%c", (xtime->wHour < 12) ? 'A' : 'P');
2156                } else if (count == 2) {
2157                  /* sprintf(buf, "%s", (xtime->wHour < 12) ? "AM" : "PM"); */
2158                   GetLocaleInfoA(locale,
2159                            (xtime->wHour<12)
2160                            ? LOCALE_S1159 : LOCALE_S2359,
2161                            buf, sizeof(buf));
2162                }
2163             };
2164
2165             /* we need to check the next char in the format string
2166                again, no matter what happened */
2167             inpos--;
2168
2169             /* add the contents of buf to the output */
2170             buflen = strlen(buf);
2171             if (outpos + buflen < datelen) {
2172                date[outpos] = '\0'; /* for strcat to hook onto */
2173                  strcat(date, buf);
2174                outpos += buflen;
2175             } else {
2176                date[outpos] = '\0';
2177                strncat(date, buf, datelen - outpos);
2178                  date[datelen - 1] = '\0';
2179                  SetLastError(ERROR_INSUFFICIENT_BUFFER);
2180                WARN("insufficient buffer\n");
2181                  return 0;
2182             }
2183
2184             /* reset the variables we used to keep track of this item */
2185             count = 0;
2186             type = '\0';
2187          } else if (format[inpos] == '\0') {
2188             /* we can't check for this at the loop-head, because
2189                that breaks the printing of the last format-item */
2190             date[outpos] = '\0';
2191             break;
2192          } else if (count) {
2193             /* continuing a code for an item */
2194             count +=1;
2195             continue;
2196          } else if (strchr("hHmstyMdg", format[inpos])) {
2197             type = format[inpos];
2198             count = 1;
2199             continue;
2200          } else if (format[inpos] == '\'') {
2201             inquote = 1;
2202             continue;
2203        } else {
2204             date[outpos++] = format[inpos];
2205          }
2206       /* now deal with a possible buffer overflow */
2207       if (outpos >= datelen) {
2208        date[datelen - 1] = '\0';
2209        SetLastError(ERROR_INSUFFICIENT_BUFFER);
2210        return 0;
2211       }
2212    }
2213
2214    if (Overflow) {
2215       SetLastError(ERROR_INSUFFICIENT_BUFFER);
2216    };
2217
2218    /* finish it off with a string terminator */
2219    outpos++;
2220    /* sanity check */
2221    if (outpos > datelen-1) outpos = datelen-1;
2222    date[outpos] = '\0';
2223
2224    TRACE("returns string '%s', len %d\n", date, outpos);
2225    return outpos;
2226 }
2227
2228 /******************************************************************************
2229  * OLE_GetFormatW [INTERNAL]
2230  */
2231 static INT OLE_GetFormatW(LCID locale, DWORD flags, DWORD tflags,
2232                             const SYSTEMTIME* xtime,
2233                             LPCWSTR format,
2234                             LPWSTR output, INT outlen)
2235 {
2236    INT   inpos, outpos;
2237    int     count, type=0, inquote;
2238    int     Overflow; /* loop check */
2239    char    tmp[16];
2240    WCHAR   buf[40];
2241    int     buflen=0;
2242    WCHAR   arg0[] = {0}, arg1[] = {'%','d',0};
2243    WCHAR   arg2[] = {'%','0','2','d',0};
2244    WCHAR  *argarr[3];
2245    int     datevars=0, timevars=0;
2246
2247    argarr[0] = arg0;
2248    argarr[1] = arg1;
2249    argarr[2] = arg2;
2250
2251    /* make a debug report */
2252    TRACE("args: 0x%lx, 0x%lx, 0x%lx, time(d=%d,h=%d,m=%d,s=%d), fmt:%s (at %p), "
2253               "%p with max len %d\n",
2254          locale, flags, tflags,
2255          xtime->wDay, xtime->wHour, xtime->wMinute, xtime->wSecond,
2256          debugstr_w(format), format, output, outlen);
2257
2258    if(outlen == 0) {
2259      FIXME("outlen = 0, returning 255\n");
2260      return 255;
2261    }
2262
2263    /* initialize state variables */
2264    inpos = outpos = 0;
2265    count = 0;
2266    inquote = Overflow = 0;
2267    /* this is really just a sanity check */
2268    output[0] = buf[0] = 0;
2269
2270    /* this loop is the core of the function */
2271    for (inpos = 0; /* we have several break points */ ; inpos++) {
2272       if (inquote) {
2273          if (format[inpos] == (WCHAR) '\'') {
2274             if (format[inpos+1] == '\'') {
2275                inpos++;
2276                output[outpos++] = '\'';
2277             } else {
2278                inquote = 0;
2279                continue;
2280             }
2281          } else if (format[inpos] == 0) {
2282             output[outpos++] = 0;
2283             if (outpos > outlen) Overflow = 1;
2284             break;  /*  normal exit (within a quote) */
2285          } else {
2286             output[outpos++] = format[inpos]; /* copy input */
2287             if (outpos > outlen) {
2288                Overflow = 1;
2289                output[outpos-1] = 0;
2290                break;
2291             }
2292          }
2293       } else if (  (count && (format[inpos] != type))
2294                    || ( (count==4 && type =='y') ||
2295                         (count==4 && type =='M') ||
2296                         (count==4 && type =='d') ||
2297                         (count==2 && type =='g') ||
2298                         (count==2 && type =='h') ||
2299                         (count==2 && type =='H') ||
2300                         (count==2 && type =='m') ||
2301                         (count==2 && type =='s') ||
2302                         (count==2 && type =='t') )  ) {
2303           switch(type)
2304           {
2305           case 'd':
2306             if        (count == 4) {
2307                GetLocaleInfoW(locale,
2308                              LOCALE_SDAYNAME1 + (xtime->wDayOfWeek +6)%7,
2309                              buf, sizeof(buf)/sizeof(WCHAR) );
2310             } else if (count == 3) {
2311                GetLocaleInfoW(locale,
2312                                 LOCALE_SABBREVDAYNAME1 +
2313                                 (xtime->wDayOfWeek +6)%7,
2314                                 buf, sizeof(buf)/sizeof(WCHAR) );
2315             } else {
2316                 sprintf( tmp, "%.*d", count, xtime->wDay );
2317                 MultiByteToWideChar( CP_ACP, 0, tmp, -1, buf, sizeof(buf)/sizeof(WCHAR) );
2318             }
2319             break;
2320
2321           case 'M':
2322             if        (count == 4) {
2323                GetLocaleInfoW(locale,  LOCALE_SMONTHNAME1 +
2324                                 xtime->wMonth -1, buf,
2325                                 sizeof(buf)/sizeof(WCHAR) );
2326             } else if (count == 3) {
2327                GetLocaleInfoW(locale,  LOCALE_SABBREVMONTHNAME1 +
2328                                 xtime->wMonth -1, buf,
2329                                 sizeof(buf)/sizeof(WCHAR) );
2330             } else {
2331                 sprintf( tmp, "%.*d", count, xtime->wMonth );
2332                 MultiByteToWideChar( CP_ACP, 0, tmp, -1, buf, sizeof(buf)/sizeof(WCHAR) );
2333             }
2334             break;
2335           case 'y':
2336             if        (count == 4) {
2337                 sprintf( tmp, "%d", xtime->wYear );
2338             } else if (count == 3) {
2339                 strcpy( tmp, "yyy" );
2340             } else {
2341                 sprintf( tmp, "%.*d", count, xtime->wYear % 100 );
2342             }
2343             MultiByteToWideChar( CP_ACP, 0, tmp, -1, buf, sizeof(buf)/sizeof(WCHAR) );
2344             break;
2345
2346           case 'g':
2347             if        (count == 2) {
2348                FIXME("LOCALE_ICALENDARTYPE unimplemented\n");
2349                strcpy( tmp, "AD" );
2350             } else {
2351                /* Win API sez we copy it verbatim */
2352                 strcpy( tmp, "g" );
2353             }
2354             MultiByteToWideChar( CP_ACP, 0, tmp, -1, buf, sizeof(buf)/sizeof(WCHAR) );
2355             break;
2356
2357           case 'h':
2358               /* hours 1:00-12:00 --- is this right? */
2359               sprintf( tmp, "%.*d", count, (xtime->wHour-1)%12 +1);
2360               MultiByteToWideChar( CP_ACP, 0, tmp, -1, buf, sizeof(buf)/sizeof(WCHAR) );
2361               break;
2362
2363           case 'H':
2364               sprintf( tmp, "%.*d", count, xtime->wHour );
2365               MultiByteToWideChar( CP_ACP, 0, tmp, -1, buf, sizeof(buf)/sizeof(WCHAR) );
2366               break;
2367
2368           case 'm':
2369               sprintf( tmp, "%.*d", count, xtime->wMinute );
2370               MultiByteToWideChar( CP_ACP, 0, tmp, -1, buf, sizeof(buf)/sizeof(WCHAR) );
2371               break;
2372
2373           case 's':
2374               sprintf( tmp, "%.*d", count, xtime->wSecond );
2375               MultiByteToWideChar( CP_ACP, 0, tmp, -1, buf, sizeof(buf)/sizeof(WCHAR) );
2376               break;
2377
2378           case 't':
2379             GetLocaleInfoW(locale, (xtime->wHour < 12) ?
2380                              LOCALE_S1159 : LOCALE_S2359,
2381                              buf, sizeof(buf) );
2382             if        (count == 1) {
2383                buf[1] = 0;
2384             }
2385             break;
2386           }
2387
2388          /* no matter what happened,  we need to check this next
2389             character the next time we loop through */
2390          inpos--;
2391
2392          /* cat buf onto the output */
2393          outlen = strlenW(buf);
2394          if (outpos + buflen < outlen) {
2395             strcpyW( output + outpos, buf );
2396             outpos += buflen;
2397          } else {
2398             lstrcpynW( output + outpos, buf, outlen - outpos );
2399             Overflow = 1;
2400             break; /* Abnormal exit */
2401          }
2402
2403          /* reset the variables we used this time */
2404          count = 0;
2405          type = '\0';
2406       } else if (format[inpos] == 0) {
2407          /* we can't check for this at the beginning,  because that
2408          would keep us from printing a format spec that ended the
2409          string */
2410          output[outpos] = 0;
2411          break;  /*  NORMAL EXIT  */
2412       } else if (count) {
2413          /* how we keep track of the middle of a format spec */
2414          count++;
2415          continue;
2416       } else if ( (datevars && (format[inpos]=='d' ||
2417                                 format[inpos]=='M' ||
2418                                 format[inpos]=='y' ||
2419                                 format[inpos]=='g')  ) ||
2420                   (timevars && (format[inpos]=='H' ||
2421                                 format[inpos]=='h' ||
2422                                 format[inpos]=='m' ||
2423                                 format[inpos]=='s' ||
2424                                 format[inpos]=='t') )    ) {
2425          type = format[inpos];
2426          count = 1;
2427          continue;
2428       } else if (format[inpos] == '\'') {
2429          inquote = 1;
2430          continue;
2431       } else {
2432          /* unquoted literals */
2433          output[outpos++] = format[inpos];
2434       }
2435    }
2436
2437    if (Overflow) {
2438       SetLastError(ERROR_INSUFFICIENT_BUFFER);
2439       WARN(" buffer overflow\n");
2440    };
2441
2442    /* final string terminator and sanity check */
2443    outpos++;
2444    if (outpos > outlen-1) outpos = outlen-1;
2445    output[outpos] = '0';
2446
2447    TRACE(" returning %s\n", debugstr_w(output));
2448
2449    return (!Overflow) ? outlen : 0;
2450
2451 }
2452
2453
2454 /******************************************************************************
2455  *              GetDateFormatA  [KERNEL32.@]
2456  * Makes an ASCII string of the date
2457  *
2458  * This function uses format to format the date,  or,  if format
2459  * is NULL, uses the default for the locale.  format is a string
2460  * of literal fields and characters as follows:
2461  *
2462  * - d    single-digit (no leading zero) day (of month)
2463  * - dd   two-digit day (of month)
2464  * - ddd  short day-of-week name
2465  * - dddd long day-of-week name
2466  * - M    single-digit month
2467  * - MM   two-digit month
2468  * - MMM  short month name
2469  * - MMMM full month name
2470  * - y    two-digit year, no leading 0
2471  * - yy   two-digit year
2472  * - yyyy four-digit year
2473  * - gg   era string
2474  *
2475  */
2476 INT WINAPI GetDateFormatA(LCID locale,DWORD flags,
2477                               const SYSTEMTIME* xtime,
2478                               LPCSTR format, LPSTR date,INT datelen)
2479 {
2480
2481   char format_buf[40];
2482   LPCSTR thisformat;
2483   SYSTEMTIME t;
2484   LPSYSTEMTIME thistime;
2485   LCID thislocale;
2486   INT ret;
2487   FILETIME ft;
2488   BOOL res;
2489
2490   TRACE("(0x%04lx,0x%08lx,%p,%s,%p,%d)\n",
2491               locale,flags,xtime,format,date,datelen);
2492
2493   if (!locale) {
2494      locale = LOCALE_SYSTEM_DEFAULT;
2495      };
2496
2497   if (locale == LOCALE_SYSTEM_DEFAULT) {
2498      thislocale = GetSystemDefaultLCID();
2499   } else if (locale == LOCALE_USER_DEFAULT) {
2500      thislocale = GetUserDefaultLCID();
2501   } else {
2502      thislocale = locale;
2503    };
2504
2505   if (xtime == NULL) {
2506      GetSystemTime(&t);
2507   } else {
2508       /* Silently correct wDayOfWeek by transforming to FileTime and back again */
2509       res=SystemTimeToFileTime(xtime,&ft);
2510       /* Check year(?)/month and date for range and set ERROR_INVALID_PARAMETER  on error */
2511       /*FIXME: SystemTimeToFileTime doesn't yet do that check */
2512       if(!res)
2513         {
2514           SetLastError(ERROR_INVALID_PARAMETER);
2515           return 0;
2516         }
2517       FileTimeToSystemTime(&ft,&t);
2518
2519   };
2520   thistime = &t;
2521
2522   if (format == NULL) {
2523      GetLocaleInfoA(thislocale, ((flags&DATE_LONGDATE)
2524                                    ? LOCALE_SLONGDATE
2525                                    : LOCALE_SSHORTDATE),
2526                       format_buf, sizeof(format_buf));
2527      thisformat = format_buf;
2528   } else {
2529      thisformat = format;
2530   };
2531
2532
2533   ret = OLE_GetFormatA(thislocale, flags, 0, thistime, thisformat,
2534                        date, datelen);
2535
2536
2537    TRACE(
2538                "GetDateFormatA() returning %d, with data=%s\n",
2539                ret, date);
2540   return ret;
2541 }
2542
2543 /******************************************************************************
2544  *              GetDateFormatW  [KERNEL32.@]
2545  * Makes a Unicode string of the date
2546  *
2547  * Acts the same as GetDateFormatA(),  except that it's Unicode.
2548  * Accepts & returns sizes as counts of Unicode characters.
2549  *
2550  */
2551 INT WINAPI GetDateFormatW(LCID locale,DWORD flags,
2552                               const SYSTEMTIME* xtime,
2553                               LPCWSTR format,
2554                               LPWSTR date, INT datelen)
2555 {
2556    unsigned short datearr[] = {'1','9','9','4','-','1','-','1',0};
2557
2558    FIXME("STUB (should call OLE_GetFormatW)\n");
2559    lstrcpynW(date, datearr, datelen);
2560    return (  datelen < 9) ? datelen : 9;
2561
2562
2563 }
2564
2565 /**************************************************************************
2566  *              EnumDateFormatsA        (KERNEL32.@)
2567  */
2568 BOOL WINAPI EnumDateFormatsA(
2569   DATEFMT_ENUMPROCA lpDateFmtEnumProc, LCID Locale,  DWORD dwFlags)
2570 {
2571   LCID Loc = GetUserDefaultLCID();
2572   if(!lpDateFmtEnumProc)
2573     {
2574       SetLastError(ERROR_INVALID_PARAMETER);
2575       return FALSE;
2576     }
2577
2578   switch( Loc )
2579  {
2580
2581    case 0x00000407:  /* (Loc,"de_DE") */
2582    {
2583     switch(dwFlags)
2584     {
2585       case DATE_SHORTDATE:
2586         if(!(*lpDateFmtEnumProc)("dd.MM.yy")) return TRUE;
2587         if(!(*lpDateFmtEnumProc)("d.M.yyyy")) return TRUE;
2588         if(!(*lpDateFmtEnumProc)("d.MM.yy")) return TRUE;
2589         if(!(*lpDateFmtEnumProc)("d.M.yy")) return TRUE;
2590         return TRUE;
2591       case DATE_LONGDATE:
2592         if(!(*lpDateFmtEnumProc)("dddd,d. MMMM yyyy")) return TRUE;
2593         if(!(*lpDateFmtEnumProc)("d. MMMM yyyy")) return TRUE;
2594         if(!(*lpDateFmtEnumProc)("d. MMM yyyy")) return TRUE;
2595         return TRUE;
2596       default:
2597         FIXME("Unknown date format (%ld)\n", dwFlags);
2598         SetLastError(ERROR_INVALID_PARAMETER);
2599         return FALSE;
2600      }
2601    }
2602
2603    case 0x0000040c:  /* (Loc,"fr_FR") */
2604    {
2605     switch(dwFlags)
2606     {
2607       case DATE_SHORTDATE:
2608         if(!(*lpDateFmtEnumProc)("dd/MM/yy")) return TRUE;
2609         if(!(*lpDateFmtEnumProc)("dd.MM.yy")) return TRUE;
2610         if(!(*lpDateFmtEnumProc)("dd-MM-yy")) return TRUE;
2611         if(!(*lpDateFmtEnumProc)("dd/MM/yyyy")) return TRUE;
2612         return TRUE;
2613       case DATE_LONGDATE:
2614         if(!(*lpDateFmtEnumProc)("dddd d MMMM yyyy")) return TRUE;
2615         if(!(*lpDateFmtEnumProc)("d MMM yy")) return TRUE;
2616         if(!(*lpDateFmtEnumProc)("d MMMM yyyy")) return TRUE;
2617         return TRUE;
2618       default:
2619         FIXME("Unknown date format (%ld)\n", dwFlags);
2620         SetLastError(ERROR_INVALID_PARAMETER);
2621         return FALSE;
2622      }
2623    }
2624
2625    case 0x00000c0c:  /* (Loc,"fr_CA") */
2626    {
2627     switch(dwFlags)
2628     {
2629       case DATE_SHORTDATE:
2630         if(!(*lpDateFmtEnumProc)("yy-MM-dd")) return TRUE;
2631         if(!(*lpDateFmtEnumProc)("dd-MM-yy")) return TRUE;
2632         if(!(*lpDateFmtEnumProc)("yy MM dd")) return TRUE;
2633         if(!(*lpDateFmtEnumProc)("dd/MM/yy")) return TRUE;
2634         return TRUE;
2635       case DATE_LONGDATE:
2636         if(!(*lpDateFmtEnumProc)("d MMMM, yyyy")) return TRUE;
2637         if(!(*lpDateFmtEnumProc)("d MMM yyyy")) return TRUE;
2638         return TRUE;
2639       default:
2640         FIXME("Unknown date format (%ld)\n", dwFlags);
2641         SetLastError(ERROR_INVALID_PARAMETER);
2642         return FALSE;
2643      }
2644    }
2645
2646    case 0x00000809:  /* (Loc,"en_UK") */
2647   {
2648    switch(dwFlags)
2649     {
2650       case DATE_SHORTDATE:
2651         if(!(*lpDateFmtEnumProc)("dd/MM/yy")) return TRUE;
2652         if(!(*lpDateFmtEnumProc)("dd/MM/yyyy")) return TRUE;
2653         if(!(*lpDateFmtEnumProc)("d/M/yy")) return TRUE;
2654         if(!(*lpDateFmtEnumProc)("d.M.yy")) return TRUE;
2655         return TRUE;
2656       case DATE_LONGDATE:
2657         if(!(*lpDateFmtEnumProc)("dd MMMM yyyy")) return TRUE;
2658         if(!(*lpDateFmtEnumProc)("d MMMM yyyy")) return TRUE;
2659         return TRUE;
2660       default:
2661         FIXME("Unknown date format (%ld)\n", dwFlags);
2662         SetLastError(ERROR_INVALID_PARAMETER);
2663         return FALSE;
2664     }
2665   }
2666
2667    case 0x00000c09:  /* (Loc,"en_AU") */
2668   {
2669    switch(dwFlags)
2670     {
2671       case DATE_SHORTDATE:
2672         if(!(*lpDateFmtEnumProc)("d/MM/yy")) return TRUE;
2673         if(!(*lpDateFmtEnumProc)("d/M/yy")) return TRUE;
2674         if(!(*lpDateFmtEnumProc)("dd/MM/yy")) return TRUE;
2675         return TRUE;
2676       case DATE_LONGDATE:
2677         if(!(*lpDateFmtEnumProc)("dddd,d MMMM yyyy")) return TRUE;
2678         if(!(*lpDateFmtEnumProc)("d MMMM yyyy")) return TRUE;
2679         return TRUE;
2680       default:
2681         FIXME("Unknown date format (%ld)\n", dwFlags);
2682         SetLastError(ERROR_INVALID_PARAMETER);
2683         return FALSE;
2684     }
2685   }
2686
2687    case 0x00001009:  /* (Loc,"en_CA") */
2688   {
2689    switch(dwFlags)
2690     {
2691       case DATE_SHORTDATE:
2692         if(!(*lpDateFmtEnumProc)("dd/MM/yy")) return TRUE;
2693         if(!(*lpDateFmtEnumProc)("d/M/yy")) return TRUE;
2694         if(!(*lpDateFmtEnumProc)("yy-MM-dd")) return TRUE;
2695         if(!(*lpDateFmtEnumProc)("M/dd/yy")) return TRUE;
2696         return TRUE;
2697       case DATE_LONGDATE:
2698         if(!(*lpDateFmtEnumProc)("d-MMM-yy")) return TRUE;
2699         if(!(*lpDateFmtEnumProc)("MMMM d, yyyy")) return TRUE;
2700         return TRUE;
2701       default:
2702         FIXME("Unknown date format (%ld)\n", dwFlags);
2703         SetLastError(ERROR_INVALID_PARAMETER);
2704         return FALSE;
2705     }
2706   }
2707
2708    case 0x00001409:  /* (Loc,"en_NZ") */
2709   {
2710    switch(dwFlags)
2711     {
2712       case DATE_SHORTDATE:
2713         if(!(*lpDateFmtEnumProc)("d/MM/yy")) return TRUE;
2714         if(!(*lpDateFmtEnumProc)("dd/MM/yy")) return TRUE;
2715         if(!(*lpDateFmtEnumProc)("d.MM.yy")) return TRUE;
2716         return TRUE;
2717       case DATE_LONGDATE:
2718         if(!(*lpDateFmtEnumProc)("d MMMM yyyy")) return TRUE;
2719         if(!(*lpDateFmtEnumProc)("dddd, d MMMM yyyy")) return TRUE;
2720         return TRUE;
2721       default:
2722         FIXME("Unknown date format (%ld)\n", dwFlags);
2723         SetLastError(ERROR_INVALID_PARAMETER);
2724         return FALSE;
2725     }
2726   }
2727
2728    case 0x00001809:  /* (Loc,"en_IE") */
2729   {
2730    switch(dwFlags)
2731     {
2732       case DATE_SHORTDATE:
2733         if(!(*lpDateFmtEnumProc)("dd/MM/yy")) return TRUE;
2734         if(!(*lpDateFmtEnumProc)("d/M/yy")) return TRUE;
2735         if(!(*lpDateFmtEnumProc)("d.M.yy")) return TRUE;
2736         return TRUE;
2737       case DATE_LONGDATE:
2738         if(!(*lpDateFmtEnumProc)("dd MMMM yyyy")) return TRUE;
2739         if(!(*lpDateFmtEnumProc)("d MMMM yyyy")) return TRUE;
2740         return TRUE;
2741       default:
2742         FIXME("Unknown date format (%ld)\n", dwFlags);
2743         SetLastError(ERROR_INVALID_PARAMETER);
2744         return FALSE;
2745     }
2746   }
2747
2748    case 0x00001c09:  /* (Loc,"en_ZA") */
2749   {
2750    switch(dwFlags)
2751     {
2752       case DATE_SHORTDATE:
2753         if(!(*lpDateFmtEnumProc)("yy/MM/dd")) return TRUE;
2754         return TRUE;
2755       case DATE_LONGDATE:
2756         if(!(*lpDateFmtEnumProc)("dd MMMM yyyy")) return TRUE;
2757         return TRUE;
2758       default:
2759         FIXME("Unknown date format (%ld)\n", dwFlags);
2760         SetLastError(ERROR_INVALID_PARAMETER);
2761         return FALSE;
2762     }
2763   }
2764
2765    case 0x00002009:  /* (Loc,"en_JM") */
2766   {
2767    switch(dwFlags)
2768     {
2769       case DATE_SHORTDATE:
2770         if(!(*lpDateFmtEnumProc)("dd/MM/yyyy")) return TRUE;
2771         return TRUE;
2772       case DATE_LONGDATE:
2773         if(!(*lpDateFmtEnumProc)("dddd,MMMM dd,yyyy")) return TRUE;
2774         if(!(*lpDateFmtEnumProc)("MMMM dd,yyyy")) return TRUE;
2775         if(!(*lpDateFmtEnumProc)("dddd,dd MMMM,yyyy")) return TRUE;
2776         if(!(*lpDateFmtEnumProc)("dd MMMM,yyyy")) return TRUE;
2777         return TRUE;
2778       default:
2779         FIXME("Unknown date format (%ld)\n", dwFlags);
2780         SetLastError(ERROR_INVALID_PARAMETER);
2781         return FALSE;
2782     }
2783   }
2784
2785    case 0x00002809:  /* (Loc,"en_BZ") */
2786    case 0x00002c09:  /* (Loc,"en_TT") */
2787   {
2788    switch(dwFlags)
2789     {
2790       case DATE_SHORTDATE:
2791         if(!(*lpDateFmtEnumProc)("dd/MM/yyyy")) return TRUE;
2792         return TRUE;
2793       case DATE_LONGDATE:
2794         if(!(*lpDateFmtEnumProc)("dddd,dd MMMM yyyy")) return TRUE;
2795         return TRUE;
2796       default:
2797         FIXME("Unknown date format (%ld)\n", dwFlags);
2798         SetLastError(ERROR_INVALID_PARAMETER);
2799         return FALSE;
2800     }
2801   }
2802
2803    default:  /* default to US English "en_US" */
2804   {
2805    switch(dwFlags)
2806     {
2807       case DATE_SHORTDATE:
2808         if(!(*lpDateFmtEnumProc)("M/d/yy")) return TRUE;
2809         if(!(*lpDateFmtEnumProc)("M/d/yyyy")) return TRUE;
2810         if(!(*lpDateFmtEnumProc)("MM/dd/yy")) return TRUE;
2811         if(!(*lpDateFmtEnumProc)("MM/dd/yyyy")) return TRUE;
2812         if(!(*lpDateFmtEnumProc)("yy/MM/dd")) return TRUE;
2813         if(!(*lpDateFmtEnumProc)("dd-MMM-yy")) return TRUE;
2814         return TRUE;
2815       case DATE_LONGDATE:
2816         if(!(*lpDateFmtEnumProc)("dddd, MMMM dd, yyyy")) return TRUE;
2817         if(!(*lpDateFmtEnumProc)("MMMM dd, yyyy")) return TRUE;
2818         if(!(*lpDateFmtEnumProc)("dddd, dd MMMM, yyyy")) return TRUE;
2819         if(!(*lpDateFmtEnumProc)("dd MMMM, yyyy")) return TRUE;
2820         return TRUE;
2821       default:
2822         FIXME("Unknown date format (%ld)\n", dwFlags);
2823         SetLastError(ERROR_INVALID_PARAMETER);
2824         return FALSE;
2825     }
2826   }
2827  }
2828 }
2829
2830 /**************************************************************************
2831  *              EnumDateFormatsW        (KERNEL32.@)
2832  */
2833 BOOL WINAPI EnumDateFormatsW(
2834   DATEFMT_ENUMPROCW lpDateFmtEnumProc, LCID Locale, DWORD dwFlags)
2835 {
2836   FIXME("(%p, %ld, %ld): stub\n", lpDateFmtEnumProc, Locale, dwFlags);
2837   SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2838   return FALSE;
2839 }
2840
2841 /**************************************************************************
2842  *              EnumTimeFormatsA        (KERNEL32.@)
2843  */
2844 BOOL WINAPI EnumTimeFormatsA(
2845   TIMEFMT_ENUMPROCA lpTimeFmtEnumProc, LCID Locale, DWORD dwFlags)
2846 {
2847   LCID Loc = GetUserDefaultLCID();
2848   if(!lpTimeFmtEnumProc)
2849     {
2850       SetLastError(ERROR_INVALID_PARAMETER);
2851       return FALSE;
2852     }
2853   if(dwFlags)
2854     {
2855       FIXME("Unknown time format (%ld)\n", dwFlags);
2856     }
2857
2858   switch( Loc )
2859  {
2860    case 0x00000407:  /* (Loc,"de_DE") */
2861    {
2862     if(!(*lpTimeFmtEnumProc)("HH.mm")) return TRUE;
2863     if(!(*lpTimeFmtEnumProc)("HH:mm:ss")) return TRUE;
2864     if(!(*lpTimeFmtEnumProc)("H:mm:ss")) return TRUE;
2865     if(!(*lpTimeFmtEnumProc)("H.mm")) return TRUE;
2866     if(!(*lpTimeFmtEnumProc)("H.mm'Uhr'")) return TRUE;
2867     return TRUE;
2868    }
2869
2870    case 0x0000040c:  /* (Loc,"fr_FR") */
2871    case 0x00000c0c:  /* (Loc,"fr_CA") */
2872    {
2873     if(!(*lpTimeFmtEnumProc)("H:mm")) return TRUE;
2874     if(!(*lpTimeFmtEnumProc)("HH:mm:ss")) return TRUE;
2875     if(!(*lpTimeFmtEnumProc)("H:mm:ss")) return TRUE;
2876     if(!(*lpTimeFmtEnumProc)("HH.mm")) return TRUE;
2877     if(!(*lpTimeFmtEnumProc)("HH'h'mm")) return TRUE;
2878     return TRUE;
2879    }
2880
2881    case 0x00000809:  /* (Loc,"en_UK") */
2882    case 0x00000c09:  /* (Loc,"en_AU") */
2883    case 0x00001409:  /* (Loc,"en_NZ") */
2884    case 0x00001809:  /* (Loc,"en_IE") */
2885    {
2886     if(!(*lpTimeFmtEnumProc)("h:mm:ss tt")) return TRUE;
2887     if(!(*lpTimeFmtEnumProc)("HH:mm:ss")) return TRUE;
2888     if(!(*lpTimeFmtEnumProc)("H:mm:ss")) return TRUE;
2889     return TRUE;
2890    }
2891
2892    case 0x00001c09:  /* (Loc,"en_ZA") */
2893    case 0x00002809:  /* (Loc,"en_BZ") */
2894    case 0x00002c09:  /* (Loc,"en_TT") */
2895    {
2896     if(!(*lpTimeFmtEnumProc)("h:mm:ss tt")) return TRUE;
2897     if(!(*lpTimeFmtEnumProc)("hh:mm:ss tt")) return TRUE;
2898     return TRUE;
2899    }
2900
2901    default:  /* default to US style "en_US" */
2902    {
2903     if(!(*lpTimeFmtEnumProc)("h:mm:ss tt")) return TRUE;
2904     if(!(*lpTimeFmtEnumProc)("hh:mm:ss tt")) return TRUE;
2905     if(!(*lpTimeFmtEnumProc)("H:mm:ss")) return TRUE;
2906     if(!(*lpTimeFmtEnumProc)("HH:mm:ss")) return TRUE;
2907     return TRUE;
2908    }
2909  }
2910 }
2911
2912 /**************************************************************************
2913  *              EnumTimeFormatsW        (KERNEL32.@)
2914  */
2915 BOOL WINAPI EnumTimeFormatsW(
2916   TIMEFMT_ENUMPROCW lpTimeFmtEnumProc, LCID Locale, DWORD dwFlags)
2917 {
2918   FIXME("(%p,%ld,%ld): stub\n", lpTimeFmtEnumProc, Locale, dwFlags);
2919   SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2920   return FALSE;
2921 }
2922
2923 /**************************************************************************
2924  *           This function is used just locally !
2925  *  Description: Inverts a string.
2926  */
2927 static void OLE_InvertString(char* string)
2928 {
2929     char    sTmpArray[128];
2930     INT     counter, i = 0;
2931
2932     for (counter = strlen(string); counter > 0; counter--)
2933     {
2934         memcpy(sTmpArray + i, string + counter-1, 1);
2935         i++;
2936     }
2937     memcpy(sTmpArray + i, "\0", 1);
2938     strcpy(string, sTmpArray);
2939 }
2940
2941 /***************************************************************************************
2942  *           This function is used just locally !
2943  *  Description: Test if the given string (psNumber) is valid or not.
2944  *               The valid characters are the following:
2945  *               - Characters '0' through '9'.
2946  *               - One decimal point (dot) if the number is a floating-point value.
2947  *               - A minus sign in the first character position if the number is
2948  *                 a negative value.
2949  *              If the function succeeds, psBefore/psAfter will point to the string
2950  *              on the right/left of the decimal symbol. pbNegative indicates if the
2951  *              number is negative.
2952  */
2953 static INT OLE_GetNumberComponents(char* pInput, char* psBefore, char* psAfter, BOOL* pbNegative)
2954 {
2955 char    sNumberSet[] = "0123456789";
2956 BOOL    bInDecimal = FALSE;
2957
2958         /* Test if we do have a minus sign */
2959         if ( *pInput == '-' )
2960         {
2961                 *pbNegative = TRUE;
2962                 pInput++; /* Jump to the next character. */
2963         }
2964
2965         while(*pInput != '\0')
2966         {
2967                 /* Do we have a valid numeric character */
2968                 if ( strchr(sNumberSet, *pInput) != NULL )
2969                 {
2970                         if (bInDecimal == TRUE)
2971                 *psAfter++ = *pInput;
2972                         else
2973                 *psBefore++ = *pInput;
2974                 }
2975                 else
2976                 {
2977                         /* Is this a decimal point (dot) */
2978                         if ( *pInput == '.' )
2979                         {
2980                                 /* Is it the first time we find it */
2981                                 if ((bInDecimal == FALSE))
2982                                         bInDecimal = TRUE;
2983                                 else
2984                                         return -1; /* ERROR: Invalid parameter */
2985                         }
2986                         else
2987                         {
2988                                 /* It's neither a numeric character, nor a decimal point.
2989                                  * Thus, return an error.
2990                  */
2991                                 return -1;
2992                         }
2993                 }
2994         pInput++;
2995         }
2996
2997         /* Add an End of Line character to the output buffers */
2998         *psBefore = '\0';
2999         *psAfter = '\0';
3000
3001         return 0;
3002 }
3003
3004 /**************************************************************************
3005  *           This function is used just locally !
3006  *  Description: A number could be formatted using different numbers
3007  *               of "digits in group" (example: 4;3;2;0).
3008  *               The first parameter of this function is an array
3009  *               containing the rule to be used. Its format is the following:
3010  *               |NDG|DG1|DG2|...|0|
3011  *               where NDG is the number of used "digits in group" and DG1, DG2,
3012  *               are the corresponding "digits in group".
3013  *               Thus, this function returns the grouping value in the array
3014  *               pointed by the second parameter.
3015  */
3016 static INT OLE_GetGrouping(char* sRule, INT index)
3017 {
3018     char    sData[2], sRuleSize[2];
3019     INT     nData, nRuleSize;
3020
3021     memcpy(sRuleSize, sRule, 1);
3022     memcpy(sRuleSize+1, "\0", 1);
3023     nRuleSize = atoi(sRuleSize);
3024
3025     if (index > 0 && index < nRuleSize)
3026     {
3027         memcpy(sData, sRule+index, 1);
3028         memcpy(sData+1, "\0", 1);
3029         nData = atoi(sData);
3030     }
3031
3032     else
3033     {
3034         memcpy(sData, sRule+nRuleSize-1, 1);
3035         memcpy(sData+1, "\0", 1);
3036         nData = atoi(sData);
3037     }
3038
3039     return nData;
3040 }
3041
3042 /**************************************************************************
3043  *              GetNumberFormatA        (KERNEL32.@)
3044  */
3045 INT WINAPI GetNumberFormatA(LCID locale, DWORD dwflags,
3046                                LPCSTR lpvalue,   const NUMBERFMTA * lpFormat,
3047                                LPSTR lpNumberStr, int cchNumber)
3048 {
3049     char   sNumberDigits[3], sDecimalSymbol[5], sDigitsInGroup[11], sDigitGroupSymbol[5], sILZero[2];
3050     INT    nNumberDigits, nNumberDecimal, i, j, nCounter, nStep, nRuleIndex, nGrouping, nDigits, retVal, nLZ;
3051     char   sNumber[128], sDestination[128], sDigitsAfterDecimal[10], sDigitsBeforeDecimal[128];
3052     char   sRule[10], sSemiColumn[]=";", sBuffer[5], sNegNumber[2];
3053     char   *pStr = NULL, *pTmpStr = NULL;
3054     LCID   systemDefaultLCID;
3055     BOOL   bNegative = FALSE;
3056     enum   Operations
3057     {
3058         USE_PARAMETER,
3059         USE_LOCALEINFO,
3060         USE_SYSTEMDEFAULT,
3061         RETURN_ERROR
3062     } used_operation;
3063
3064     strncpy(sNumber, lpvalue, 128);
3065     sNumber[127] = '\0';
3066
3067     /* Make sure we have a valid input string, get the number
3068      * of digits before and after the decimal symbol, and check
3069      * if this is a negative number.
3070      */
3071     if ( OLE_GetNumberComponents(sNumber, sDigitsBeforeDecimal, sDigitsAfterDecimal, &bNegative) != -1)
3072     {
3073         nNumberDecimal = strlen(sDigitsBeforeDecimal);
3074         nDigits = strlen(sDigitsAfterDecimal);
3075     }
3076     else
3077     {
3078         SetLastError(ERROR_INVALID_PARAMETER);
3079         return 0;
3080     }
3081
3082     /* Which source will we use to format the string */
3083     used_operation = RETURN_ERROR;
3084     if (lpFormat != NULL)
3085     {
3086         if (dwflags == 0)
3087             used_operation = USE_PARAMETER;
3088     }
3089     else
3090     {
3091         if (dwflags & LOCALE_NOUSEROVERRIDE)
3092             used_operation = USE_SYSTEMDEFAULT;
3093         else
3094             used_operation = USE_LOCALEINFO;
3095     }
3096
3097     /* Load the fields we need */
3098     switch(used_operation)
3099     {
3100     case USE_LOCALEINFO:
3101         GetLocaleInfoA(locale, LOCALE_IDIGITS, sNumberDigits, sizeof(sNumberDigits));
3102         GetLocaleInfoA(locale, LOCALE_SDECIMAL, sDecimalSymbol, sizeof(sDecimalSymbol));
3103         GetLocaleInfoA(locale, LOCALE_SGROUPING, sDigitsInGroup, sizeof(sDigitsInGroup));
3104         GetLocaleInfoA(locale, LOCALE_STHOUSAND, sDigitGroupSymbol, sizeof(sDigitGroupSymbol));
3105         GetLocaleInfoA(locale, LOCALE_ILZERO, sILZero, sizeof(sILZero));
3106         GetLocaleInfoA(locale, LOCALE_INEGNUMBER, sNegNumber, sizeof(sNegNumber));
3107         break;
3108     case USE_PARAMETER:
3109         sprintf(sNumberDigits, "%d",lpFormat->NumDigits);
3110         strcpy(sDecimalSymbol, lpFormat->lpDecimalSep);
3111         sprintf(sDigitsInGroup, "%d;0",lpFormat->Grouping);
3112         strcpy(sDigitGroupSymbol, lpFormat->lpThousandSep);
3113         sprintf(sILZero, "%d",lpFormat->LeadingZero);
3114         sprintf(sNegNumber, "%d",lpFormat->NegativeOrder);
3115         break;
3116     case USE_SYSTEMDEFAULT:
3117         systemDefaultLCID = GetSystemDefaultLCID();
3118         GetLocaleInfoA(systemDefaultLCID, LOCALE_IDIGITS, sNumberDigits, sizeof(sNumberDigits));
3119         GetLocaleInfoA(systemDefaultLCID, LOCALE_SDECIMAL, sDecimalSymbol, sizeof(sDecimalSymbol));
3120         GetLocaleInfoA(systemDefaultLCID, LOCALE_SGROUPING, sDigitsInGroup, sizeof(sDigitsInGroup));
3121         GetLocaleInfoA(systemDefaultLCID, LOCALE_STHOUSAND, sDigitGroupSymbol, sizeof(sDigitGroupSymbol));
3122         GetLocaleInfoA(systemDefaultLCID, LOCALE_ILZERO, sILZero, sizeof(sILZero));
3123         GetLocaleInfoA(systemDefaultLCID, LOCALE_INEGNUMBER, sNegNumber, sizeof(sNegNumber));
3124         break;
3125     default:
3126         SetLastError(ERROR_INVALID_PARAMETER);
3127         return 0;
3128     }
3129
3130     nNumberDigits = atoi(sNumberDigits);
3131
3132     /* Remove the ";" */
3133     i=0;
3134     j = 1;
3135     for (nCounter=0; nCounter<strlen(sDigitsInGroup); nCounter++)
3136     {
3137         if ( memcmp(sDigitsInGroup + nCounter, sSemiColumn, 1) != 0 )
3138         {
3139             memcpy(sRule + j, sDigitsInGroup + nCounter, 1);
3140             i++;
3141             j++;
3142         }
3143     }
3144     sprintf(sBuffer, "%d", i);
3145     memcpy(sRule, sBuffer, 1); /* Number of digits in the groups ( used by OLE_GetGrouping() ) */
3146     memcpy(sRule + j, "\0", 1);
3147
3148     /* First, format the digits before the decimal. */
3149     if ((nNumberDecimal>0) && (atoi(sDigitsBeforeDecimal) != 0))
3150     {
3151         /* Working on an inverted string is easier ! */
3152         OLE_InvertString(sDigitsBeforeDecimal);
3153
3154         nStep = nCounter = i = j = 0;
3155         nRuleIndex = 1;
3156         nGrouping = OLE_GetGrouping(sRule, nRuleIndex);
3157
3158         /* Here, we will loop until we reach the end of the string.
3159          * An internal counter (j) is used in order to know when to
3160          * insert the "digit group symbol".
3161          */
3162         while (nNumberDecimal > 0)
3163         {
3164             i = nCounter + nStep;
3165             memcpy(sDestination + i, sDigitsBeforeDecimal + nCounter, 1);
3166             nCounter++;
3167             j++;
3168             if (j >= nGrouping)
3169             {
3170                 j = 0;
3171                 if (nRuleIndex < sRule[0])
3172                     nRuleIndex++;
3173                 nGrouping = OLE_GetGrouping(sRule, nRuleIndex);
3174                 memcpy(sDestination + i+1, sDigitGroupSymbol, strlen(sDigitGroupSymbol));
3175                 nStep+= strlen(sDigitGroupSymbol);
3176             }
3177
3178             nNumberDecimal--;
3179         }
3180
3181         memcpy(sDestination + i+1, "\0", 1);
3182         /* Get the string in the right order ! */
3183         OLE_InvertString(sDestination);
3184      }
3185      else
3186      {
3187         nLZ = atoi(sILZero);
3188         if (nLZ != 0)
3189         {
3190             /* Use 0.xxx instead of .xxx */
3191             memcpy(sDestination, "0", 1);
3192             memcpy(sDestination+1, "\0", 1);
3193         }
3194         else
3195             memcpy(sDestination, "\0", 1);
3196
3197      }
3198
3199     /* Second, format the digits after the decimal. */
3200     j = 0;
3201     nCounter = nNumberDigits;
3202     if ( (nDigits>0) && (pStr = strstr (sNumber, ".")) )
3203     {
3204         i = strlen(sNumber) - strlen(pStr) + 1;
3205         strncpy ( sDigitsAfterDecimal, sNumber + i, nNumberDigits);
3206         j = strlen(sDigitsAfterDecimal);
3207         if (j < nNumberDigits)
3208             nCounter = nNumberDigits-j;
3209     }
3210     for (i=0;i<nCounter;i++)
3211          memcpy(sDigitsAfterDecimal+i+j, "0", 1);
3212     memcpy(sDigitsAfterDecimal + nNumberDigits, "\0", 1);
3213
3214     i = strlen(sDestination);
3215     j = strlen(sDigitsAfterDecimal);
3216     /* Finally, construct the resulting formatted string. */
3217
3218     for (nCounter=0; nCounter<i; nCounter++)
3219         memcpy(sNumber + nCounter, sDestination + nCounter, 1);
3220
3221     memcpy(sNumber + nCounter, sDecimalSymbol, strlen(sDecimalSymbol));
3222
3223     for (i=0; i<j; i++)
3224         memcpy(sNumber + nCounter+i+strlen(sDecimalSymbol), sDigitsAfterDecimal + i, 1);
3225     memcpy(sNumber + nCounter+i+strlen(sDecimalSymbol), "\0", 1);
3226
3227     /* Is it a negative number */
3228     if (bNegative == TRUE)
3229     {
3230         i = atoi(sNegNumber);
3231         pStr = sDestination;
3232         pTmpStr = sNumber;
3233         switch (i)
3234         {
3235         case 0:
3236             *pStr++ = '(';
3237             while (*sNumber != '\0')
3238                 *pStr++ =  *pTmpStr++;
3239             *pStr++ = ')';
3240             break;
3241         case 1:
3242             *pStr++ = '-';
3243             while (*pTmpStr != '\0')
3244                 *pStr++ =  *pTmpStr++;
3245             break;
3246         case 2:
3247             *pStr++ = '-';
3248             *pStr++ = ' ';
3249             while (*pTmpStr != '\0')
3250                 *pStr++ =  *pTmpStr++;
3251             break;
3252         case 3:
3253             while (*pTmpStr != '\0')
3254                 *pStr++ =  *pTmpStr++;
3255             *pStr++ = '-';
3256             break;
3257         case 4:
3258             while (*pTmpStr != '\0')
3259                 *pStr++ =  *pTmpStr++;
3260             *pStr++ = ' ';
3261             *pStr++ = '-';
3262             break;
3263         default:
3264             while (*pTmpStr != '\0')
3265                 *pStr++ =  *pTmpStr++;
3266             break;
3267         }
3268     }
3269     else
3270         strcpy(sDestination, sNumber);
3271
3272     /* If cchNumber is zero, then returns the number of bytes or characters
3273      * required to hold the formatted number string
3274      */
3275     retVal = strlen(sDestination) + 1;
3276     if (cchNumber!=0)
3277     {
3278         memcpy( lpNumberStr, sDestination, min(cchNumber, retVal) );
3279         if (cchNumber < retVal) retVal = 0;
3280     }
3281     return retVal;
3282 }
3283
3284 /**************************************************************************
3285  *              GetNumberFormatW        (KERNEL32.@)
3286  */
3287 INT WINAPI GetNumberFormatW(LCID locale, DWORD dwflags,
3288                                LPCWSTR lpvalue,  const NUMBERFMTW * lpFormat,
3289                                LPWSTR lpNumberStr, int cchNumber)
3290 {
3291  FIXME("%s: stub, no reformatting done\n",debugstr_w(lpvalue));
3292
3293  lstrcpynW( lpNumberStr, lpvalue, cchNumber );
3294  return cchNumber? strlenW( lpNumberStr ) : 0;
3295 }
3296
3297 /**************************************************************************
3298  *              GetCurrencyFormatA      (KERNEL32.@)
3299  */
3300 INT WINAPI GetCurrencyFormatA(LCID locale, DWORD dwflags,
3301                                LPCSTR lpvalue,   const CURRENCYFMTA * lpFormat,
3302                                LPSTR lpCurrencyStr, int cchCurrency)
3303 {
3304     UINT   nPosOrder, nNegOrder;
3305     INT    retVal;
3306     char   sDestination[128], sNegOrder[8], sPosOrder[8], sCurrencySymbol[8];
3307     char   *pDestination = sDestination;
3308     char   sNumberFormated[128];
3309     char   *pNumberFormated = sNumberFormated;
3310     LCID   systemDefaultLCID;
3311     BOOL   bIsPositive = FALSE, bValidFormat = FALSE;
3312     enum   Operations
3313     {
3314         USE_PARAMETER,
3315         USE_LOCALEINFO,
3316         USE_SYSTEMDEFAULT,
3317         RETURN_ERROR
3318     } used_operation;
3319
3320     NUMBERFMTA  numberFmt;
3321
3322     /* Which source will we use to format the string */
3323     used_operation = RETURN_ERROR;
3324     if (lpFormat != NULL)
3325     {
3326         if (dwflags == 0)
3327             used_operation = USE_PARAMETER;
3328     }
3329     else
3330     {
3331         if (dwflags & LOCALE_NOUSEROVERRIDE)
3332             used_operation = USE_SYSTEMDEFAULT;
3333         else
3334             used_operation = USE_LOCALEINFO;
3335     }
3336
3337     /* Load the fields we need */
3338     switch(used_operation)
3339     {
3340     case USE_LOCALEINFO:
3341         /* Specific to CURRENCYFMTA */
3342         GetLocaleInfoA(locale, LOCALE_INEGCURR, sNegOrder, sizeof(sNegOrder));
3343         GetLocaleInfoA(locale, LOCALE_ICURRENCY, sPosOrder, sizeof(sPosOrder));
3344         GetLocaleInfoA(locale, LOCALE_SCURRENCY, sCurrencySymbol, sizeof(sCurrencySymbol));
3345
3346         nPosOrder = atoi(sPosOrder);
3347         nNegOrder = atoi(sNegOrder);
3348         break;
3349     case USE_PARAMETER:
3350         /* Specific to CURRENCYFMTA */
3351         nNegOrder = lpFormat->NegativeOrder;
3352         nPosOrder = lpFormat->PositiveOrder;
3353         strcpy(sCurrencySymbol, lpFormat->lpCurrencySymbol);
3354         break;
3355     case USE_SYSTEMDEFAULT:
3356         systemDefaultLCID = GetSystemDefaultLCID();
3357         /* Specific to CURRENCYFMTA */
3358         GetLocaleInfoA(systemDefaultLCID, LOCALE_INEGCURR, sNegOrder, sizeof(sNegOrder));
3359         GetLocaleInfoA(systemDefaultLCID, LOCALE_ICURRENCY, sPosOrder, sizeof(sPosOrder));
3360         GetLocaleInfoA(systemDefaultLCID, LOCALE_SCURRENCY, sCurrencySymbol, sizeof(sCurrencySymbol));
3361
3362         nPosOrder = atoi(sPosOrder);
3363         nNegOrder = atoi(sNegOrder);
3364         break;
3365     default:
3366         SetLastError(ERROR_INVALID_PARAMETER);
3367         return 0;
3368     }
3369
3370     /* Construct a temporary number format structure */
3371     if (lpFormat != NULL)
3372     {
3373         numberFmt.NumDigits     = lpFormat->NumDigits;
3374         numberFmt.LeadingZero   = lpFormat->LeadingZero;
3375         numberFmt.Grouping      = lpFormat->Grouping;
3376         numberFmt.NegativeOrder = 0;
3377         numberFmt.lpDecimalSep = lpFormat->lpDecimalSep;
3378         numberFmt.lpThousandSep = lpFormat->lpThousandSep;
3379         bValidFormat = TRUE;
3380     }
3381
3382     /* Make a call to GetNumberFormatA() */
3383     if (*lpvalue == '-')
3384     {
3385         bIsPositive = FALSE;
3386         retVal = GetNumberFormatA(locale,0,lpvalue+1,(bValidFormat)?&numberFmt:NULL,pNumberFormated,128);
3387     }
3388     else
3389     {
3390         bIsPositive = TRUE;
3391         retVal = GetNumberFormatA(locale,0,lpvalue,(bValidFormat)?&numberFmt:NULL,pNumberFormated,128);
3392     }
3393
3394     if (retVal == 0)
3395         return 0;
3396
3397     /* construct the formatted string */
3398     if (bIsPositive)
3399     {
3400         switch (nPosOrder)
3401         {
3402         case 0:   /* Prefix, no separation */
3403             strcpy (pDestination, sCurrencySymbol);
3404             strcat (pDestination, pNumberFormated);
3405             break;
3406         case 1:   /* Suffix, no separation */
3407             strcpy (pDestination, pNumberFormated);
3408             strcat (pDestination, sCurrencySymbol);
3409             break;
3410         case 2:   /* Prefix, 1 char separation */
3411             strcpy (pDestination, sCurrencySymbol);
3412             strcat (pDestination, " ");
3413             strcat (pDestination, pNumberFormated);
3414             break;
3415         case 3:   /* Suffix, 1 char separation */
3416             strcpy (pDestination, pNumberFormated);
3417             strcat (pDestination, " ");
3418             strcat (pDestination, sCurrencySymbol);
3419             break;
3420         default:
3421             SetLastError(ERROR_INVALID_PARAMETER);
3422             return 0;
3423         }
3424     }
3425     else  /* negative number */
3426     {
3427         switch (nNegOrder)
3428         {
3429         case 0:   /* format: ($1.1) */
3430             strcpy (pDestination, "(");
3431             strcat (pDestination, sCurrencySymbol);
3432             strcat (pDestination, pNumberFormated);
3433             strcat (pDestination, ")");
3434             break;
3435         case 1:   /* format: -$1.1 */
3436             strcpy (pDestination, "-");
3437             strcat (pDestination, sCurrencySymbol);
3438             strcat (pDestination, pNumberFormated);
3439             break;
3440         case 2:   /* format: $-1.1 */
3441             strcpy (pDestination, sCurrencySymbol);
3442             strcat (pDestination, "-");
3443             strcat (pDestination, pNumberFormated);
3444             break;
3445         case 3:   /* format: $1.1- */
3446             strcpy (pDestination, sCurrencySymbol);
3447             strcat (pDestination, pNumberFormated);
3448             strcat (pDestination, "-");
3449             break;
3450         case 4:   /* format: (1.1$) */
3451             strcpy (pDestination, "(");
3452             strcat (pDestination, pNumberFormated);
3453             strcat (pDestination, sCurrencySymbol);
3454             strcat (pDestination, ")");
3455             break;
3456         case 5:   /* format: -1.1$ */
3457             strcpy (pDestination, "-");
3458             strcat (pDestination, pNumberFormated);
3459             strcat (pDestination, sCurrencySymbol);
3460             break;
3461         case 6:   /* format: 1.1-$ */
3462             strcpy (pDestination, pNumberFormated);
3463             strcat (pDestination, "-");
3464             strcat (pDestination, sCurrencySymbol);
3465             break;
3466         case 7:   /* format: 1.1$- */
3467             strcpy (pDestination, pNumberFormated);
3468             strcat (pDestination, sCurrencySymbol);
3469             strcat (pDestination, "-");
3470             break;
3471         case 8:   /* format: -1.1 $ */
3472             strcpy (pDestination, "-");
3473             strcat (pDestination, pNumberFormated);
3474             strcat (pDestination, " ");
3475             strcat (pDestination, sCurrencySymbol);
3476             break;
3477         case 9:   /* format: -$ 1.1 */
3478             strcpy (pDestination, "-");
3479             strcat (pDestination, sCurrencySymbol);
3480             strcat (pDestination, " ");
3481             strcat (pDestination, pNumberFormated);
3482             break;
3483         case 10:   /* format: 1.1 $- */
3484             strcpy (pDestination, pNumberFormated);
3485             strcat (pDestination, " ");
3486             strcat (pDestination, sCurrencySymbol);
3487             strcat (pDestination, "-");
3488             break;
3489         case 11:   /* format: $ 1.1- */
3490             strcpy (pDestination, sCurrencySymbol);
3491             strcat (pDestination, " ");
3492             strcat (pDestination, pNumberFormated);
3493             strcat (pDestination, "-");
3494             break;
3495         case 12:   /* format: $ -1.1 */
3496             strcpy (pDestination, sCurrencySymbol);
3497             strcat (pDestination, " ");
3498             strcat (pDestination, "-");
3499             strcat (pDestination, pNumberFormated);
3500             break;
3501         case 13:   /* format: 1.1- $ */
3502             strcpy (pDestination, pNumberFormated);
3503             strcat (pDestination, "-");
3504             strcat (pDestination, " ");
3505             strcat (pDestination, sCurrencySymbol);
3506             break;
3507         case 14:   /* format: ($ 1.1) */
3508             strcpy (pDestination, "(");
3509             strcat (pDestination, sCurrencySymbol);
3510             strcat (pDestination, " ");
3511             strcat (pDestination, pNumberFormated);
3512             strcat (pDestination, ")");
3513             break;
3514         case 15:   /* format: (1.1 $) */
3515             strcpy (pDestination, "(");
3516             strcat (pDestination, pNumberFormated);
3517             strcat (pDestination, " ");
3518             strcat (pDestination, sCurrencySymbol);
3519             strcat (pDestination, ")");
3520             break;
3521         default:
3522             SetLastError(ERROR_INVALID_PARAMETER);
3523             return 0;
3524         }
3525     }
3526
3527     retVal = strlen(pDestination) + 1;
3528
3529     if (cchCurrency)
3530     {
3531         memcpy( lpCurrencyStr, pDestination, min(cchCurrency, retVal) );
3532         if (cchCurrency < retVal) retVal = 0;
3533     }
3534     return retVal;
3535 }
3536
3537 /**************************************************************************
3538  *              GetCurrencyFormatW      (KERNEL32.@)
3539  */
3540 INT WINAPI GetCurrencyFormatW(LCID locale, DWORD dwflags,
3541                                LPCWSTR lpvalue,   const CURRENCYFMTW * lpFormat,
3542                                LPWSTR lpCurrencyStr, int cchCurrency)
3543 {
3544     FIXME("This API function is NOT implemented !\n");
3545     return 0;
3546 }
3547
3548 /******************************************************************************
3549  *              OLE2NLS_CheckLocale     [intern]
3550  */
3551 static LCID OLE2NLS_CheckLocale (LCID locale)
3552 {
3553         if (!locale)
3554         { locale = LOCALE_SYSTEM_DEFAULT;
3555         }
3556
3557         if (locale == LOCALE_SYSTEM_DEFAULT)
3558         { return GetSystemDefaultLCID();
3559         }
3560         else if (locale == LOCALE_USER_DEFAULT)
3561         { return GetUserDefaultLCID();
3562         }
3563         else
3564         { return locale;
3565         }
3566 }
3567 /******************************************************************************
3568  *              GetTimeFormatA  [KERNEL32.@]
3569  * Makes an ASCII string of the time
3570  *
3571  * Formats date according to format,  or locale default if format is
3572  * NULL. The format consists of literal characters and fields as follows:
3573  *
3574  * h  hours with no leading zero (12-hour)
3575  * hh hours with full two digits
3576  * H  hours with no leading zero (24-hour)
3577  * HH hours with full two digits
3578  * m  minutes with no leading zero
3579  * mm minutes with full two digits
3580  * s  seconds with no leading zero
3581  * ss seconds with full two digits
3582  * t  time marker (A or P)
3583  * tt time marker (AM, PM)
3584  *
3585  */
3586 INT WINAPI
3587 GetTimeFormatA(LCID locale,        /* [in]  */
3588                DWORD flags,        /* [in]  */
3589                const SYSTEMTIME* xtime, /* [in]  */
3590                LPCSTR format,      /* [in]  */
3591                LPSTR timestr,      /* [out] */
3592                INT timelen         /* [in]  */)
3593 { char format_buf[40];
3594   LPCSTR thisformat;
3595   SYSTEMTIME t;
3596   const SYSTEMTIME* thistime;
3597   LCID thislocale=0;
3598   DWORD thisflags=LOCALE_STIMEFORMAT; /* standard timeformat */
3599   INT ret;
3600
3601   TRACE("GetTimeFormat(0x%04lx,0x%08lx,%p,%s,%p,%d)\n",locale,flags,xtime,format,timestr,timelen);
3602
3603   thislocale = OLE2NLS_CheckLocale ( locale );
3604
3605   if (format == NULL)
3606   { if (flags & LOCALE_NOUSEROVERRIDE)  /* use system default */
3607     { thislocale = GetSystemDefaultLCID();
3608     }
3609     GetLocaleInfoA(thislocale, thisflags, format_buf, sizeof(format_buf));
3610     thisformat = format_buf;
3611   }
3612   else
3613   { thisformat = format;
3614   }
3615
3616   if (xtime == NULL) /* NULL means use the current local time */
3617   { GetLocalTime(&t);
3618     thistime = &t;
3619   }
3620   else
3621   { thistime = xtime;
3622   /* Check that hour,min and sec is in range */
3623   }
3624   ret = OLE_GetFormatA(thislocale, thisflags, flags, thistime, thisformat,
3625                          timestr, timelen);
3626   return ret;
3627 }
3628
3629
3630 /******************************************************************************
3631  *              GetTimeFormatW  [KERNEL32.@]
3632  * Makes a Unicode string of the time
3633  */
3634 INT WINAPI
3635 GetTimeFormatW(LCID locale,        /* [in]  */
3636                DWORD flags,        /* [in]  */
3637                const SYSTEMTIME* xtime, /* [in]  */
3638                LPCWSTR format,     /* [in]  */
3639                LPWSTR timestr,     /* [out] */
3640                INT timelen         /* [in]  */)
3641 {       WCHAR format_buf[40];
3642         LPCWSTR thisformat;
3643         SYSTEMTIME t;
3644         const SYSTEMTIME* thistime;
3645         LCID thislocale=0;
3646         DWORD thisflags=LOCALE_STIMEFORMAT; /* standard timeformat */
3647         INT ret;
3648
3649         TRACE("GetTimeFormat(0x%04lx,0x%08lx,%p,%s,%p,%d)\n",locale,flags,
3650         xtime,debugstr_w(format),timestr,timelen);
3651
3652         thislocale = OLE2NLS_CheckLocale ( locale );
3653
3654         if (format == NULL)
3655         { if (flags & LOCALE_NOUSEROVERRIDE)  /* use system default */
3656           { thislocale = GetSystemDefaultLCID();
3657           }
3658           GetLocaleInfoW(thislocale, thisflags, format_buf, 40);
3659           thisformat = format_buf;
3660         }
3661         else
3662         { thisformat = format;
3663         }
3664
3665         if (xtime == NULL) /* NULL means use the current local time */
3666         { GetLocalTime(&t);
3667           thistime = &t;
3668         }
3669         else
3670         { thistime = xtime;
3671         }
3672
3673         ret = OLE_GetFormatW(thislocale, thisflags, flags, thistime, thisformat,
3674                          timestr, timelen);
3675         return ret;
3676 }
3677
3678 /******************************************************************************
3679  *              EnumCalendarInfoA       [KERNEL32.@]
3680  */
3681 BOOL WINAPI EnumCalendarInfoA(
3682         CALINFO_ENUMPROCA calinfoproc,LCID locale,CALID calendar,CALTYPE caltype
3683 ) {
3684         FIXME("(%p,0x%04lx,0x%08lx,0x%08lx),stub!\n",calinfoproc,locale,calendar,caltype);
3685         return FALSE;
3686 }