quartz: Make dwSamplesProcessed a longlong.
[wine] / programs / winhelp / hlpfile.c
1 /*
2  * Help Viewer
3  *
4  * Copyright    1996 Ulrich Schmid
5  *              2002, 2008 Eric Pouech
6  *              2007 Kirill K. Smirnov
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "wingdi.h"
30 #include "winuser.h"
31 #include "winhelp.h"
32
33 #include "wine/debug.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(winhelp);
36
37 static inline unsigned short GET_USHORT(const BYTE* buffer, unsigned i)
38 {
39     return (BYTE)buffer[i] + 0x100 * (BYTE)buffer[i + 1];
40 }
41
42 static inline short GET_SHORT(const BYTE* buffer, unsigned i)
43 {
44     return (BYTE)buffer[i] + 0x100 * (signed char)buffer[i+1];
45 }
46
47 static inline unsigned GET_UINT(const BYTE* buffer, unsigned i)
48 {
49     return GET_USHORT(buffer, i) + 0x10000 * GET_USHORT(buffer, i + 2);
50 }
51
52 static HLPFILE *first_hlpfile = 0;
53
54 static struct
55 {
56     UINT                wFont;
57     UINT                wIndent;
58     UINT                wHSpace;
59     UINT                wVSpace;
60     HLPFILE_LINK*       link;
61 } attributes;
62
63 static BOOL  HLPFILE_DoReadHlpFile(HLPFILE*, LPCSTR);
64 static BOOL  HLPFILE_ReadFileToBuffer(HLPFILE*, HFILE);
65 static BOOL  HLPFILE_FindSubFile(HLPFILE*, LPCSTR, BYTE**, BYTE**);
66 static BOOL  HLPFILE_SystemCommands(HLPFILE*);
67 static INT   HLPFILE_UncompressedLZ77_Size(BYTE *ptr, BYTE *end);
68 static BYTE* HLPFILE_UncompressLZ77(BYTE *ptr, BYTE *end, BYTE *newptr);
69 static BOOL  HLPFILE_UncompressLZ77_Phrases(HLPFILE*);
70 static BOOL  HLPFILE_Uncompress_Phrases40(HLPFILE*);
71 static BOOL  HLPFILE_Uncompress_Topic(HLPFILE*);
72 static BOOL  HLPFILE_GetContext(HLPFILE*);
73 static BOOL  HLPFILE_GetKeywords(HLPFILE*);
74 static BOOL  HLPFILE_GetMap(HLPFILE*);
75 static BOOL  HLPFILE_AddPage(HLPFILE*, BYTE*, BYTE*, unsigned, unsigned);
76 static BOOL  HLPFILE_SkipParagraph(HLPFILE*, BYTE *, BYTE*, unsigned*);
77 static void  HLPFILE_Uncompress2(HLPFILE*, const BYTE*, const BYTE*, BYTE*, const BYTE*);
78 static BOOL  HLPFILE_Uncompress3(HLPFILE*, char*, const char*, const BYTE*, const BYTE*);
79 static void  HLPFILE_UncompressRLE(const BYTE* src, const BYTE* end, BYTE** dst, unsigned dstsz);
80 static BOOL  HLPFILE_ReadFont(HLPFILE* hlpfile);
81
82 /***********************************************************************
83  *
84  *           HLPFILE_PageByNumber
85  */
86 static HLPFILE_PAGE *HLPFILE_PageByNumber(HLPFILE* hlpfile, UINT wNum)
87 {
88     HLPFILE_PAGE *page;
89     UINT          temp = wNum;
90
91     WINE_TRACE("<%s>[%u]\n", hlpfile->lpszPath, wNum);
92
93     for (page = hlpfile->first_page; page && temp; page = page->next) temp--;
94     if (!page)
95         WINE_ERR("Page of number %u not found in file %s\n", wNum, hlpfile->lpszPath);
96     return page;
97 }
98
99 /******************************************************************
100  *              HLPFILE_PageByOffset
101  *
102  *
103  */
104 HLPFILE_PAGE *HLPFILE_PageByOffset(HLPFILE* hlpfile, LONG offset, ULONG* relative)
105 {
106     HLPFILE_PAGE*       page;
107     HLPFILE_PAGE*       found;
108
109     if (!hlpfile) return 0;
110
111     WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, offset);
112
113     if (offset == 0xFFFFFFFF) return NULL;
114     page = NULL;
115
116     for (found = NULL, page = hlpfile->first_page; page; page = page->next)
117     {
118         if (page->offset <= offset && (!found || found->offset < page->offset))
119         {
120             *relative = offset - page->offset;
121             found = page;
122         }
123     }
124     if (!found)
125         WINE_ERR("Page of offset %u not found in file %s\n",
126                  offset, hlpfile->lpszPath);
127     return found;
128 }
129
130 /**************************************************************************
131  * comp_PageByHash
132  *
133  * HLPFILE_BPTreeCompare function for '|CONTEXT' B+ tree file
134  *
135  */
136 static int comp_PageByHash(void *p, const void *key,
137                            int leaf, void** next)
138 {
139     LONG lKey = (LONG_PTR)key;
140     LONG lTest = (INT)GET_UINT(p, 0);
141
142     *next = (char *)p+(leaf?8:6);
143     WINE_TRACE("Comparing '%d' with '%d'\n", lKey, lTest);
144     if (lTest < lKey) return -1;
145     if (lTest > lKey) return 1;
146     return 0;
147 }
148
149 /***********************************************************************
150  *
151  *           HLPFILE_PageByHash
152  */
153 HLPFILE_PAGE *HLPFILE_PageByHash(HLPFILE* hlpfile, LONG lHash, ULONG* relative)
154 {
155     BYTE *ptr;
156
157     if (!hlpfile) return NULL;
158     if (!lHash) return HLPFILE_Contents(hlpfile, relative);
159
160     WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, lHash);
161
162     /* For win 3.0 files hash values are really page numbers */
163     if (hlpfile->version <= 16)
164     {
165         *relative = 0;
166         return HLPFILE_PageByNumber(hlpfile, lHash);
167     }
168
169     ptr = HLPFILE_BPTreeSearch(hlpfile->Context, LongToPtr(lHash), comp_PageByHash);
170     if (!ptr)
171     {
172         WINE_ERR("Page of hash %x not found in file %s\n", lHash, hlpfile->lpszPath);
173         return NULL;
174     }
175
176     return HLPFILE_PageByOffset(hlpfile, GET_UINT(ptr, 4), relative);
177 }
178
179 /***********************************************************************
180  *
181  *           HLPFILE_PageByMap
182  */
183 HLPFILE_PAGE *HLPFILE_PageByMap(HLPFILE* hlpfile, LONG lMap, ULONG* relative)
184 {
185     unsigned int i;
186
187     if (!hlpfile) return 0;
188
189     WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, lMap);
190
191     for (i = 0; i < hlpfile->wMapLen; i++)
192     {
193         if (hlpfile->Map[i].lMap == lMap)
194             return HLPFILE_PageByOffset(hlpfile, hlpfile->Map[i].offset, relative);
195     }
196
197     WINE_ERR("Page of Map %x not found in file %s\n", lMap, hlpfile->lpszPath);
198     return NULL;
199 }
200
201 /***********************************************************************
202  *
203  *           HLPFILE_Contents
204  */
205 HLPFILE_PAGE* HLPFILE_Contents(HLPFILE *hlpfile, ULONG* relative)
206 {
207     HLPFILE_PAGE*       page = NULL;
208
209     if (!hlpfile) return NULL;
210
211     page = HLPFILE_PageByOffset(hlpfile, hlpfile->contents_start, relative);
212     if (!page)
213     {
214         page = hlpfile->first_page;
215         *relative = 0;
216     }
217     return page;
218 }
219
220 /***********************************************************************
221  *
222  *           HLPFILE_Hash
223  */
224 LONG HLPFILE_Hash(LPCSTR lpszContext)
225 {
226     LONG lHash = 0;
227     CHAR c;
228
229     while ((c = *lpszContext++))
230     {
231         CHAR x = 0;
232         if (c >= 'A' && c <= 'Z') x = c - 'A' + 17;
233         if (c >= 'a' && c <= 'z') x = c - 'a' + 17;
234         if (c >= '1' && c <= '9') x = c - '0';
235         if (c == '0') x = 10;
236         if (c == '.') x = 12;
237         if (c == '_') x = 13;
238         if (x) lHash = lHash * 43 + x;
239     }
240     return lHash;
241 }
242
243 /***********************************************************************
244  *
245  *           HLPFILE_ReadHlpFile
246  */
247 HLPFILE *HLPFILE_ReadHlpFile(LPCSTR lpszPath)
248 {
249     HLPFILE*      hlpfile;
250
251     for (hlpfile = first_hlpfile; hlpfile; hlpfile = hlpfile->next)
252     {
253         if (!strcmp(lpszPath, hlpfile->lpszPath))
254         {
255             hlpfile->wRefCount++;
256             return hlpfile;
257         }
258     }
259
260     hlpfile = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
261                         sizeof(HLPFILE) + lstrlen(lpszPath) + 1);
262     if (!hlpfile) return 0;
263
264     hlpfile->lpszPath           = (char*)hlpfile + sizeof(HLPFILE);
265     hlpfile->contents_start     = 0xFFFFFFFF;
266     hlpfile->next               = first_hlpfile;
267     hlpfile->wRefCount          = 1;
268
269     strcpy(hlpfile->lpszPath, lpszPath);
270
271     first_hlpfile = hlpfile;
272     if (hlpfile->next) hlpfile->next->prev = hlpfile;
273
274     if (!HLPFILE_DoReadHlpFile(hlpfile, lpszPath))
275     {
276         HLPFILE_FreeHlpFile(hlpfile);
277         hlpfile = 0;
278     }
279
280     return hlpfile;
281 }
282
283 /***********************************************************************
284  *
285  *           HLPFILE_DoReadHlpFile
286  */
287 static BOOL HLPFILE_DoReadHlpFile(HLPFILE *hlpfile, LPCSTR lpszPath)
288 {
289     BOOL        ret;
290     HFILE       hFile;
291     OFSTRUCT    ofs;
292     BYTE*       buf;
293     DWORD       ref = 0x0C;
294     unsigned    index, old_index, offset, len, offs;
295
296     hFile = OpenFile(lpszPath, &ofs, OF_READ);
297     if (hFile == HFILE_ERROR) return FALSE;
298
299     ret = HLPFILE_ReadFileToBuffer(hlpfile, hFile);
300     _lclose(hFile);
301     if (!ret) return FALSE;
302
303     if (!HLPFILE_SystemCommands(hlpfile)) return FALSE;
304
305     /* load phrases support */
306     if (!HLPFILE_UncompressLZ77_Phrases(hlpfile))
307         HLPFILE_Uncompress_Phrases40(hlpfile);
308
309     if (!HLPFILE_Uncompress_Topic(hlpfile)) return FALSE;
310     if (!HLPFILE_ReadFont(hlpfile)) return FALSE;
311
312     buf = hlpfile->topic_map[0];
313     old_index = -1;
314     offs = 0;
315     do
316     {
317         BYTE*   end;
318
319         if (hlpfile->version <= 16)
320         {
321             index  = (ref - 0x0C) / hlpfile->dsize;
322             offset = (ref - 0x0C) % hlpfile->dsize;
323         }
324         else
325         {
326             index  = (ref - 0x0C) >> 14;
327             offset = (ref - 0x0C) & 0x3FFF;
328         }
329
330         if (hlpfile->version <= 16 && index != old_index && old_index != -1)
331         {
332             /* we jumped to the next block, adjust pointers */
333             ref -= 12;
334             offset -= 12;
335         }
336
337         WINE_TRACE("ref=%08x => [%u/%u]\n", ref, index, offset);
338
339         if (index >= hlpfile->topic_maplen) {WINE_WARN("maplen\n"); break;}
340         buf = hlpfile->topic_map[index] + offset;
341         if (buf + 0x15 >= hlpfile->topic_end) {WINE_WARN("extra\n"); break;}
342         end = min(buf + GET_UINT(buf, 0), hlpfile->topic_end);
343         if (index != old_index) {offs = 0; old_index = index;}
344
345         switch (buf[0x14])
346         {
347         case 0x02:
348             if (!HLPFILE_AddPage(hlpfile, buf, end, ref, index * 0x8000L + offs)) return FALSE;
349             break;
350
351         case 0x01:
352         case 0x20:
353         case 0x23:
354             if (!HLPFILE_SkipParagraph(hlpfile, buf, end, &len)) return FALSE;
355             offs += len;
356             break;
357
358         default:
359             WINE_ERR("buf[0x14] = %x\n", buf[0x14]);
360         }
361
362         if (hlpfile->version <= 16)
363         {
364             ref += GET_UINT(buf, 0xc);
365             if (GET_UINT(buf, 0xc) == 0)
366                 break;
367         }
368         else
369             ref = GET_UINT(buf, 0xc);
370     } while (ref != 0xffffffff);
371
372     HLPFILE_GetKeywords(hlpfile);
373     HLPFILE_GetMap(hlpfile);
374     if (hlpfile->version <= 16) return TRUE;
375     return HLPFILE_GetContext(hlpfile);
376 }
377
378 /***********************************************************************
379  *
380  *           HLPFILE_AddPage
381  */
382 static BOOL HLPFILE_AddPage(HLPFILE *hlpfile, BYTE *buf, BYTE *end, unsigned ref, unsigned offset)
383 {
384     HLPFILE_PAGE* page;
385     BYTE*         title;
386     UINT          titlesize, blocksize, datalen;
387     char*         ptr;
388     HLPFILE_MACRO*macro;
389
390     blocksize = GET_UINT(buf, 0);
391     datalen = GET_UINT(buf, 0x10);
392     title = buf + datalen;
393     if (title > end) {WINE_WARN("page2\n"); return FALSE;};
394
395     titlesize = GET_UINT(buf, 4);
396     page = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_PAGE) + titlesize + 1);
397     if (!page) return FALSE;
398     page->lpszTitle = (char*)page + sizeof(HLPFILE_PAGE);
399
400     if (titlesize > blocksize - datalen)
401     {
402         /* need to decompress */
403         if (hlpfile->hasPhrases)
404             HLPFILE_Uncompress2(hlpfile, title, end, (BYTE*)page->lpszTitle, (BYTE*)page->lpszTitle + titlesize);
405         else if (hlpfile->hasPhrases40)
406             HLPFILE_Uncompress3(hlpfile, page->lpszTitle, page->lpszTitle + titlesize, title, end);
407         else
408         {
409             WINE_FIXME("Text size is too long, splitting\n");
410             titlesize = blocksize - datalen;
411             memcpy(page->lpszTitle, title, titlesize);
412         }
413     }
414     else
415         memcpy(page->lpszTitle, title, titlesize);
416
417     page->lpszTitle[titlesize] = '\0';
418
419     if (hlpfile->first_page)
420     {
421         hlpfile->last_page->next = page;
422         page->prev = hlpfile->last_page;
423         hlpfile->last_page = page;
424     }
425     else
426     {
427         hlpfile->first_page = page;
428         hlpfile->last_page = page;
429         page->prev = NULL;
430     }
431
432     page->file            = hlpfile;
433     page->next            = NULL;
434     page->first_paragraph = NULL;
435     page->first_macro     = NULL;
436     page->first_link      = NULL;
437     page->wNumber         = GET_UINT(buf, 0x21);
438     page->offset          = offset;
439     page->reference       = ref;
440
441     page->browse_bwd = GET_UINT(buf, 0x19);
442     page->browse_fwd = GET_UINT(buf, 0x1D);
443
444     WINE_TRACE("Added page[%d]: title='%s' %08x << %08x >> %08x\n",
445                page->wNumber, page->lpszTitle, 
446                page->browse_bwd, page->offset, page->browse_fwd);
447
448     memset(&attributes, 0, sizeof(attributes));
449
450     /* now load macros */
451     ptr = page->lpszTitle + strlen(page->lpszTitle) + 1;
452     while (ptr < page->lpszTitle + titlesize)
453     {
454         unsigned len = strlen(ptr);
455         char*    macro_str;
456
457         WINE_TRACE("macro: %s\n", ptr);
458         macro = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_MACRO) + len + 1);
459         macro->lpszMacro = macro_str = (char*)(macro + 1);
460         memcpy(macro_str, ptr, len + 1);
461         /* FIXME: shall we really link macro in reverse order ??
462          * may produce strange results when played at page opening
463          */
464         macro->next = page->first_macro;
465         page->first_macro = macro;
466         ptr += len + 1;
467     }
468
469     return TRUE;
470 }
471
472 static long fetch_long(BYTE** ptr)
473 {
474     long        ret;
475
476     if (*(*ptr) & 1)
477     {
478         ret = (*(unsigned long*)(*ptr) - 0x80000000L) / 2;
479         (*ptr) += 4;
480     }
481     else
482     {
483         ret = (*(unsigned short*)(*ptr) - 0x8000) / 2;
484         (*ptr) += 2;
485     }
486
487     return ret;
488 }
489
490 static unsigned long fetch_ulong(BYTE** ptr)
491 {
492     unsigned long        ret;
493
494     if (*(*ptr) & 1)
495     {
496         ret = *(unsigned long*)(*ptr) / 2;
497         (*ptr) += 4;
498     }
499     else
500     {
501         ret = *(unsigned short*)(*ptr) / 2;
502         (*ptr) += 2;
503     }
504     return ret;
505 }    
506
507 static short fetch_short(BYTE** ptr)
508 {
509     short       ret;
510
511     if (*(*ptr) & 1)
512     {
513         ret = (*(unsigned short*)(*ptr) - 0x8000) / 2;
514         (*ptr) += 2;
515     }
516     else
517     {
518         ret = (*(unsigned char*)(*ptr) - 0x80) / 2;
519         (*ptr)++;
520     }
521     return ret;
522 }
523
524 static unsigned short fetch_ushort(BYTE** ptr)
525 {
526     unsigned short ret;
527
528     if (*(*ptr) & 1)
529     {
530         ret = *(unsigned short*)(*ptr) / 2;
531         (*ptr) += 2;
532     }
533     else
534     {
535         ret = *(unsigned char*)(*ptr) / 2;
536         (*ptr)++;
537     }
538     return ret;
539 }
540
541 /***********************************************************************
542  *
543  *           HLPFILE_SkipParagraph
544  */
545 static BOOL HLPFILE_SkipParagraph(HLPFILE *hlpfile, BYTE *buf, BYTE *end, unsigned* len)
546 {
547     BYTE              *tmp;
548
549     if (!hlpfile->first_page) {WINE_WARN("no page\n"); return FALSE;};
550     if (buf + 0x19 > end) {WINE_WARN("header too small\n"); return FALSE;};
551
552     tmp = buf + 0x15;
553     if (buf[0x14] == 0x20 || buf[0x14] == 0x23)
554     {
555         fetch_long(&tmp);
556         *len = fetch_ushort(&tmp);
557     }
558     else *len = end-buf-15;
559
560     return TRUE;
561 }
562
563 /******************************************************************
564  *              HLPFILE_DecompressGfx
565  *
566  * Decompress the data part of a bitmap or a metafile
567  */
568 static BYTE*    HLPFILE_DecompressGfx(BYTE* src, unsigned csz, unsigned sz, BYTE packing)
569 {
570     BYTE*       dst;
571     BYTE*       tmp;
572     BYTE*       tmp2;
573     unsigned    sz77;
574
575     WINE_TRACE("Unpacking (%d) from %u bytes to %u bytes\n", packing, csz, sz);
576
577     switch (packing)
578     {
579     case 0: /* uncompressed */
580         if (sz != csz)
581             WINE_WARN("Bogus gfx sizes (uncompressed): %u / %u\n", sz, csz);
582         dst = src;
583         break;
584     case 1: /* RunLen */
585         tmp = dst = HeapAlloc(GetProcessHeap(), 0, sz);
586         if (!dst) return NULL;
587         HLPFILE_UncompressRLE(src, src + csz, &tmp, sz);
588         if (tmp - dst != sz)
589             WINE_WARN("Bogus gfx sizes (RunLen): %lu/%u\n", (SIZE_T)(tmp - dst), sz);
590         break;
591     case 2: /* LZ77 */
592         sz77 = HLPFILE_UncompressedLZ77_Size(src, src + csz);
593         dst = HeapAlloc(GetProcessHeap(), 0, sz77);
594         if (!dst) return NULL;
595         HLPFILE_UncompressLZ77(src, src + csz, dst);
596         if (sz77 != sz)
597             WINE_WARN("Bogus gfx sizes (LZ77): %u / %u\n", sz77, sz);
598         break;
599     case 3: /* LZ77 then RLE */
600         sz77 = HLPFILE_UncompressedLZ77_Size(src, src + csz);
601         tmp = HeapAlloc(GetProcessHeap(), 0, sz77);
602         if (!tmp) return FALSE;
603         HLPFILE_UncompressLZ77(src, src + csz, tmp);
604         dst = tmp2 = HeapAlloc(GetProcessHeap(), 0, sz);
605         if (!dst)
606         {
607             HeapFree(GetProcessHeap(), 0, tmp);
608             return FALSE;
609         }
610         HLPFILE_UncompressRLE(tmp, tmp + sz77, &tmp2, sz);
611         if (tmp2 - dst != sz)
612             WINE_WARN("Bogus gfx sizes (LZ77+RunLen): %lu / %u\n", (SIZE_T)(tmp2 - dst), sz);
613         HeapFree(GetProcessHeap(), 0, tmp);
614         break;
615     default:
616         WINE_FIXME("Unsupported packing %u\n", packing);
617         return NULL;
618     }
619     return dst;
620 }
621
622 static BOOL HLPFILE_RtfAddRawString(struct RtfData* rd, const char* str, size_t sz)
623 {
624     if (!rd) return TRUE; /* FIXME: TEMP */
625     if (rd->ptr + sz >= rd->data + rd->allocated)
626     {
627         char*   new = HeapReAlloc(GetProcessHeap(), 0, rd->data, rd->allocated *= 2);
628         if (!new) return FALSE;
629         rd->ptr = new + (rd->ptr - rd->data);
630         rd->data = new;
631     }
632     memcpy(rd->ptr, str, sz);
633     rd->ptr += sz;
634
635     return TRUE;
636 }
637
638 static BOOL HLPFILE_RtfAddControl(struct RtfData* rd, const char* str)
639 {
640     if (!rd) return TRUE; /* FIXME: TEMP */
641     if (*str == '\\' || *str == '{') rd->in_text = FALSE;
642     else if (*str == '}') rd->in_text = TRUE;
643     return HLPFILE_RtfAddRawString(rd, str, strlen(str));
644 }
645
646 static BOOL HLPFILE_RtfAddText(struct RtfData* rd, const char* str)
647 {
648     const char* p;
649     const char* last;
650     const char* replace;
651     unsigned    rlen;
652
653     if (!rd) return TRUE; /* FIXME: TEMP */
654     if (!rd->in_text)
655     {
656         if (!HLPFILE_RtfAddRawString(rd, " ", 1)) return FALSE;
657         rd->in_text = TRUE;
658     }
659     for (last = p = str; *p; p++)
660     {
661         if (*p < 0) /* escape non ASCII chars */
662         {
663             static char         xx[8];
664             rlen = sprintf(xx, "\\'%x", *(const BYTE*)p);
665             replace = xx;
666         }
667         else switch (*p)
668         {
669         case '{':  rlen = 2; replace = "\\{";  break;
670         case '}':  rlen = 2; replace = "\\}";  break;
671         case '\\': rlen = 2; replace = "\\\\"; break;
672         default:   continue;
673         }
674         if ((p != last && !HLPFILE_RtfAddRawString(rd, last, p - last)) ||
675             !HLPFILE_RtfAddRawString(rd, replace, rlen)) return FALSE;
676         last = p + 1;
677     }
678     return HLPFILE_RtfAddRawString(rd, last, p - last);
679 }
680
681 /******************************************************************
682  *              RtfAddHexBytes
683  *
684  */
685 static BOOL HLPFILE_RtfAddHexBytes(struct RtfData* rd, const void* _ptr, unsigned sz)
686 {
687     char        tmp[512];
688     unsigned    i, step;
689     const BYTE* ptr = _ptr;
690     static const char* _2hex = "0123456789abcdef";
691
692     if (!rd) return TRUE; /* FIXME: TEMP */
693     if (!rd->in_text)
694     {
695         if (!HLPFILE_RtfAddRawString(rd, " ", 1)) return FALSE;
696         rd->in_text = TRUE;
697     }
698     for (; sz; sz -= step)
699     {
700         step = min(256, sz);
701         for (i = 0; i < step; i++)
702         {
703             tmp[2 * i + 0] = _2hex[*ptr >> 4];
704             tmp[2 * i + 1] = _2hex[*ptr++ & 0xF];
705         }
706         if (!HLPFILE_RtfAddRawString(rd, tmp, 2 * step)) return FALSE;
707     }
708     return TRUE;
709 }
710
711 /******************************************************************
712  *              HLPFILE_RtfAddBitmap
713  *
714  */
715 static BOOL HLPFILE_RtfAddBitmap(struct RtfData* rd, BYTE* beg, BYTE type, BYTE pack)
716 {
717     BYTE*               ptr;
718     BYTE*               pict_beg;
719     BITMAPINFO*         bi;
720     unsigned long       off, csz;
721     unsigned            nc = 0;
722     BOOL                ret = FALSE;
723     char                tmp[256];
724
725     bi = HeapAlloc(GetProcessHeap(), 0, sizeof(*bi));
726     if (!bi) return FALSE;
727
728     ptr = beg + 2; /* for type and pack */
729
730     bi->bmiHeader.biSize          = sizeof(bi->bmiHeader);
731     bi->bmiHeader.biXPelsPerMeter = fetch_ulong(&ptr);
732     bi->bmiHeader.biYPelsPerMeter = fetch_ulong(&ptr);
733     bi->bmiHeader.biPlanes        = fetch_ushort(&ptr);
734     bi->bmiHeader.biBitCount      = fetch_ushort(&ptr);
735     bi->bmiHeader.biWidth         = fetch_ulong(&ptr);
736     bi->bmiHeader.biHeight        = fetch_ulong(&ptr);
737     bi->bmiHeader.biClrUsed       = fetch_ulong(&ptr);
738     bi->bmiHeader.biClrImportant  = fetch_ulong(&ptr);
739     bi->bmiHeader.biCompression   = BI_RGB;
740     if (bi->bmiHeader.biBitCount > 32) WINE_FIXME("Unknown bit count %u\n", bi->bmiHeader.biBitCount);
741     if (bi->bmiHeader.biPlanes != 1) WINE_FIXME("Unsupported planes %u\n", bi->bmiHeader.biPlanes);
742     bi->bmiHeader.biSizeImage = (((bi->bmiHeader.biWidth * bi->bmiHeader.biBitCount + 31) & ~31) / 8) * bi->bmiHeader.biHeight;
743     WINE_TRACE("planes=%d bc=%d size=(%d,%d)\n",
744                bi->bmiHeader.biPlanes, bi->bmiHeader.biBitCount,
745                bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
746
747     csz = fetch_ulong(&ptr);
748     fetch_ulong(&ptr); /* hotspot size */
749
750     off = GET_UINT(ptr, 0);     ptr += 4;
751     /* GET_UINT(ptr, 0); hotspot offset */ ptr += 4;
752
753     /* now read palette info */
754     if (type == 0x06)
755     {
756         unsigned i;
757
758         nc = bi->bmiHeader.biClrUsed;
759         /* not quite right, especially for bitfields type of compression */
760         if (!nc && bi->bmiHeader.biBitCount <= 8)
761             nc = 1 << bi->bmiHeader.biBitCount;
762
763         bi = HeapReAlloc(GetProcessHeap(), 0, bi, sizeof(*bi) + nc * sizeof(RGBQUAD));
764         if (!bi) return FALSE;
765         for (i = 0; i < nc; i++)
766         {
767             bi->bmiColors[i].rgbBlue     = ptr[0];
768             bi->bmiColors[i].rgbGreen    = ptr[1];
769             bi->bmiColors[i].rgbRed      = ptr[2];
770             bi->bmiColors[i].rgbReserved = 0;
771             ptr += 4;
772         }
773     }
774     pict_beg = HLPFILE_DecompressGfx(beg + off, csz, bi->bmiHeader.biSizeImage, pack);
775
776
777     if (!HLPFILE_RtfAddControl(rd, "{\\pict")) goto done;
778     if (type == 0x06)
779     {
780         sprintf(tmp, "\\dibitmap0\\picw%d\\pich%d",
781                 bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
782         if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
783         if (!HLPFILE_RtfAddHexBytes(rd, bi, sizeof(*bi) + nc * sizeof(RGBQUAD))) goto done;
784     }
785     else
786     {
787         sprintf(tmp, "\\wbitmap0\\wbmbitspixel%d\\wbmplanes%d\\picw%d\\pich%d",
788                 bi->bmiHeader.biBitCount, bi->bmiHeader.biPlanes,
789                 bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
790         if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
791     }
792     if (!HLPFILE_RtfAddHexBytes(rd, pict_beg, bi->bmiHeader.biSizeImage)) goto done;
793     if (!HLPFILE_RtfAddControl(rd, "}")) goto done;
794
795     ret = TRUE;
796 done:
797     HeapFree(GetProcessHeap(), 0, bi);
798     if (pict_beg != beg + off) HeapFree(GetProcessHeap(), 0, pict_beg);
799
800     return ret;
801 }
802
803 /******************************************************************
804  *              HLPFILE_RtfAddMetaFile
805  *
806  */
807 static BOOL     HLPFILE_RtfAddMetaFile(struct RtfData* rd, BYTE* beg, BYTE pack)
808 {
809     BYTE*               ptr;
810     unsigned long       size, csize;
811     unsigned long       off, hsoff;
812     BYTE*               bits;
813     char                tmp[256];
814     unsigned            mm;
815     BOOL                ret;
816
817     WINE_TRACE("Loading metafile\n");
818
819     ptr = beg + 2; /* for type and pack */
820
821     mm = fetch_ushort(&ptr); /* mapping mode */
822     sprintf(tmp, "{\\pict\\wmetafile%d\\picw%d\\pich%d",
823             mm, GET_USHORT(ptr, 0), GET_USHORT(ptr, 2));
824     if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
825     ptr += 4;
826
827     size = fetch_ulong(&ptr); /* decompressed size */
828     csize = fetch_ulong(&ptr); /* compressed size */
829     fetch_ulong(&ptr); /* hotspot size */
830     off = GET_UINT(ptr, 0);
831     hsoff = GET_UINT(ptr, 4);
832     ptr += 8;
833
834     WINE_TRACE("sz=%lu csz=%lu offs=%lu/%u,%lu\n",
835                size, csize, off, ptr - beg, hsoff);
836
837     bits = HLPFILE_DecompressGfx(beg + off, csize, size, pack);
838     if (!bits) return FALSE;
839
840     ret = HLPFILE_RtfAddHexBytes(rd, bits, size) &&
841         HLPFILE_RtfAddControl(rd, "}");
842
843     if (bits != beg + off) HeapFree(GetProcessHeap(), 0, bits);
844
845     return ret;
846 }
847
848 /******************************************************************
849  *              HLPFILE_RtfAddGfxByAddr
850  *
851  */
852 static  BOOL    HLPFILE_RtfAddGfxByAddr(struct RtfData* rd, HLPFILE *hlpfile,
853                                         BYTE* ref, unsigned long size)
854 {
855     unsigned    i, numpict;
856
857     numpict = GET_USHORT(ref, 2);
858     WINE_TRACE("Got picture magic=%04x #=%d\n", GET_USHORT(ref, 0), numpict);
859
860     for (i = 0; i < numpict; i++)
861     {
862         BYTE*   beg;
863         BYTE*   ptr;
864         BYTE    type, pack;
865
866         WINE_TRACE("Offset[%d] = %x\n", i, GET_UINT(ref, (1 + i) * 4));
867         beg = ptr = ref + GET_UINT(ref, (1 + i) * 4);
868
869         type = *ptr++;
870         pack = *ptr++;
871
872         switch (type)
873         {
874         case 5: /* device dependent bmp */
875         case 6: /* device independent bmp */
876             HLPFILE_RtfAddBitmap(rd, beg, type, pack);
877             break;
878         case 8:
879             HLPFILE_RtfAddMetaFile(rd, beg, pack);
880             break;
881         default: WINE_FIXME("Unknown type %u\n", type); return FALSE;
882         }
883
884         /* FIXME: hotspots */
885
886         /* FIXME: implement support for multiple picture format */
887         if (numpict != 1) WINE_FIXME("Supporting only one bitmap format per logical bitmap (for now). Using first format\n");
888         break;
889     }
890     return TRUE;
891 }
892
893 /******************************************************************
894  *              HLPFILE_RtfAddGfxByIndex
895  *
896  *
897  */
898 static  BOOL    HLPFILE_RtfAddGfxByIndex(struct RtfData* rd, HLPFILE *hlpfile,
899                                          unsigned index)
900 {
901     char        tmp[16];
902     BYTE        *ref, *end;
903
904     WINE_TRACE("Loading picture #%d\n", index);
905
906     sprintf(tmp, "|bm%u", index);
907
908     if (!HLPFILE_FindSubFile(hlpfile, tmp, &ref, &end)) {WINE_WARN("no sub file\n"); return FALSE;}
909
910     ref += 9;
911     return HLPFILE_RtfAddGfxByAddr(rd, hlpfile, ref, end - ref);
912 }
913
914 /******************************************************************
915  *              HLPFILE_LoadBitmap
916  *
917  *
918  */
919 static BOOL HLPFILE_LoadBitmap(BYTE* beg, BYTE type, BYTE pack, 
920                                HLPFILE_PARAGRAPH* paragraph)
921 {
922     BYTE*               ptr;
923     BYTE*               pict_beg;
924     BITMAPINFO*         bi;
925     unsigned long       off, csz;
926     HDC                 hdc;
927
928     bi = HeapAlloc(GetProcessHeap(), 0, sizeof(*bi));
929     if (!bi) return FALSE;
930
931     ptr = beg + 2; /* for type and pack */
932
933     bi->bmiHeader.biSize          = sizeof(bi->bmiHeader);
934     bi->bmiHeader.biXPelsPerMeter = fetch_ulong(&ptr);
935     bi->bmiHeader.biYPelsPerMeter = fetch_ulong(&ptr);
936     bi->bmiHeader.biPlanes        = fetch_ushort(&ptr);
937     bi->bmiHeader.biBitCount      = fetch_ushort(&ptr);
938     bi->bmiHeader.biWidth         = fetch_ulong(&ptr);
939     bi->bmiHeader.biHeight        = fetch_ulong(&ptr);
940     bi->bmiHeader.biClrUsed       = fetch_ulong(&ptr);
941     bi->bmiHeader.biClrImportant  = fetch_ulong(&ptr);
942     bi->bmiHeader.biCompression   = BI_RGB;
943     if (bi->bmiHeader.biBitCount > 32) WINE_FIXME("Unknown bit count %u\n", bi->bmiHeader.biBitCount);
944     if (bi->bmiHeader.biPlanes != 1) WINE_FIXME("Unsupported planes %u\n", bi->bmiHeader.biPlanes);
945     bi->bmiHeader.biSizeImage = (((bi->bmiHeader.biWidth * bi->bmiHeader.biBitCount + 31) & ~31) / 8) * bi->bmiHeader.biHeight;
946     WINE_TRACE("planes=%d bc=%d size=(%d,%d)\n",
947                bi->bmiHeader.biPlanes, bi->bmiHeader.biBitCount, 
948                bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
949
950     csz = fetch_ulong(&ptr);
951     fetch_ulong(&ptr); /* hotspot size */
952
953     off = GET_UINT(ptr, 0);     ptr += 4;
954     /* GET_UINT(ptr, 0); hotspot offset */ ptr += 4;
955     
956     /* now read palette info */
957     if (type == 0x06)
958     {
959         unsigned nc = bi->bmiHeader.biClrUsed;
960         unsigned i;
961         
962         /* not quite right, especially for bitfields type of compression */
963         if (!nc && bi->bmiHeader.biBitCount <= 8)
964             nc = 1 << bi->bmiHeader.biBitCount;
965         
966         bi = HeapReAlloc(GetProcessHeap(), 0, bi, sizeof(*bi) + nc * sizeof(RGBQUAD));
967         if (!bi) return FALSE;
968         for (i = 0; i < nc; i++)
969         {
970             bi->bmiColors[i].rgbBlue     = ptr[0];
971             bi->bmiColors[i].rgbGreen    = ptr[1];
972             bi->bmiColors[i].rgbRed      = ptr[2];
973             bi->bmiColors[i].rgbReserved = 0;
974             ptr += 4;
975         }
976     }
977     pict_beg = HLPFILE_DecompressGfx(beg + off, csz, bi->bmiHeader.biSizeImage, pack);
978     
979     paragraph->u.gfx.u.bmp.hBitmap = CreateDIBitmap(hdc = GetDC(0), &bi->bmiHeader, 
980                                                     CBM_INIT, pict_beg, 
981                                                     bi, DIB_RGB_COLORS);
982     ReleaseDC(0, hdc);      
983     if (!paragraph->u.gfx.u.bmp.hBitmap)
984         WINE_ERR("Couldn't create bitmap\n");
985     
986     HeapFree(GetProcessHeap(), 0, bi);
987     if (pict_beg != beg + off) HeapFree(GetProcessHeap(), 0, pict_beg);
988
989     return TRUE;
990 }
991
992 /******************************************************************
993  *              HLPFILE_LoadMetaFile
994  *
995  *
996  */
997 static BOOL     HLPFILE_LoadMetaFile(BYTE* beg, BYTE pack, HLPFILE_PARAGRAPH* paragraph)
998 {
999     BYTE*               ptr;
1000     unsigned long       size, csize;
1001     unsigned long       off, hsoff;
1002     BYTE*               bits;
1003     LPMETAFILEPICT      lpmfp;
1004
1005     WINE_TRACE("Loading metafile\n");
1006
1007     ptr = beg + 2; /* for type and pack */
1008
1009     lpmfp = &paragraph->u.gfx.u.mfp;
1010     lpmfp->mm = fetch_ushort(&ptr); /* mapping mode */
1011
1012     lpmfp->xExt = GET_USHORT(ptr, 0);
1013     lpmfp->yExt = GET_USHORT(ptr, 2);
1014     ptr += 4;
1015
1016     size = fetch_ulong(&ptr); /* decompressed size */
1017     csize = fetch_ulong(&ptr); /* compressed size */
1018     fetch_ulong(&ptr); /* hotspot size */
1019     off = GET_UINT(ptr, 0);
1020     hsoff = GET_UINT(ptr, 4);
1021     ptr += 8;
1022
1023     WINE_TRACE("sz=%lu csz=%lu (%d,%d) offs=%lu/%lu,%lu\n",
1024                size, csize, lpmfp->xExt, lpmfp->yExt, off, (SIZE_T)(ptr - beg), hsoff);
1025
1026     bits = HLPFILE_DecompressGfx(beg + off, csize, size, pack);
1027     if (!bits) return FALSE;
1028
1029     paragraph->cookie = para_metafile;
1030
1031     lpmfp->hMF = SetMetaFileBitsEx(size, bits);
1032
1033     if (!lpmfp->hMF)
1034         WINE_FIXME("Couldn't load metafile\n");
1035
1036     if (bits != beg + off) HeapFree(GetProcessHeap(), 0, bits);
1037
1038     return TRUE;
1039 }
1040
1041 /******************************************************************
1042  *              HLPFILE_LoadGfxByAddr
1043  *
1044  *
1045  */
1046 static  BOOL    HLPFILE_LoadGfxByAddr(HLPFILE *hlpfile, BYTE* ref,
1047                                       unsigned long size, 
1048                                       HLPFILE_PARAGRAPH* paragraph)
1049 {
1050     unsigned    i, numpict;
1051
1052     numpict = GET_USHORT(ref, 2);
1053     WINE_TRACE("Got picture magic=%04x #=%d\n", 
1054                GET_USHORT(ref, 0), numpict);
1055
1056     for (i = 0; i < numpict; i++)
1057     {
1058         BYTE*   beg;
1059         BYTE*   ptr;
1060         BYTE    type, pack;
1061
1062         WINE_TRACE("Offset[%d] = %x\n", i, GET_UINT(ref, (1 + i) * 4));
1063         beg = ptr = ref + GET_UINT(ref, (1 + i) * 4);
1064
1065         type = *ptr++;
1066         pack = *ptr++;
1067         
1068         switch (type)
1069         {
1070         case 5: /* device dependent bmp */
1071         case 6: /* device independent bmp */
1072             HLPFILE_LoadBitmap(beg, type, pack, paragraph);
1073             break;
1074         case 8: 
1075             HLPFILE_LoadMetaFile(beg, pack, paragraph);
1076             break;
1077         default: WINE_FIXME("Unknown type %u\n", type); return FALSE;
1078         }
1079
1080         /* FIXME: hotspots */
1081
1082         /* FIXME: implement support for multiple picture format */
1083         if (numpict != 1) WINE_FIXME("Supporting only one bitmap format per logical bitmap (for now). Using first format\n");
1084         break;
1085     }
1086     return TRUE;
1087 }
1088
1089 /******************************************************************
1090  *              HLPFILE_LoadGfxByIndex
1091  *
1092  *
1093  */
1094 static  BOOL    HLPFILE_LoadGfxByIndex(HLPFILE *hlpfile, unsigned index, 
1095                                        HLPFILE_PARAGRAPH* paragraph)
1096 {
1097     char        tmp[16];
1098     BYTE        *ref, *end;
1099     BOOL        ret;
1100
1101     WINE_TRACE("Loading picture #%d\n", index);
1102
1103     if (index < hlpfile->numBmps && hlpfile->bmps[index] != NULL)
1104     {
1105         paragraph->u.gfx.u.bmp.hBitmap = hlpfile->bmps[index];
1106         return TRUE;
1107     }
1108
1109     sprintf(tmp, "|bm%u", index);
1110
1111     if (!HLPFILE_FindSubFile(hlpfile, tmp, &ref, &end)) {WINE_WARN("no sub file\n"); return FALSE;}
1112
1113     ref += 9;
1114
1115     ret = HLPFILE_LoadGfxByAddr(hlpfile, ref, end - ref, paragraph);
1116
1117     /* cache bitmap */
1118     if (ret && paragraph->cookie == para_bitmap)
1119     {
1120         if (index >= hlpfile->numBmps)
1121         {
1122             hlpfile->numBmps = index + 1;
1123             if (hlpfile->bmps)
1124                 hlpfile->bmps = HeapReAlloc(GetProcessHeap(), 0, hlpfile->bmps, 
1125                                         hlpfile->numBmps * sizeof(hlpfile->bmps[0]));
1126             else
1127                 hlpfile->bmps = HeapAlloc(GetProcessHeap(), 0, 
1128                                         hlpfile->numBmps * sizeof(hlpfile->bmps[0]));
1129
1130         }
1131         hlpfile->bmps[index] = paragraph->u.gfx.u.bmp.hBitmap;
1132     }
1133     return ret;
1134 }
1135
1136 /******************************************************************
1137  *              HLPFILE_AllocLink
1138  *
1139  *
1140  */
1141 static HLPFILE_LINK*       HLPFILE_AllocLink(struct RtfData* rd, int cookie,
1142                                              const char* str, unsigned len, LONG hash,
1143                                              unsigned clrChange, unsigned wnd)
1144 {
1145     HLPFILE_LINK*  link;
1146     char*          link_str;
1147
1148     /* FIXME: should build a string table for the attributes.link.lpszPath
1149      * they are reallocated for each link
1150      */
1151     if (len == -1) len = strlen(str);
1152     link = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_LINK) + len + 1);
1153     if (!link) return NULL;
1154
1155     link->cookie     = cookie;
1156     link->string     = link_str = (char*)(link + 1);
1157     memcpy(link_str, str, len);
1158     link_str[len] = '\0';
1159     link->hash       = hash;
1160     link->bClrChange = clrChange ? 1 : 0;
1161     link->window     = wnd;
1162     link->wRefCount  = 1;
1163     if (rd) {
1164     link->next       = rd->first_link;
1165     rd->first_link   = link;
1166     link->cpMin      = rd->char_pos;
1167     link->cpMax      = 0;
1168     rd->force_color  = clrChange;
1169     link->wRefCount++;
1170     if (rd->current_link) WINE_FIXME("Pending link\n");
1171     rd->current_link = link;
1172     }
1173
1174     WINE_TRACE("Link[%d] to %s@%08x:%d\n",
1175                link->cookie, link->string, link->hash, link->window);
1176     return link;
1177 }
1178
1179 unsigned HLPFILE_HalfPointsToTwips(unsigned pts)
1180 {
1181     static unsigned logPxY;
1182     if (!logPxY)
1183     {
1184         HDC hdc = GetDC(NULL);
1185         logPxY = GetDeviceCaps(hdc, LOGPIXELSY);
1186         ReleaseDC(NULL, hdc);
1187     }
1188     return MulDiv(pts, 72 * 10, logPxY);
1189 }
1190
1191 /***********************************************************************
1192  *
1193  *           HLPFILE_BrowseParagraph
1194  */
1195 static BOOL HLPFILE_BrowseParagraph(HLPFILE_PAGE* page, struct RtfData* rd, BYTE *buf, BYTE* end)
1196 {
1197     HLPFILE_PARAGRAPH *paragraph, **paragraphptr;
1198     UINT               textsize;
1199     BYTE              *format, *format_end;
1200     char              *text, *text_base, *text_end;
1201     long               size, blocksize, datalen;
1202     unsigned short     bits;
1203     unsigned           nc, ncol = 1;
1204     BOOL               in_table = FALSE;
1205     char               tmp[256];
1206     BOOL               ret = FALSE;
1207
1208     for (paragraphptr = &page->first_paragraph; *paragraphptr;
1209          paragraphptr = &(*paragraphptr)->next) /* Nothing */;
1210
1211     if (buf + 0x19 > end) {WINE_WARN("header too small\n"); return FALSE;};
1212
1213     blocksize = GET_UINT(buf, 0);
1214     size = GET_UINT(buf, 0x4);
1215     datalen = GET_UINT(buf, 0x10);
1216     text = text_base = HeapAlloc(GetProcessHeap(), 0, size);
1217     if (!text) return FALSE;
1218     if (size > blocksize - datalen)
1219     {
1220         /* need to decompress */
1221         if (page->file->hasPhrases)
1222             HLPFILE_Uncompress2(page->file, buf + datalen, end, (BYTE*)text, (BYTE*)text + size);
1223         else if (page->file->hasPhrases40)
1224             HLPFILE_Uncompress3(page->file, text, text + size, buf + datalen, end);
1225         else
1226         {
1227             WINE_FIXME("Text size is too long, splitting\n");
1228             size = blocksize - datalen;
1229             memcpy(text, buf + datalen, size);
1230         }
1231     }
1232     else
1233         memcpy(text, buf + datalen, size);
1234
1235     text_end = text + size;
1236
1237     format = buf + 0x15;
1238     format_end = buf + GET_UINT(buf, 0x10);
1239
1240     if (buf[0x14] == 0x20 || buf[0x14] == 0x23)
1241     {
1242         fetch_long(&format);
1243         fetch_ushort(&format);
1244     }
1245
1246     if (buf[0x14] == 0x23)
1247     {
1248         char    type;
1249
1250         in_table = TRUE;
1251         ncol = *format++;
1252
1253         WINE_TRACE("#cols %u\n", ncol);
1254         type = *format++;
1255         if (type == 0 || type == 2)
1256             format += 2;
1257         format += ncol * 4;
1258     }
1259
1260     for (nc = 0; nc < ncol; /**/)
1261     {
1262         WINE_TRACE("looking for format at offset %lu in column %d\n", (SIZE_T)(format - (buf + 0x15)), nc);
1263         if (in_table)
1264         {
1265             nc = GET_SHORT(format, 0);
1266             if (nc == -1) break;
1267             format += 5;
1268         }
1269         else nc++;
1270         if (buf[0x14] == 0x01)
1271             format += 6;
1272         else
1273             format += 4;
1274         bits = GET_USHORT(format, 0); format += 2;
1275         if (bits & 0x0001) fetch_long(&format);
1276         if (bits & 0x0002)
1277         {
1278             sprintf(tmp, "\\sb%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1279             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1280         }
1281         if (bits & 0x0004)
1282         {
1283             sprintf(tmp, "\\sa%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1284             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1285         }
1286         if (bits & 0x0008)
1287         {
1288             sprintf(tmp, "\\sl%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1289             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1290         }
1291         if (bits & 0x0010)
1292         {
1293             sprintf(tmp, "\\li%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1294             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1295         }
1296         if (bits & 0x0020)
1297         {
1298             sprintf(tmp, "\\ri%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1299             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1300         }
1301         if (bits & 0x0040)
1302         {
1303             sprintf(tmp, "\\fi%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1304             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1305         }
1306         if (bits & 0x0100)
1307         {
1308             BYTE        brdr = *format++;
1309             short       w;
1310
1311             if (brdr & 0x01 && !HLPFILE_RtfAddControl(rd, "\\box")) goto done;
1312             if (brdr & 0x02 && !HLPFILE_RtfAddControl(rd, "\\brdrt")) goto done;
1313             if (brdr & 0x04 && !HLPFILE_RtfAddControl(rd, "\\brdrl")) goto done;
1314             if (brdr & 0x08 && !HLPFILE_RtfAddControl(rd, "\\brdrb")) goto done;
1315             if (brdr & 0x10 && !HLPFILE_RtfAddControl(rd, "\\brdrr")) goto done;
1316             if (brdr & 0x20 && !HLPFILE_RtfAddControl(rd, "\\brdrth")) goto done;
1317             if (!(brdr & 0x20) && !HLPFILE_RtfAddControl(rd, "\\brdrs")) goto done;
1318             if (brdr & 0x40 && !HLPFILE_RtfAddControl(rd, "\\brdrdb")) goto done;
1319             /* 0x80: unknown */
1320
1321             w = GET_SHORT(format, 0); format += 2;
1322             if (w)
1323             {
1324                 sprintf(tmp, "\\brdrw%d", HLPFILE_HalfPointsToTwips(w));
1325                 if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1326             }
1327         }
1328         if (bits & 0x0200)
1329         {
1330             int                 i, ntab = fetch_short(&format);
1331             unsigned            tab, ts;
1332             const char*         kind;
1333
1334             for (i = 0; i < ntab; i++)
1335             {
1336                 tab = fetch_ushort(&format);
1337                 ts = (tab & 0x4000) ? fetch_ushort(&format) : 0 /* left */;
1338                 switch (ts)
1339                 {
1340                 default: WINE_FIXME("Unknown tab style %x\n", ts);
1341                 /* fall through */
1342                 case 0: kind = ""; break;
1343                 case 1: kind = "\\tqr"; break;
1344                 case 2: kind = "\\tqc"; break;
1345                 }
1346                 /* FIXME: do kind */
1347                 sprintf(tmp, "%s\\tx%d",
1348                         kind, HLPFILE_HalfPointsToTwips(tab & 0x3FFF));
1349                 if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1350             }
1351         }
1352         switch (bits & 0xc00)
1353         {
1354         default: WINE_FIXME("Unsupported alignment 0xC00\n"); break;
1355         case 0: if (!HLPFILE_RtfAddControl(rd, "\\ql")) goto done; break;
1356         case 0x400: if (!HLPFILE_RtfAddControl(rd, "\\qr")) goto done; break;
1357         case 0x800: if (!HLPFILE_RtfAddControl(rd, "\\qc")) goto done; break;
1358         }
1359
1360         /* 0x1000 doesn't need space */
1361         if ((bits & 0x1000) && !HLPFILE_RtfAddControl(rd, "\\keep")) goto done;
1362         if ((bits & 0xE080) != 0) 
1363             WINE_FIXME("Unsupported bits %04x, potential trouble ahead\n", bits);
1364
1365         while (text < text_end && format < format_end)
1366         {
1367             WINE_TRACE("Got text: %s (%p/%p - %p/%p)\n", wine_dbgstr_a(text), text, text_end, format, format_end);
1368             textsize = strlen(text);
1369             if (textsize)
1370             {
1371                 paragraph = HeapAlloc(GetProcessHeap(), 0,
1372                                       sizeof(HLPFILE_PARAGRAPH) + textsize + 1);
1373                 if (!paragraph) return FALSE;
1374                 *paragraphptr = paragraph;
1375                 paragraphptr = &paragraph->next;
1376
1377                 paragraph->next            = NULL;
1378                 if (!rd)
1379                 {
1380                 paragraph->link            = attributes.link;
1381                 if (paragraph->link) paragraph->link->wRefCount++;
1382                 }
1383                 else paragraph->link       = NULL;
1384                 paragraph->cookie          = para_normal_text;
1385                 paragraph->u.text.wFont    = attributes.wFont;
1386                 paragraph->u.text.wVSpace  = attributes.wVSpace;
1387                 paragraph->u.text.wHSpace  = attributes.wHSpace;
1388                 paragraph->u.text.wIndent  = attributes.wIndent;
1389                 paragraph->u.text.lpszText = (char*)paragraph + sizeof(HLPFILE_PARAGRAPH);
1390                 strcpy(paragraph->u.text.lpszText, text);
1391
1392                 attributes.wVSpace = 0;
1393                 attributes.wHSpace = 0;
1394                 if (rd) /* FIXME: TEMP */ {
1395                 if (rd->force_color)
1396                 {
1397                     if ((rd->current_link->cookie == hlp_link_popup) ?
1398                         !HLPFILE_RtfAddControl(rd, "{\\uld\\cf1") :
1399                         !HLPFILE_RtfAddControl(rd, "{\\ul\\cf1")) goto done;
1400                 }
1401                 if (!HLPFILE_RtfAddText(rd, text)) goto done;
1402                 if (rd->force_color && !HLPFILE_RtfAddControl(rd, "}")) goto done;
1403                 rd->char_pos += textsize;
1404                 }
1405             }
1406             /* else: null text, keep on storing attributes */
1407             text += textsize + 1;
1408
1409             if (*format == 0xff)
1410             {
1411                 format++;
1412                 break;
1413             }
1414
1415             WINE_TRACE("format=%02x\n", *format);
1416             switch (*format)
1417             {
1418             case 0x20:
1419                 WINE_FIXME("NIY20\n");
1420                 format += 5;
1421                 break;
1422
1423             case 0x21:
1424                 WINE_FIXME("NIY21\n");
1425                 format += 3;
1426                 break;
1427
1428             case 0x80:
1429                 {
1430                     unsigned    font = GET_USHORT(format, 1);
1431                     unsigned    fs;
1432                     attributes.wFont = font;
1433                     WINE_TRACE("Changing font to %d\n", attributes.wFont);
1434                     format += 3;
1435                     fs = (4 * page->file->fonts[font].LogFont.lfHeight - 3) / 5;
1436                     /* FIXME: missing at least colors, also bold attribute looses information */
1437
1438                     sprintf(tmp, "\\f%d\\cf%d\\fs%d%s%s%s%s",
1439                             font, font + 2, fs,
1440                             page->file->fonts[font].LogFont.lfWeight > 400 ? "\\b" : "\\b0",
1441                             page->file->fonts[font].LogFont.lfItalic ? "\\i" : "\\i0",
1442                             page->file->fonts[font].LogFont.lfUnderline ? "\\ul" : "\\ul0",
1443                             page->file->fonts[font].LogFont.lfStrikeOut ? "\\strike" : "\\strike0");
1444                     if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1445                 }
1446                break;
1447
1448             case 0x81:
1449                 if (!HLPFILE_RtfAddControl(rd, "\\line")) goto done;
1450                 attributes.wVSpace++;
1451                 format += 1;
1452                 if (rd) /* FIXME: TEMP */ rd->char_pos++;
1453                 break;
1454
1455             case 0x82:
1456                 if (!HLPFILE_RtfAddControl(rd, "\\par\\pard")) goto done;
1457                 attributes.wVSpace++;
1458                 attributes.wIndent = 0;
1459                 format += 1;
1460                 if (rd)  /* FIXME: TEMP */ rd->char_pos++;
1461                 break;
1462
1463             case 0x83:
1464                 if (!HLPFILE_RtfAddControl(rd, "\\tab")) goto done;
1465                 attributes.wIndent++;
1466                 format += 1;
1467                 if (rd)  /* FIXME: TEMP */ rd->char_pos++;
1468                 break;
1469
1470 #if 0
1471             case 0x84:
1472                 format += 3;
1473                 break;
1474 #endif
1475
1476             case 0x86:
1477             case 0x87:
1478             case 0x88:
1479                 {
1480                     BYTE    pos = (*format - 0x86);
1481                     BYTE    type = format[1];
1482                     long    size;
1483
1484                     format += 2;
1485                     size = fetch_long(&format);
1486
1487                     paragraph = HeapAlloc(GetProcessHeap(), 0,
1488                                           sizeof(HLPFILE_PARAGRAPH) + textsize);
1489                     if (!paragraph) return FALSE;
1490                     *paragraphptr = paragraph;
1491                     paragraphptr = &paragraph->next;
1492
1493                     paragraph->next        = NULL;
1494                     if (!rd){
1495                     paragraph->link        = attributes.link;
1496                     if (paragraph->link) paragraph->link->wRefCount++;
1497                     }
1498                     else paragraph->link   = NULL;
1499                     paragraph->cookie      = para_bitmap;
1500                     paragraph->u.gfx.pos   = pos;
1501                     switch (type)
1502                     {
1503                     case 0x22:
1504                         fetch_ushort(&format); /* hot spot */
1505                         /* fall thru */
1506                     case 0x03:
1507                         switch (GET_SHORT(format, 0))
1508                         {
1509                         case 0:
1510                             HLPFILE_LoadGfxByIndex(page->file, GET_SHORT(format, 2),
1511                                                    paragraph);
1512                             if (rd) { /* FIXME: TEMP */
1513                             HLPFILE_RtfAddGfxByIndex(rd, page->file, GET_SHORT(format, 2));
1514                             rd->char_pos++;
1515                             }
1516                             break;
1517                         case 1:
1518                             WINE_FIXME("does it work ??? %x<%lu>#%u\n", 
1519                                        GET_SHORT(format, 0), 
1520                                        size, GET_SHORT(format, 2));
1521                             HLPFILE_LoadGfxByAddr(page->file, format + 2, size - 4,
1522                                                   paragraph);
1523                             if (rd) { /* FIXME: TEMP */
1524                             HLPFILE_RtfAddGfxByAddr(rd, page->file, format + 2, size - 4);
1525                             rd->char_pos++;
1526                             }
1527                            break;
1528                         default:
1529                             WINE_FIXME("??? %u\n", GET_SHORT(format, 0));
1530                             break;
1531                         }
1532                         break;
1533                     case 0x05:
1534                         WINE_FIXME("Got an embedded element %s\n", format + 6);
1535                         break;
1536                     default:
1537                         WINE_FIXME("Got a type %d picture\n", type);
1538                         break;
1539                     }
1540                     if (attributes.wVSpace) paragraph->u.gfx.pos |= 0x8000;
1541
1542                     format += size;
1543                 }
1544                 break;
1545
1546             case 0x89:
1547                 HLPFILE_FreeLink(attributes.link);
1548                 attributes.link = NULL;
1549                 format += 1;
1550                 if (rd) {
1551                 if (!rd->current_link)
1552                     WINE_FIXME("No existing link\n");
1553                 else
1554                 rd->current_link->cpMax = rd->char_pos;
1555                 rd->current_link = NULL;
1556                 rd->force_color = FALSE;
1557                 }
1558                 break;
1559
1560             case 0x8B:
1561                 if (!HLPFILE_RtfAddControl(rd, "\\~")) goto done;
1562                 format += 1;
1563                 if (rd) /* FIXME: TEMP */ rd->char_pos++;
1564                 break;
1565
1566             case 0x8C:
1567                 if (!HLPFILE_RtfAddControl(rd, "\\_")) goto done;
1568                 /* FIXME: it could be that hypen is also in input stream !! */
1569                 format += 1;
1570                 if (rd) /* FIXME: TEMP */ rd->char_pos++;
1571                 break;
1572
1573 #if 0
1574             case 0xA9:
1575                 format += 2;
1576                 break;
1577 #endif
1578
1579             case 0xC8:
1580             case 0xCC:
1581                 WINE_TRACE("macro => %s\n", format + 3);
1582                 HLPFILE_FreeLink(attributes.link);
1583                 attributes.link = HLPFILE_AllocLink(rd, hlp_link_macro, (const char*)format + 3,
1584                                                     GET_USHORT(format, 1), 0, !(*format & 4), -1);
1585                 format += 3 + GET_USHORT(format, 1);
1586                 break;
1587
1588             case 0xE0:
1589             case 0xE1:
1590                 WINE_WARN("jump topic 1 => %u\n", GET_UINT(format, 1));
1591                 HLPFILE_FreeLink(attributes.link);
1592                 attributes.link = HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1593                                                     page->file->lpszPath, -1,
1594                                                     GET_UINT(format, 1)-16,
1595                                                     1, -1);
1596
1597
1598                 format += 5;
1599                 break;
1600
1601             case 0xE2:
1602             case 0xE3:
1603             case 0xE6:
1604             case 0xE7:
1605                 attributes.link = HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1606                                                     page->file->lpszPath, -1,
1607                                                     GET_UINT(format, 1),
1608                                                     !(*format & 4), -1);
1609                 format += 5;
1610                 break;
1611
1612             case 0xEA:
1613             case 0xEB:
1614             case 0xEE:
1615             case 0xEF:
1616                 {
1617                     char*       ptr = (char*) format + 8;
1618                     BYTE        type = format[3];
1619                     int         wnd = -1;
1620
1621                     switch (type)
1622                     {
1623                     case 1:
1624                         wnd = *ptr;
1625                         /* fall through */
1626                     case 0:
1627                         ptr = page->file->lpszPath;
1628                         break;
1629                     case 6:
1630                         for (wnd = page->file->numWindows - 1; wnd >= 0; wnd--)
1631                         {
1632                             if (!strcmp(ptr, page->file->windows[wnd].name)) break;
1633                         }
1634                         if (wnd == -1)
1635                             WINE_WARN("Couldn't find window info for %s\n", ptr);
1636                         ptr += strlen(ptr) + 1;
1637                         /* fall through */
1638                     case 4:
1639                         break;
1640                     default:
1641                         WINE_WARN("Unknown link type %d\n", type);
1642                         break;
1643                     }
1644                     HLPFILE_FreeLink(attributes.link);
1645                     attributes.link = HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1646                                                         ptr, -1, GET_UINT(format, 4),
1647                                                         !(*format & 4), wnd);
1648                 }
1649                 format += 3 + GET_USHORT(format, 1);
1650                 break;
1651
1652             default:
1653                 WINE_WARN("format %02x\n", *format);
1654                 format++;
1655             }
1656         }
1657     }
1658     ret = TRUE;
1659 done:
1660     HeapFree(GetProcessHeap(), 0, text_base);
1661     return ret;
1662 }
1663
1664 /******************************************************************
1665  *              HLPFILE_BrowsePage
1666  *
1667  */
1668 BOOL    HLPFILE_BrowsePage(HLPFILE_PAGE* page, struct RtfData* rd)
1669 {
1670     HLPFILE     *hlpfile = page->file;
1671     BYTE        *buf, *end;
1672     DWORD       ref = page->reference;
1673     unsigned    index, old_index = -1, offset, count = 0, cpg;
1674     char        tmp[1024];
1675     const char* ck = NULL;
1676
1677     if (rd) { /* FIXME: TEMP */
1678     rd->in_text = TRUE;
1679     rd->data = rd->ptr = HeapAlloc(GetProcessHeap(), 0, rd->allocated = 32768);
1680     rd->char_pos = 0;
1681     rd->first_link = rd->current_link = NULL;
1682     rd->force_color = FALSE;
1683     }
1684
1685     switch (hlpfile->charset)
1686     {
1687     case DEFAULT_CHARSET:
1688     case ANSI_CHARSET:          cpg = 1252; break;
1689     case SHIFTJIS_CHARSET:      cpg = 932; break;
1690     case HANGEUL_CHARSET:       cpg = 949; break;
1691     case GB2312_CHARSET:        cpg = 936; break;
1692     case CHINESEBIG5_CHARSET:   cpg = 950; break;
1693     case GREEK_CHARSET:         cpg = 1253; break;
1694     case TURKISH_CHARSET:       cpg = 1254; break;
1695     case HEBREW_CHARSET:        cpg = 1255; break;
1696     case ARABIC_CHARSET:        cpg = 1256; break;
1697     case BALTIC_CHARSET:        cpg = 1257; break;
1698     case VIETNAMESE_CHARSET:    cpg = 1258; break;
1699     case RUSSIAN_CHARSET:       cpg = 1251; break;
1700     case EE_CHARSET:            cpg = 1250; break;
1701     case THAI_CHARSET:          cpg = 874; break;
1702     case JOHAB_CHARSET:         cpg = 1361; break;
1703     case MAC_CHARSET:           ck = "mac"; break;
1704     default:
1705         WINE_FIXME("Unsupported charset %u\n", hlpfile->charset);
1706         cpg = 1252;
1707     }
1708     if (ck)
1709     {
1710         sprintf(tmp, "{\\rtf1\\%s\\deff0", ck);
1711         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1712     }
1713     else
1714     {
1715         sprintf(tmp, "{\\rtf1\\ansi\\ansicpg%d\\deff0", cpg);
1716         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1717     }
1718
1719     /* generate font table */
1720     if (!HLPFILE_RtfAddControl(rd, "{\\fonttbl")) return FALSE;
1721     for (index = 0; index < hlpfile->numFonts; index++)
1722     {
1723         const char* family;
1724         switch (hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0xF0)
1725         {
1726         case FF_MODERN:     family = "modern";  break;
1727         case FF_ROMAN:      family = "roman";   break;
1728         case FF_SWISS:      family = "swiss";   break;
1729         case FF_SCRIPT:     family = "script";  break;
1730         case FF_DECORATIVE: family = "decor";   break;
1731         default:            family = "nil";     break;
1732         }
1733         sprintf(tmp, "{\\f%d\\f%s\\fprq%d\\fcharset%d %s;}",
1734                 index, family,
1735                 hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0x0F,
1736                 hlpfile->fonts[index].LogFont.lfCharSet,
1737                 hlpfile->fonts[index].LogFont.lfFaceName);
1738         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1739     }
1740     if (!HLPFILE_RtfAddControl(rd, "}")) return FALSE;
1741     /* generate color table */
1742     if (!HLPFILE_RtfAddControl(rd, "{\\colortbl ;\\red0\\green128\\blue0;")) return FALSE;
1743     for (index = 0; index < hlpfile->numFonts; index++)
1744     {
1745         const char* family;
1746         switch (hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0xF0)
1747         {
1748         case FF_MODERN:     family = "modern";  break;
1749         case FF_ROMAN:      family = "roman";   break;
1750         case FF_SWISS:      family = "swiss";   break;
1751         case FF_SCRIPT:     family = "script";  break;
1752         case FF_DECORATIVE: family = "decor";   break;
1753         default:            family = "nil";     break;
1754         }
1755         sprintf(tmp, "\\red%d\\green%d\\blue%d;",
1756                 GetRValue(hlpfile->fonts[index].color),
1757                 GetGValue(hlpfile->fonts[index].color),
1758                 GetBValue(hlpfile->fonts[index].color));
1759         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1760     }
1761     if (!HLPFILE_RtfAddControl(rd, "}")) return FALSE;
1762
1763     do
1764     {
1765         if (hlpfile->version <= 16)
1766         {
1767             index  = (ref - 0x0C) / hlpfile->dsize;
1768             offset = (ref - 0x0C) % hlpfile->dsize;
1769         }
1770         else
1771         {
1772             index  = (ref - 0x0C) >> 14;
1773             offset = (ref - 0x0C) & 0x3FFF;
1774         }
1775
1776         if (hlpfile->version <= 16 && index != old_index && old_index != -1)
1777         {
1778             /* we jumped to the next block, adjust pointers */
1779             ref -= 12;
1780             offset -= 12;
1781         }
1782
1783         if (index >= hlpfile->topic_maplen) {WINE_WARN("maplen\n"); break;}
1784         buf = hlpfile->topic_map[index] + offset;
1785         if (buf + 0x15 >= hlpfile->topic_end) {WINE_WARN("extra\n"); break;}
1786         end = min(buf + GET_UINT(buf, 0), hlpfile->topic_end);
1787         if (index != old_index) {old_index = index;}
1788
1789         switch (buf[0x14])
1790         {
1791         case 0x02:
1792             if (count++) goto done;
1793             break;
1794         case 0x01:
1795         case 0x20:
1796         case 0x23:
1797             if (!HLPFILE_BrowseParagraph(page, rd, buf, end)) return FALSE;
1798             break;
1799         default:
1800             WINE_ERR("buf[0x14] = %x\n", buf[0x14]);
1801         }
1802         if (hlpfile->version <= 16)
1803         {
1804             ref += GET_UINT(buf, 0xc);
1805             if (GET_UINT(buf, 0xc) == 0)
1806                 break;
1807         }
1808         else
1809             ref = GET_UINT(buf, 0xc);
1810     } while (ref != 0xffffffff);
1811 done:
1812     if (rd)
1813     page->first_link = rd->first_link;
1814     return HLPFILE_RtfAddControl(rd, "}");
1815 }
1816
1817 /******************************************************************
1818  *              HLPFILE_ReadFont
1819  *
1820  *
1821  */
1822 static BOOL HLPFILE_ReadFont(HLPFILE* hlpfile)
1823 {
1824     BYTE        *ref, *end;
1825     unsigned    i, len, idx;
1826     unsigned    face_num, dscr_num, face_offset, dscr_offset;
1827     BYTE        flag, family;
1828
1829     if (!HLPFILE_FindSubFile(hlpfile, "|FONT", &ref, &end))
1830     {
1831         WINE_WARN("no subfile FONT\n");
1832         hlpfile->numFonts = 0;
1833         hlpfile->fonts = NULL;
1834         return FALSE;
1835     }
1836
1837     ref += 9;
1838
1839     face_num    = GET_USHORT(ref, 0);
1840     dscr_num    = GET_USHORT(ref, 2);
1841     face_offset = GET_USHORT(ref, 4);
1842     dscr_offset = GET_USHORT(ref, 6);
1843
1844     WINE_TRACE("Got NumFacenames=%u@%u NumDesc=%u@%u\n",
1845                face_num, face_offset, dscr_num, dscr_offset);
1846
1847     hlpfile->numFonts = dscr_num;
1848     hlpfile->fonts = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_FONT) * dscr_num);
1849
1850     len = (dscr_offset - face_offset) / face_num;
1851 /* EPP     for (i = face_offset; i < dscr_offset; i += len) */
1852 /* EPP         WINE_FIXME("[%d]: %*s\n", i / len, len, ref + i); */
1853     for (i = 0; i < dscr_num; i++)
1854     {
1855         flag = ref[dscr_offset + i * 11 + 0];
1856         family = ref[dscr_offset + i * 11 + 2];
1857
1858         hlpfile->fonts[i].LogFont.lfHeight = ref[dscr_offset + i * 11 + 1];
1859         hlpfile->fonts[i].LogFont.lfWidth = 0;
1860         hlpfile->fonts[i].LogFont.lfEscapement = 0;
1861         hlpfile->fonts[i].LogFont.lfOrientation = 0;
1862         hlpfile->fonts[i].LogFont.lfWeight = (flag & 1) ? 700 : 400;
1863         hlpfile->fonts[i].LogFont.lfItalic = (flag & 2) ? TRUE : FALSE;
1864         hlpfile->fonts[i].LogFont.lfUnderline = (flag & 4) ? TRUE : FALSE;
1865         hlpfile->fonts[i].LogFont.lfStrikeOut = (flag & 8) ? TRUE : FALSE;
1866         hlpfile->fonts[i].LogFont.lfCharSet = hlpfile->charset;
1867         hlpfile->fonts[i].LogFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
1868         hlpfile->fonts[i].LogFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1869         hlpfile->fonts[i].LogFont.lfQuality = DEFAULT_QUALITY;
1870         hlpfile->fonts[i].LogFont.lfPitchAndFamily = DEFAULT_PITCH;
1871
1872         switch (family)
1873         {
1874         case 0x01: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_MODERN;     break;
1875         case 0x02: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_ROMAN;      break;
1876         case 0x03: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_SWISS;      break;
1877         case 0x04: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_SCRIPT;     break;
1878         case 0x05: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_DECORATIVE; break;
1879         default: WINE_FIXME("Unknown family %u\n", family);
1880         }
1881         idx = GET_USHORT(ref, dscr_offset + i * 11 + 3);
1882
1883         if (idx < face_num)
1884         {
1885             memcpy(hlpfile->fonts[i].LogFont.lfFaceName, ref + face_offset + idx * len, min(len, LF_FACESIZE - 1));
1886             hlpfile->fonts[i].LogFont.lfFaceName[min(len, LF_FACESIZE - 1)] = '\0';
1887         }
1888         else
1889         {
1890             WINE_FIXME("Too high face ref (%u/%u)\n", idx, face_num);
1891             strcpy(hlpfile->fonts[i].LogFont.lfFaceName, "Helv");
1892         }
1893         hlpfile->fonts[i].hFont = 0;
1894         hlpfile->fonts[i].color = RGB(ref[dscr_offset + i * 11 + 5],
1895                                       ref[dscr_offset + i * 11 + 6],
1896                                       ref[dscr_offset + i * 11 + 7]);
1897 #define X(b,s) ((flag & (1 << b)) ? "-"s: "")
1898         WINE_TRACE("Font[%d]: flags=%02x%s%s%s%s%s%s pSize=%u family=%u face=%s[%u] color=%08x\n",
1899                    i, flag,
1900                    X(0, "bold"),
1901                    X(1, "italic"),
1902                    X(2, "underline"),
1903                    X(3, "strikeOut"),
1904                    X(4, "dblUnderline"),
1905                    X(5, "smallCaps"),
1906                    ref[dscr_offset + i * 11 + 1],
1907                    family,
1908                    hlpfile->fonts[i].LogFont.lfFaceName, idx,
1909                    GET_UINT(ref, dscr_offset + i * 11 + 5) & 0x00FFFFFF);
1910     }
1911     return TRUE;
1912 }
1913
1914 /***********************************************************************
1915  *
1916  *           HLPFILE_ReadFileToBuffer
1917  */
1918 static BOOL HLPFILE_ReadFileToBuffer(HLPFILE* hlpfile, HFILE hFile)
1919 {
1920     BYTE  header[16], dummy[1];
1921
1922     if (_hread(hFile, header, 16) != 16) {WINE_WARN("header\n"); return FALSE;};
1923
1924     /* sanity checks */
1925     if (GET_UINT(header, 0) != 0x00035F3F)
1926     {WINE_WARN("wrong header\n"); return FALSE;};
1927
1928     hlpfile->file_buffer_size = GET_UINT(header, 12);
1929     hlpfile->file_buffer = HeapAlloc(GetProcessHeap(), 0, hlpfile->file_buffer_size + 1);
1930     if (!hlpfile->file_buffer) return FALSE;
1931
1932     memcpy(hlpfile->file_buffer, header, 16);
1933     if (_hread(hFile, hlpfile->file_buffer + 16, hlpfile->file_buffer_size - 16) !=hlpfile->file_buffer_size - 16)
1934     {WINE_WARN("filesize1\n"); return FALSE;};
1935
1936     if (_hread(hFile, dummy, 1) != 0) WINE_WARN("filesize2\n");
1937
1938     hlpfile->file_buffer[hlpfile->file_buffer_size] = '\0'; /* FIXME: was '0', sounds backwards to me */
1939
1940     return TRUE;
1941 }
1942
1943 /**************************************************************************
1944  * comp_FindSubFile
1945  *
1946  * HLPFILE_BPTreeCompare function for HLPFILE directory.
1947  *
1948  */
1949 static int comp_FindSubFile(void *p, const void *key,
1950                             int leaf, void** next)
1951 {
1952     *next = (char *)p+strlen(p)+(leaf?5:3);
1953     WINE_TRACE("Comparing '%s' with '%s'\n", (char *)p, (char *)key);
1954     return strcmp(p, key);
1955 }
1956
1957 /***********************************************************************
1958  *
1959  *           HLPFILE_FindSubFile
1960  */
1961 static BOOL HLPFILE_FindSubFile(HLPFILE* hlpfile, LPCSTR name, BYTE **subbuf, BYTE **subend)
1962 {
1963     BYTE *ptr;
1964
1965     WINE_TRACE("looking for file '%s'\n", name);
1966     ptr = HLPFILE_BPTreeSearch(hlpfile->file_buffer + GET_UINT(hlpfile->file_buffer, 4),
1967                                name, comp_FindSubFile);
1968     if (!ptr) return FALSE;
1969     *subbuf = hlpfile->file_buffer + GET_UINT(ptr, strlen(name)+1);
1970     if (*subbuf >= hlpfile->file_buffer + hlpfile->file_buffer_size)
1971     {
1972         WINE_ERR("internal file %s does not fit\n", name);
1973         return FALSE;
1974     }
1975     *subend = *subbuf + GET_UINT(*subbuf, 0);
1976     if (*subend > hlpfile->file_buffer + hlpfile->file_buffer_size)
1977     {
1978         WINE_ERR("internal file %s does not fit\n", name);
1979         return FALSE;
1980     }
1981     if (GET_UINT(*subbuf, 0) < GET_UINT(*subbuf, 4) + 9)
1982     {
1983         WINE_ERR("invalid size provided for internal file %s\n", name);
1984         return FALSE;
1985     }
1986     return TRUE;
1987 }
1988
1989 /***********************************************************************
1990  *
1991  *           HLPFILE_SystemCommands
1992  */
1993 static BOOL HLPFILE_SystemCommands(HLPFILE* hlpfile)
1994 {
1995     BYTE *buf, *ptr, *end;
1996     HLPFILE_MACRO *macro, **m;
1997     LPSTR p;
1998     unsigned short magic, minor, major, flags;
1999
2000     hlpfile->lpszTitle = NULL;
2001
2002     if (!HLPFILE_FindSubFile(hlpfile, "|SYSTEM", &buf, &end)) return FALSE;
2003
2004     magic = GET_USHORT(buf + 9, 0);
2005     minor = GET_USHORT(buf + 9, 2);
2006     major = GET_USHORT(buf + 9, 4);
2007     /* gen date on 4 bytes */
2008     flags = GET_USHORT(buf + 9, 10);
2009     WINE_TRACE("Got system header: magic=%04x version=%d.%d flags=%04x\n",
2010                magic, major, minor, flags);
2011     if (magic != 0x036C || major != 1)
2012     {WINE_WARN("Wrong system header\n"); return FALSE;}
2013     if (minor <= 16)
2014     {
2015         hlpfile->tbsize = 0x800;
2016         hlpfile->compressed = 0;
2017     }
2018     else if (flags == 0)
2019     {
2020         hlpfile->tbsize = 0x1000;
2021         hlpfile->compressed = 0;
2022     }
2023     else if (flags == 4)
2024     {
2025         hlpfile->tbsize = 0x1000;
2026         hlpfile->compressed = 1;
2027     }
2028     else
2029     {
2030         hlpfile->tbsize = 0x800;
2031         hlpfile->compressed = 1;
2032     }
2033
2034     if (hlpfile->compressed)
2035         hlpfile->dsize = 0x4000;
2036     else
2037         hlpfile->dsize = hlpfile->tbsize - 0x0C;
2038
2039     hlpfile->version = minor;
2040     hlpfile->flags = flags;
2041     hlpfile->charset = DEFAULT_CHARSET;
2042
2043     for (ptr = buf + 0x15; ptr + 4 <= end; ptr += GET_USHORT(ptr, 2) + 4)
2044     {
2045         char *str = (char*) ptr + 4;
2046         switch (GET_USHORT(ptr, 0))
2047         {
2048         case 1:
2049             if (hlpfile->lpszTitle) {WINE_WARN("title\n"); break;}
2050             hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
2051             if (!hlpfile->lpszTitle) return FALSE;
2052             lstrcpy(hlpfile->lpszTitle, str);
2053             WINE_TRACE("Title: %s\n", hlpfile->lpszTitle);
2054             break;
2055
2056         case 2:
2057             if (hlpfile->lpszCopyright) {WINE_WARN("copyright\n"); break;}
2058             hlpfile->lpszCopyright = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
2059             if (!hlpfile->lpszCopyright) return FALSE;
2060             lstrcpy(hlpfile->lpszCopyright, str);
2061             WINE_TRACE("Copyright: %s\n", hlpfile->lpszCopyright);
2062             break;
2063
2064         case 3:
2065             if (GET_USHORT(ptr, 2) != 4) {WINE_WARN("system3\n");break;}
2066             hlpfile->contents_start = GET_UINT(ptr, 4);
2067             WINE_TRACE("Setting contents start at %08lx\n", hlpfile->contents_start);
2068             break;
2069
2070         case 4:
2071             macro = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_MACRO) + lstrlen(str) + 1);
2072             if (!macro) break;
2073             p = (char*)macro + sizeof(HLPFILE_MACRO);
2074             lstrcpy(p, str);
2075             macro->lpszMacro = p;
2076             macro->next = 0;
2077             for (m = &hlpfile->first_macro; *m; m = &(*m)->next);
2078             *m = macro;
2079             break;
2080
2081         case 5:
2082             if (GET_USHORT(ptr, 4 + 4) != 1)
2083                 WINE_FIXME("More than one icon, picking up first\n");
2084             /* 0x16 is sizeof(CURSORICONDIR), see user32/user_private.h */
2085             hlpfile->hIcon = CreateIconFromResourceEx(ptr + 4 + 0x16,
2086                                                       GET_USHORT(ptr, 2) - 0x16, TRUE,
2087                                                       0x30000, 0, 0, 0);
2088             break;
2089
2090         case 6:
2091             if (GET_USHORT(ptr, 2) != 90) {WINE_WARN("system6\n");break;}
2092
2093             if (hlpfile->windows) 
2094                 hlpfile->windows = HeapReAlloc(GetProcessHeap(), 0, hlpfile->windows, 
2095                                            sizeof(HLPFILE_WINDOWINFO) * ++hlpfile->numWindows);
2096             else 
2097                 hlpfile->windows = HeapAlloc(GetProcessHeap(), 0, 
2098                                            sizeof(HLPFILE_WINDOWINFO) * ++hlpfile->numWindows);
2099             
2100             if (hlpfile->windows)
2101             {
2102                 unsigned flags = GET_USHORT(ptr, 4);
2103                 HLPFILE_WINDOWINFO* wi = &hlpfile->windows[hlpfile->numWindows - 1];
2104
2105                 if (flags & 0x0001) strcpy(wi->type, &str[2]);
2106                 else wi->type[0] = '\0';
2107                 if (flags & 0x0002) strcpy(wi->name, &str[12]);
2108                 else wi->name[0] = '\0';
2109                 if (flags & 0x0004) strcpy(wi->caption, &str[21]);
2110                 else lstrcpynA(wi->caption, hlpfile->lpszTitle, sizeof(wi->caption));
2111                 wi->origin.x = (flags & 0x0008) ? GET_USHORT(ptr, 76) : CW_USEDEFAULT;
2112                 wi->origin.y = (flags & 0x0010) ? GET_USHORT(ptr, 78) : CW_USEDEFAULT;
2113                 wi->size.cx = (flags & 0x0020) ? GET_USHORT(ptr, 80) : CW_USEDEFAULT;
2114                 wi->size.cy = (flags & 0x0040) ? GET_USHORT(ptr, 82) : CW_USEDEFAULT;
2115                 wi->style = (flags & 0x0080) ? GET_USHORT(ptr, 84) : SW_SHOW;
2116                 wi->win_style = WS_OVERLAPPEDWINDOW;
2117                 wi->sr_color = (flags & 0x0100) ? GET_UINT(ptr, 86) : 0xFFFFFF;
2118                 wi->nsr_color = (flags & 0x0200) ? GET_UINT(ptr, 90) : 0xFFFFFF;
2119                 WINE_TRACE("System-Window: flags=%c%c%c%c%c%c%c%c type=%s name=%s caption=%s (%d,%d)x(%d,%d)\n",
2120                            flags & 0x0001 ? 'T' : 't',
2121                            flags & 0x0002 ? 'N' : 'n',
2122                            flags & 0x0004 ? 'C' : 'c',
2123                            flags & 0x0008 ? 'X' : 'x',
2124                            flags & 0x0010 ? 'Y' : 'y',
2125                            flags & 0x0020 ? 'W' : 'w',
2126                            flags & 0x0040 ? 'H' : 'h',
2127                            flags & 0x0080 ? 'S' : 's',
2128                            wi->type, wi->name, wi->caption, wi->origin.x, wi->origin.y,
2129                            wi->size.cx, wi->size.cy);
2130             }
2131             break;
2132         case 8:
2133             WINE_WARN("Citation: '%s'\n", ptr + 4);
2134             break;
2135         case 11:
2136             hlpfile->charset = ptr[4];
2137             WINE_TRACE("Charset: %d\n", hlpfile->charset);
2138             break;
2139         default:
2140             WINE_WARN("Unsupported SystemRecord[%d]\n", GET_USHORT(ptr, 0));
2141         }
2142     }
2143     if (!hlpfile->lpszTitle)
2144         hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 1);
2145     return TRUE;
2146 }
2147
2148 /***********************************************************************
2149  *
2150  *           HLPFILE_UncompressedLZ77_Size
2151  */
2152 static INT HLPFILE_UncompressedLZ77_Size(BYTE *ptr, BYTE *end)
2153 {
2154     int  i, newsize = 0;
2155
2156     while (ptr < end)
2157     {
2158         int mask = *ptr++;
2159         for (i = 0; i < 8 && ptr < end; i++, mask >>= 1)
2160         {
2161             if (mask & 1)
2162             {
2163                 int code = GET_USHORT(ptr, 0);
2164                 int len  = 3 + (code >> 12);
2165                 newsize += len;
2166                 ptr     += 2;
2167             }
2168             else newsize++, ptr++;
2169         }
2170     }
2171
2172     return newsize;
2173 }
2174
2175 /***********************************************************************
2176  *
2177  *           HLPFILE_UncompressLZ77
2178  */
2179 static BYTE *HLPFILE_UncompressLZ77(BYTE *ptr, BYTE *end, BYTE *newptr)
2180 {
2181     int i;
2182
2183     while (ptr < end)
2184     {
2185         int mask = *ptr++;
2186         for (i = 0; i < 8 && ptr < end; i++, mask >>= 1)
2187         {
2188             if (mask & 1)
2189             {
2190                 int code   = GET_USHORT(ptr, 0);
2191                 int len    = 3 + (code >> 12);
2192                 int offset = code & 0xfff;
2193                 /*
2194                  * We must copy byte-by-byte here. We cannot use memcpy nor
2195                  * memmove here. Just example:
2196                  * a[]={1,2,3,4,5,6,7,8,9,10}
2197                  * newptr=a+2;
2198                  * offset=1;
2199                  * We expect:
2200                  * {1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 11, 12}
2201                  */
2202                 for (; len>0; len--, newptr++) *newptr = *(newptr-offset-1);
2203                 ptr    += 2;
2204             }
2205             else *newptr++ = *ptr++;
2206         }
2207     }
2208
2209     return newptr;
2210 }
2211
2212 /***********************************************************************
2213  *
2214  *           HLPFILE_UncompressLZ77_Phrases
2215  */
2216 static BOOL HLPFILE_UncompressLZ77_Phrases(HLPFILE* hlpfile)
2217 {
2218     UINT i, num, dec_size, head_size;
2219     BYTE *buf, *end;
2220
2221     if (!HLPFILE_FindSubFile(hlpfile, "|Phrases", &buf, &end)) return FALSE;
2222
2223     if (hlpfile->version <= 16)
2224         head_size = 13;
2225     else
2226         head_size = 17;
2227
2228     num = hlpfile->num_phrases = GET_USHORT(buf, 9);
2229     if (buf + 2 * num + 0x13 >= end) {WINE_WARN("1a\n"); return FALSE;};
2230
2231     if (hlpfile->version <= 16)
2232         dec_size = end - buf - 15 - 2 * num;
2233     else
2234         dec_size = HLPFILE_UncompressedLZ77_Size(buf + 0x13 + 2 * num, end);
2235
2236     hlpfile->phrases_offsets = HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned) * (num + 1));
2237     hlpfile->phrases_buffer  = HeapAlloc(GetProcessHeap(), 0, dec_size);
2238     if (!hlpfile->phrases_offsets || !hlpfile->phrases_buffer)
2239     {
2240         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2241         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2242         return FALSE;
2243     }
2244
2245     for (i = 0; i <= num; i++)
2246         hlpfile->phrases_offsets[i] = GET_USHORT(buf, head_size + 2 * i) - 2 * num - 2;
2247
2248     if (hlpfile->version <= 16)
2249         memcpy(hlpfile->phrases_buffer, buf + 15 + 2*num, dec_size);
2250     else
2251         HLPFILE_UncompressLZ77(buf + 0x13 + 2 * num, end, (BYTE*)hlpfile->phrases_buffer);
2252
2253     hlpfile->hasPhrases = TRUE;
2254     return TRUE;
2255 }
2256
2257 /***********************************************************************
2258  *
2259  *           HLPFILE_Uncompress_Phrases40
2260  */
2261 static BOOL HLPFILE_Uncompress_Phrases40(HLPFILE* hlpfile)
2262 {
2263     UINT num;
2264     INT dec_size, cpr_size;
2265     BYTE *buf_idx, *end_idx;
2266     BYTE *buf_phs, *end_phs;
2267     long* ptr, mask = 0;
2268     unsigned int i;
2269     unsigned short bc, n;
2270
2271     if (!HLPFILE_FindSubFile(hlpfile, "|PhrIndex", &buf_idx, &end_idx) ||
2272         !HLPFILE_FindSubFile(hlpfile, "|PhrImage", &buf_phs, &end_phs)) return FALSE;
2273
2274     ptr = (long*)(buf_idx + 9 + 28);
2275     bc = GET_USHORT(buf_idx, 9 + 24) & 0x0F;
2276     num = hlpfile->num_phrases = GET_USHORT(buf_idx, 9 + 4);
2277
2278     WINE_TRACE("Index: Magic=%08x #entries=%u CpsdSize=%u PhrImgSize=%u\n"
2279                "\tPhrImgCprsdSize=%u 0=%u bc=%x ukn=%x\n",
2280                GET_UINT(buf_idx, 9 + 0),
2281                GET_UINT(buf_idx, 9 + 4),
2282                GET_UINT(buf_idx, 9 + 8),
2283                GET_UINT(buf_idx, 9 + 12),
2284                GET_UINT(buf_idx, 9 + 16),
2285                GET_UINT(buf_idx, 9 + 20),
2286                GET_USHORT(buf_idx, 9 + 24),
2287                GET_USHORT(buf_idx, 9 + 26));
2288
2289     dec_size = GET_UINT(buf_idx, 9 + 12);
2290     cpr_size = GET_UINT(buf_idx, 9 + 16);
2291
2292     if (dec_size != cpr_size &&
2293         dec_size != HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs))
2294     {
2295         WINE_WARN("size mismatch %u %u\n",
2296                   dec_size, HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs));
2297         dec_size = max(dec_size, HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs));
2298     }
2299
2300     hlpfile->phrases_offsets = HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned) * (num + 1));
2301     hlpfile->phrases_buffer  = HeapAlloc(GetProcessHeap(), 0, dec_size);
2302     if (!hlpfile->phrases_offsets || !hlpfile->phrases_buffer)
2303     {
2304         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2305         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2306         return FALSE;
2307     }
2308
2309 #define getbit() (ptr += (mask < 0), mask = mask*2 + (mask<=0), (*ptr & mask) != 0)
2310
2311     hlpfile->phrases_offsets[0] = 0;
2312     for (i = 0; i < num; i++)
2313     {
2314         for (n = 1; getbit(); n += 1 << bc);
2315         if (getbit()) n++;
2316         if (bc > 1 && getbit()) n += 2;
2317         if (bc > 2 && getbit()) n += 4;
2318         if (bc > 3 && getbit()) n += 8;
2319         if (bc > 4 && getbit()) n += 16;
2320         hlpfile->phrases_offsets[i + 1] = hlpfile->phrases_offsets[i] + n;
2321     }
2322 #undef getbit
2323
2324     if (dec_size == cpr_size)
2325         memcpy(hlpfile->phrases_buffer, buf_phs + 9, dec_size);
2326     else
2327         HLPFILE_UncompressLZ77(buf_phs + 9, end_phs, (BYTE*)hlpfile->phrases_buffer);
2328
2329     hlpfile->hasPhrases40 = TRUE;
2330     return TRUE;
2331 }
2332
2333 /***********************************************************************
2334  *
2335  *           HLPFILE_Uncompress_Topic
2336  */
2337 static BOOL HLPFILE_Uncompress_Topic(HLPFILE* hlpfile)
2338 {
2339     BYTE *buf, *ptr, *end, *newptr;
2340     unsigned int i, newsize = 0;
2341     unsigned int topic_size;
2342
2343     if (!HLPFILE_FindSubFile(hlpfile, "|TOPIC", &buf, &end))
2344     {WINE_WARN("topic0\n"); return FALSE;}
2345
2346     buf += 9; /* Skip file header */
2347     topic_size = end - buf;
2348     if (hlpfile->compressed)
2349     {
2350         hlpfile->topic_maplen = (topic_size - 1) / hlpfile->tbsize + 1;
2351
2352         for (i = 0; i < hlpfile->topic_maplen; i++)
2353         {
2354             ptr = buf + i * hlpfile->tbsize;
2355
2356             /* I don't know why, it's necessary for printman.hlp */
2357             if (ptr + 0x44 > end) ptr = end - 0x44;
2358
2359             newsize += HLPFILE_UncompressedLZ77_Size(ptr + 0xc, min(end, ptr + hlpfile->tbsize));
2360         }
2361
2362         hlpfile->topic_map = HeapAlloc(GetProcessHeap(), 0,
2363                                        hlpfile->topic_maplen * sizeof(hlpfile->topic_map[0]) + newsize);
2364         if (!hlpfile->topic_map) return FALSE;
2365         newptr = (BYTE*)(hlpfile->topic_map + hlpfile->topic_maplen);
2366         hlpfile->topic_end = newptr + newsize;
2367
2368         for (i = 0; i < hlpfile->topic_maplen; i++)
2369         {
2370             ptr = buf + i * hlpfile->tbsize;
2371             if (ptr + 0x44 > end) ptr = end - 0x44;
2372
2373             hlpfile->topic_map[i] = newptr;
2374             newptr = HLPFILE_UncompressLZ77(ptr + 0xc, min(end, ptr + hlpfile->tbsize), newptr);
2375         }
2376     }
2377     else
2378     {
2379         /* basically, we need to copy the TopicBlockSize byte pages
2380          * (removing the first 0x0C) in one single area in memory
2381          */
2382         hlpfile->topic_maplen = (topic_size - 1) / hlpfile->tbsize + 1;
2383         hlpfile->topic_map = HeapAlloc(GetProcessHeap(), 0,
2384                                        hlpfile->topic_maplen * (sizeof(hlpfile->topic_map[0]) + hlpfile->dsize));
2385         if (!hlpfile->topic_map) return FALSE;
2386         newptr = (BYTE*)(hlpfile->topic_map + hlpfile->topic_maplen);
2387         hlpfile->topic_end = newptr + topic_size;
2388
2389         for (i = 0; i < hlpfile->topic_maplen; i++)
2390         {
2391             hlpfile->topic_map[i] = newptr + i * hlpfile->dsize;
2392             memcpy(hlpfile->topic_map[i], buf + i * hlpfile->tbsize + 0x0C, hlpfile->dsize);
2393         }
2394     }
2395     return TRUE;
2396 }
2397
2398 /***********************************************************************
2399  *
2400  *           HLPFILE_Uncompress2
2401  */
2402
2403 static void HLPFILE_Uncompress2(HLPFILE* hlpfile, const BYTE *ptr, const BYTE *end, BYTE *newptr, const BYTE *newend)
2404 {
2405     BYTE *phptr, *phend;
2406     UINT code;
2407     UINT index;
2408
2409     while (ptr < end && newptr < newend)
2410     {
2411         if (!*ptr || *ptr >= 0x10)
2412             *newptr++ = *ptr++;
2413         else
2414         {
2415             code  = 0x100 * ptr[0] + ptr[1];
2416             index = (code - 0x100) / 2;
2417
2418             phptr = (BYTE*)hlpfile->phrases_buffer + hlpfile->phrases_offsets[index];
2419             phend = (BYTE*)hlpfile->phrases_buffer + hlpfile->phrases_offsets[index + 1];
2420
2421             if (newptr + (phend - phptr) > newend)
2422             {
2423                 WINE_FIXME("buffer overflow %p > %p for %lu bytes\n",
2424                            newptr, newend, (SIZE_T)(phend - phptr));
2425                 return;
2426             }
2427             memcpy(newptr, phptr, phend - phptr);
2428             newptr += phend - phptr;
2429             if (code & 1) *newptr++ = ' ';
2430
2431             ptr += 2;
2432         }
2433     }
2434     if (newptr > newend) WINE_FIXME("buffer overflow %p > %p\n", newptr, newend);
2435 }
2436
2437 /******************************************************************
2438  *              HLPFILE_Uncompress3
2439  *
2440  *
2441  */
2442 static BOOL HLPFILE_Uncompress3(HLPFILE* hlpfile, char* dst, const char* dst_end,
2443                                 const BYTE* src, const BYTE* src_end)
2444 {
2445     unsigned int idx, len;
2446
2447     for (; src < src_end; src++)
2448     {
2449         if ((*src & 1) == 0)
2450         {
2451             idx = *src / 2;
2452             if (idx > hlpfile->num_phrases)
2453             {
2454                 WINE_ERR("index in phrases %d/%d\n", idx, hlpfile->num_phrases);
2455                 len = 0;
2456             }
2457             else 
2458             {
2459                 len = hlpfile->phrases_offsets[idx + 1] - hlpfile->phrases_offsets[idx];
2460                 if (dst + len <= dst_end)
2461                     memcpy(dst, &hlpfile->phrases_buffer[hlpfile->phrases_offsets[idx]], len);
2462             }
2463         }
2464         else if ((*src & 0x03) == 0x01)
2465         {
2466             idx = (*src + 1) * 64;
2467             idx += *++src;
2468             if (idx > hlpfile->num_phrases)
2469             {
2470                 WINE_ERR("index in phrases %d/%d\n", idx, hlpfile->num_phrases);
2471                 len = 0;
2472             }
2473             else
2474             {
2475                 len = hlpfile->phrases_offsets[idx + 1] - hlpfile->phrases_offsets[idx];
2476                 if (dst + len <= dst_end)
2477                     memcpy(dst, &hlpfile->phrases_buffer[hlpfile->phrases_offsets[idx]], len);
2478             }
2479         }
2480         else if ((*src & 0x07) == 0x03)
2481         {
2482             len = (*src / 8) + 1;
2483             if (dst + len <= dst_end)
2484                 memcpy(dst, src + 1, len);
2485             src += len;
2486         }
2487         else
2488         {
2489             len = (*src / 16) + 1;
2490             if (dst + len <= dst_end)
2491                 memset(dst, ((*src & 0x0F) == 0x07) ? ' ' : 0, len);
2492         }
2493         dst += len;
2494     }
2495
2496     if (dst > dst_end) WINE_ERR("buffer overflow (%p > %p)\n", dst, dst_end);
2497     return TRUE;
2498 }
2499
2500 /******************************************************************
2501  *              HLPFILE_UncompressRLE
2502  *
2503  *
2504  */
2505 static void HLPFILE_UncompressRLE(const BYTE* src, const BYTE* end, BYTE** dst, unsigned dstsz)
2506 {
2507     BYTE        ch;
2508     BYTE*       sdst = *dst + dstsz;
2509
2510     while (src < end)
2511     {
2512         ch = *src++;
2513         if (ch & 0x80)
2514         {
2515             ch &= 0x7F;
2516             if ((*dst) + ch <= sdst)
2517                 memcpy(*dst, src, ch);
2518             src += ch;
2519         }
2520         else
2521         {
2522             if ((*dst) + ch <= sdst)
2523                 memset(*dst, (char)*src, ch);
2524             src++;
2525         }
2526         *dst += ch;
2527     }
2528     if (*dst != sdst)
2529         WINE_WARN("Buffer X-flow: d(%lu) instead of d(%u)\n",
2530                   (SIZE_T)(*dst - (sdst - dstsz)), dstsz);
2531 }
2532
2533 /**************************************************************************
2534  * HLPFILE_BPTreeSearch
2535  *
2536  * Searches for an element in B+ tree
2537  *
2538  * PARAMS
2539  *     buf        [I] pointer to the embedded file structured as a B+ tree
2540  *     key        [I] pointer to data to find
2541  *     comp       [I] compare function
2542  *
2543  * RETURNS
2544  *     Pointer to block identified by key, or NULL if failure.
2545  *
2546  */
2547 void* HLPFILE_BPTreeSearch(BYTE* buf, const void* key,
2548                            HLPFILE_BPTreeCompare comp)
2549 {
2550     unsigned magic;
2551     unsigned page_size;
2552     unsigned cur_page;
2553     unsigned level;
2554     BYTE *pages, *ptr, *newptr;
2555     int i, entries;
2556     int ret;
2557
2558     magic = GET_USHORT(buf, 9);
2559     if (magic != 0x293B)
2560     {
2561         WINE_ERR("Invalid magic in B+ tree: 0x%x\n", magic);
2562         return NULL;
2563     }
2564     page_size = GET_USHORT(buf, 9+4);
2565     cur_page  = GET_USHORT(buf, 9+26);
2566     level     = GET_USHORT(buf, 9+32);
2567     pages     = buf + 9 + 38;
2568     while (--level > 0)
2569     {
2570         ptr = pages + cur_page*page_size;
2571         entries = GET_SHORT(ptr, 2);
2572         ptr += 6;
2573         for (i = 0; i < entries; i++)
2574         {
2575             if (comp(ptr, key, 0, (void **)&newptr) > 0) break;
2576             ptr = newptr;
2577         }
2578         cur_page = GET_USHORT(ptr-2, 0);
2579     }
2580     ptr = pages + cur_page*page_size;
2581     entries = GET_SHORT(ptr, 2);
2582     ptr += 8;
2583     for (i = 0; i < entries; i++)
2584     {
2585         ret = comp(ptr, key, 1, (void **)&newptr);
2586         if (ret == 0) return ptr;
2587         if (ret > 0) return NULL;
2588         ptr = newptr;
2589     }
2590     return NULL;
2591 }
2592
2593 /**************************************************************************
2594  * HLPFILE_BPTreeEnum
2595  *
2596  * Enumerates elements in B+ tree.
2597  *
2598  * PARAMS
2599  *     buf        [I]  pointer to the embedded file structured as a B+ tree
2600  *     cb         [I]  compare function
2601  *     cookie     [IO] cookie for cb function
2602  */
2603 void HLPFILE_BPTreeEnum(BYTE* buf, HLPFILE_BPTreeCallback cb, void* cookie)
2604 {
2605     unsigned magic;
2606     unsigned page_size;
2607     unsigned cur_page;
2608     unsigned level;
2609     BYTE *pages, *ptr, *newptr;
2610     int i, entries;
2611
2612     magic = GET_USHORT(buf, 9);
2613     if (magic != 0x293B)
2614     {
2615         WINE_ERR("Invalid magic in B+ tree: 0x%x\n", magic);
2616         return;
2617     }
2618     page_size = GET_USHORT(buf, 9+4);
2619     cur_page  = GET_USHORT(buf, 9+26);
2620     level     = GET_USHORT(buf, 9+32);
2621     pages     = buf + 9 + 38;
2622     while (--level > 0)
2623     {
2624         ptr = pages + cur_page*page_size;
2625         cur_page = GET_USHORT(ptr, 4);
2626     }
2627     while (cur_page != 0xFFFF)
2628     {
2629         ptr = pages + cur_page*page_size;
2630         entries = GET_SHORT(ptr, 2);
2631         ptr += 8;
2632         for (i = 0; i < entries; i++)
2633         {
2634             cb(ptr, (void **)&newptr, cookie);
2635             ptr = newptr;
2636         }
2637         cur_page = GET_USHORT(pages+cur_page*page_size, 6);
2638     }
2639 }
2640
2641
2642 /***********************************************************************
2643  *
2644  *           HLPFILE_GetContext
2645  */
2646 static BOOL HLPFILE_GetContext(HLPFILE *hlpfile)
2647 {
2648     BYTE                *cbuf, *cend;
2649     unsigned            clen;
2650
2651     if (!HLPFILE_FindSubFile(hlpfile, "|CONTEXT",  &cbuf, &cend))
2652     {WINE_WARN("context0\n"); return FALSE;}
2653
2654     clen = cend - cbuf;
2655     hlpfile->Context = HeapAlloc(GetProcessHeap(), 0, clen);
2656     if (!hlpfile->Context) return FALSE;
2657     memcpy(hlpfile->Context, cbuf, clen);
2658
2659     return TRUE;
2660 }
2661
2662 /***********************************************************************
2663  *
2664  *           HLPFILE_GetKeywords
2665  */
2666 static BOOL HLPFILE_GetKeywords(HLPFILE *hlpfile)
2667 {
2668     BYTE                *cbuf, *cend;
2669     unsigned            clen;
2670
2671     if (!HLPFILE_FindSubFile(hlpfile, "|KWBTREE", &cbuf, &cend)) return FALSE;
2672     clen = cend - cbuf;
2673     hlpfile->kwbtree = HeapAlloc(GetProcessHeap(), 0, clen);
2674     if (!hlpfile->kwbtree) return FALSE;
2675     memcpy(hlpfile->kwbtree, cbuf, clen);
2676
2677     if (!HLPFILE_FindSubFile(hlpfile, "|KWDATA", &cbuf, &cend))
2678     {
2679         WINE_ERR("corrupted help file: kwbtree present but kwdata absent\n");
2680         HeapFree(GetProcessHeap(), 0, hlpfile->kwbtree);
2681         return FALSE;
2682     }
2683     clen = cend - cbuf;
2684     hlpfile->kwdata = HeapAlloc(GetProcessHeap(), 0, clen);
2685     if (!hlpfile->kwdata)
2686     {
2687         HeapFree(GetProcessHeap(), 0, hlpfile->kwdata);
2688         return FALSE;
2689     }
2690     memcpy(hlpfile->kwdata, cbuf, clen);
2691
2692     return TRUE;
2693 }
2694
2695 /***********************************************************************
2696  *
2697  *           HLPFILE_GetMap
2698  */
2699 static BOOL HLPFILE_GetMap(HLPFILE *hlpfile)
2700 {
2701     BYTE                *cbuf, *cend;
2702     unsigned            entries, i;
2703
2704     if (!HLPFILE_FindSubFile(hlpfile, "|CTXOMAP",  &cbuf, &cend))
2705     {WINE_WARN("no map section\n"); return FALSE;}
2706
2707     entries = GET_USHORT(cbuf, 9);
2708     hlpfile->Map = HeapAlloc(GetProcessHeap(), 0, entries * sizeof(HLPFILE_MAP));
2709     if (!hlpfile->Map) return FALSE;
2710     hlpfile->wMapLen = entries;
2711     for (i = 0; i < entries; i++)
2712     {
2713         hlpfile->Map[i].lMap = GET_UINT(cbuf+11,i*8);
2714         hlpfile->Map[i].offset = GET_UINT(cbuf+11,i*8+4);
2715     }
2716     return TRUE;
2717 }
2718
2719 /******************************************************************
2720  *              HLPFILE_DeleteLink
2721  *
2722  *
2723  */
2724 void HLPFILE_FreeLink(HLPFILE_LINK* link)
2725 {
2726     if (link && !--link->wRefCount)
2727     {
2728         HeapFree(GetProcessHeap(), 0, link);
2729     }
2730 }
2731
2732 /***********************************************************************
2733  *
2734  *           HLPFILE_DeleteParagraph
2735  */
2736 static void HLPFILE_DeleteParagraph(HLPFILE_PARAGRAPH* paragraph)
2737 {
2738     HLPFILE_PARAGRAPH* next;
2739
2740     while (paragraph)
2741     {
2742         next = paragraph->next;
2743
2744         if (paragraph->cookie == para_metafile)
2745             DeleteMetaFile(paragraph->u.gfx.u.mfp.hMF);
2746
2747         HLPFILE_FreeLink(paragraph->link);
2748
2749         HeapFree(GetProcessHeap(), 0, paragraph);
2750         paragraph = next;
2751     }
2752 }
2753
2754 /***********************************************************************
2755  *
2756  *           DeleteMacro
2757  */
2758 static void HLPFILE_DeleteMacro(HLPFILE_MACRO* macro)
2759 {
2760     HLPFILE_MACRO*      next;
2761
2762     while (macro)
2763     {
2764         next = macro->next;
2765         HeapFree(GetProcessHeap(), 0, macro);
2766         macro = next;
2767     }
2768 }
2769
2770 /***********************************************************************
2771  *
2772  *           DeletePage
2773  */
2774 static void HLPFILE_DeletePage(HLPFILE_PAGE* page)
2775 {
2776     HLPFILE_PAGE* next;
2777
2778     while (page)
2779     {
2780         next = page->next;
2781         HLPFILE_DeleteParagraph(page->first_paragraph);
2782         HLPFILE_DeleteMacro(page->first_macro);
2783         HeapFree(GetProcessHeap(), 0, page);
2784         page = next;
2785     }
2786 }
2787
2788 /***********************************************************************
2789  *
2790  *           HLPFILE_FreeHlpFile
2791  */
2792 void HLPFILE_FreeHlpFile(HLPFILE* hlpfile)
2793 {
2794     unsigned i;
2795
2796     if (!hlpfile || --hlpfile->wRefCount > 0) return;
2797
2798     if (hlpfile->next) hlpfile->next->prev = hlpfile->prev;
2799     if (hlpfile->prev) hlpfile->prev->next = hlpfile->next;
2800     else first_hlpfile = hlpfile->next;
2801
2802     if (hlpfile->numFonts)
2803     {
2804         for (i = 0; i < hlpfile->numFonts; i++)
2805         {
2806             DeleteObject(hlpfile->fonts[i].hFont);
2807         }
2808         HeapFree(GetProcessHeap(), 0, hlpfile->fonts);
2809     }
2810
2811     if (hlpfile->numBmps)
2812     {
2813         for (i = 0; i < hlpfile->numBmps; i++)
2814         {
2815             DeleteObject(hlpfile->bmps[i]);
2816         }
2817         HeapFree(GetProcessHeap(), 0, hlpfile->bmps);
2818     }
2819
2820     HLPFILE_DeletePage(hlpfile->first_page);
2821     HLPFILE_DeleteMacro(hlpfile->first_macro);
2822
2823     DestroyIcon(hlpfile->hIcon);
2824     if (hlpfile->numWindows)    HeapFree(GetProcessHeap(), 0, hlpfile->windows);
2825     HeapFree(GetProcessHeap(), 0, hlpfile->Context);
2826     HeapFree(GetProcessHeap(), 0, hlpfile->Map);
2827     HeapFree(GetProcessHeap(), 0, hlpfile->lpszTitle);
2828     HeapFree(GetProcessHeap(), 0, hlpfile->lpszCopyright);
2829     HeapFree(GetProcessHeap(), 0, hlpfile->file_buffer);
2830     HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2831     HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2832     HeapFree(GetProcessHeap(), 0, hlpfile->topic_map);
2833     HeapFree(GetProcessHeap(), 0, hlpfile);
2834 }