c49eb1d33e6d462c14ae129b19143a3721102dc8
[m17n/libotf.git] / src / otfopen.c
1 /* otfopen.c -- OpenType font reader.
2
3 Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009
4   National Institute of Advanced Industrial Science and Technology (AIST)
5   Registration Number H15PRO167
6
7 This file is part of libotf.
8
9 Libotf is free software; you can redistribute it and/or modify it
10 under the terms of the GNU Lesser General Public License as published
11 by the Free Software Foundation; either version 2.1 of the License, or
12 (at your option) any later version.
13
14 Libotf is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17 License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library, in a file named COPYING; if not,
21 write to the Free Software Foundation, Inc., 59 Temple Place, Suite
22 330, Boston, MA 02111-1307, USA.  */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <config.h>
28
29 #include "otf.h"
30 #include "otferror.h"
31
32 #include FT_TRUETYPE_TABLES_H
33
34 /***
35     Table of contents (almost parallel to otf.h):
36
37     (0) Stream handler
38
39     (1) Readers for OTF Layout tables and OTF itself
40     (1-1) Basic types and functions
41     (1-2) "head" table
42     (1-3) "name" table
43     (1-4) "cmap" table
44     (1-5) Structures common to GDEF, GSUB, and GPOS
45     (1-6) "GDEF" table
46     (1-7) Structures for ScriptList, FeatureList, and LookupList
47     (1-8) Structures common to GSUB and GPOS
48     (1-9) "GSUB" table
49     (1-10) "GPOS" table
50     (1-11) Structure for OTF
51
52     (2) API for reading OTF
53     (2-1) OTF_open()
54     (2-2) OTF_close()
55     (2-3) OTF_get_table()
56     (2-4) OTF_check_table()
57
58     (5) API miscellaneous
59 */
60
61 int debug_flag = -1;
62
63 static void
64 set_debug_flag ()
65 {
66   debug_flag = getenv ("LIBOTF_DEBUG") != NULL;
67 }
68
69 \f
70 /* (0) Stream handler
71
72    Example of typical usage of OTF_Stream.
73
74     {
75       OTF_Stream *stream;
76       OTF_StreamState state;
77       int offset, nbytes;
78
79       OPEN_STREAM (_FILE_NAME_, stream);
80       if (! stream)
81         _ERROR_;
82       SETUP_STREAM (stream, fp, 0, 256, _NAME_);
83       offset = READ_OFFSET (stream);
84       nbytes = READ_ULONG (stream);
85       SETUP_STREAM (stream, fp, offset, nbytes, _NAME2_);
86       ...;
87       CLOSE_STREAM (stream);
88     }
89
90 */
91
92 typedef struct
93 {
94   const char *name;
95   long pos;
96   long bufsize;
97   long allocated;
98   unsigned char *buf;
99 } OTF_Stream;
100
101 typedef long OTF_StreamState;
102
103 static OTF_Stream *
104 make_stream (const char *name)
105 {
106   OTF_Stream *stream;
107   char *errfmt = "stream creation%s";
108   void *errret = NULL;
109
110   stream = calloc (1, sizeof (OTF_Stream));
111   if (! stream)
112     OTF_ERROR (OTF_ERROR_MEMORY, "");
113   stream->name = name;
114   return stream;
115 }
116
117 static int
118 setup_stream (OTF_Stream *stream, FILE *fp, long offset, int nbytes)
119 {
120   char *errfmt = "stream setup for %s";
121   int errret = -1;
122
123   stream->pos = 0;
124   if (stream->allocated < nbytes)
125     {
126       unsigned char *buf = malloc (nbytes);
127
128       if (! buf)
129         OTF_ERROR (OTF_ERROR_MEMORY, stream->name);
130       if (stream->buf)
131         free (stream->buf);
132       stream->buf = buf;
133       stream->allocated = nbytes;
134     }
135   stream->bufsize = nbytes;
136   if (fseek (fp, offset, SEEK_SET) < 0)
137     OTF_ERROR (OTF_ERROR_FILE, stream->name);
138   if (fread (stream->buf, 1, nbytes, fp) != nbytes)
139     OTF_ERROR (OTF_ERROR_FILE, stream->name);
140   return 0;
141 }
142
143 static OTF_Stream *
144 make_stream_from_ft_face (FT_Face face, const char *name)
145 {
146   char *errfmt = "FT_Face stream creation for %s";
147   void *errret = NULL;
148   FT_ULong nbytes = 0;
149   unsigned char *buf;
150   OTF_Stream *stream;
151   FT_ULong tag = FT_MAKE_TAG (name[0], name[1], name[2], name[3]);
152
153   if (FT_Load_Sfnt_Table (face, tag, 0, NULL, &nbytes))
154     return NULL;
155   buf = malloc (nbytes);
156   if (! buf)
157     OTF_ERROR (OTF_ERROR_MEMORY, name);
158   if (FT_Load_Sfnt_Table (face, tag, 0, buf, &nbytes))
159     {
160       free (buf);
161       OTF_ERROR (OTF_ERROR_FT_FACE, name);
162     }
163   stream = make_stream (name);
164   if (! stream)
165     return NULL;
166   stream->pos = 0;
167   stream->buf = buf;
168   stream->allocated = nbytes;
169   stream->bufsize = nbytes;
170   return stream;
171 }
172
173 static void
174 free_stream (OTF_Stream *stream)
175 {
176   if (stream->buf)
177     free (stream->buf);
178   free (stream);
179 }
180
181 #define SAVE_STREAM(stream, state) ((state) = (stream)->pos)
182 #define RESTORE_STREAM(stream, state) ((stream)->pos = (state))
183 #define SEEK_STREAM(stream, offset) ((stream)->pos = (offset))
184
185 #define STREAM_CHECK_SIZE(stream, size)                 \
186   if ((stream)->pos + (size) > (stream)->bufsize)       \
187     {                                                   \
188       char *errfmt = "buffer overrun in %s";            \
189                                                         \
190       OTF_ERROR (OTF_ERROR_TABLE, (stream)->name);      \
191       return errret;                                    \
192     }                                                   \
193   else
194
195
196 #define READ_USHORT(stream, var)                        \
197   do {                                                  \
198     STREAM_CHECK_SIZE ((stream), 2);                    \
199     (var) = (((stream)->buf[(stream)->pos] << 8)        \
200              | (stream)->buf[(stream)->pos + 1]);       \
201     (stream)->pos += 2;                                 \
202   } while (0)
203
204 #define READ_SHORT(stream, var)                                 \
205   do {                                                          \
206     STREAM_CHECK_SIZE ((stream), 2);                            \
207     (var) = (short) (((stream)->buf[(stream)->pos] << 8)        \
208                      | (stream)->buf[(stream)->pos + 1]);       \
209     (stream)->pos += 2;                                         \
210   } while (0)
211
212 #define READ_UINT24(stream, var)                        \
213   do {                                                  \
214     STREAM_CHECK_SIZE ((stream), 3);                    \
215     (var) =  (((stream)->buf[(stream)->pos ] << 16)     \
216               | ((stream)->buf[(stream)->pos + 1] << 8) \
217               | (stream)->buf[(stream)->pos + 2]);      \
218     (stream)->pos += 3;                                 \
219   } while (0)
220
221 #define READ_ULONG(stream, var)                         \
222   do {                                                  \
223     STREAM_CHECK_SIZE ((stream), 4);                    \
224     (var) = (((stream)->buf[(stream)->pos] << 24)       \
225              | ((stream)->buf[(stream)->pos + 1] << 16) \
226              | ((stream)->buf[(stream)->pos + 2] << 8)  \
227              | (stream)->buf[(stream)->pos + 3]);       \
228     (stream)->pos += 4;                                 \
229   } while (0)
230
231 #define READ_LONG(stream, var)                                  \
232   do {                                                          \
233     STREAM_CHECK_SIZE ((stream), 4);                            \
234     (var) = (int) (((stream)->buf[(stream)->pos] << 24)         \
235                    | ((stream)->buf[(stream)->pos + 1] << 16)   \
236                    | ((stream)->buf[(stream)->pos + 2] << 8)    \
237                    | (stream)->buf[(stream)->pos + 3]);         \
238     (stream)->pos += 4;                                         \
239   } while (0)
240
241
242 #define READ_FIXED(stream, fixed)               \
243   do {                                          \
244     READ_USHORT ((stream), (fixed).high);       \
245     READ_USHORT ((stream), (fixed).low);        \
246   } while (0)
247
248
249 #define READ_BYTES(stream, p, nbytes)                           \
250   do {                                                          \
251     STREAM_CHECK_SIZE ((stream), (nbytes));                     \
252     memcpy ((p), (stream)->buf + (stream)->pos, (nbytes));      \
253     (stream)->pos += (nbytes);                                  \
254   } while (0)
255
256
257 #define READ_TAG READ_ULONG
258 #define READ_OFFSET READ_USHORT
259 #define READ_UINT16 READ_USHORT
260 #define READ_INT16 READ_SHORT
261 #define READ_GLYPHID READ_USHORT
262
263 \f
264 /*** (1) Structures for OTF Layout tables and OTF itself */
265
266 /*** (1-1) Basic types and functions */
267
268 enum OTF_TableType
269   {
270     OTF_TABLE_TYPE_HEAD,
271     OTF_TABLE_TYPE_NAME,
272     OTF_TABLE_TYPE_CMAP,
273     OTF_TABLE_TYPE_GDEF,
274     OTF_TABLE_TYPE_GSUB,
275     OTF_TABLE_TYPE_GPOS,
276     OTF_TABLE_TYPE_MAX
277   };
278
279 #define OTF_MEMORY_RECORD_SIZE 1024
280
281 struct OTF_MemoryRecord
282 {
283   int used;
284   void *memory[OTF_MEMORY_RECORD_SIZE];
285   struct OTF_MemoryRecord *next;
286 };
287
288 typedef struct OTF_MemoryRecord OTF_MemoryRecord;
289
290 enum OTF_ReaderFlag
291   {
292     OTF_READ_FULL,
293     OTF_READ_SCRIPTS,
294     OTF_READ_FEATURES,
295     OTF_READ_MAX
296   };
297
298 struct _OTF_TableInfo;
299 typedef struct _OTF_TableInfo OTF_TableInfo;
300
301 struct _OTF_TableInfo
302 {
303   /* Points to one of OTF->head, OTF->name, etc.  */
304   void **address;
305   /* Function to read one of OTF tables.  */
306   void *(*reader) (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag);
307   /* Stream given to <reader>.  */
308   OTF_Stream *stream;
309 };
310
311 struct _OTF_ApplicationData
312 {
313   char *id;
314   void *data;
315   void (*freer) (void *data);
316   struct _OTF_ApplicationData *next;
317 };
318
319 typedef struct _OTF_ApplicationData OTF_ApplicationData;
320
321 struct OTF_InternalData
322 {
323   /* Information about each OTF table.  */
324   OTF_TableInfo table_info[OTF_TABLE_TYPE_MAX];
325
326   /* Stream used to read the header part of OTF.  */
327   OTF_Stream *header_stream;
328
329   /* Records of allocated memories.  */
330   OTF_MemoryRecord *memory_record;
331
332   /* Root of application data chain.  */
333   OTF_ApplicationData *app_data;
334 };
335
336
337 static OTF_MemoryRecord *
338 allocate_memory_record (OTF *otf)
339 {
340   OTF_InternalData *internal_data = (OTF_InternalData *) otf->internal_data;
341   OTF_MemoryRecord *memrec = malloc (sizeof (OTF_MemoryRecord));
342
343   if (! memrec)
344     return NULL;
345   memrec->used = 0;
346   memrec->next = internal_data->memory_record;
347   internal_data->memory_record = memrec;
348   return memrec;
349 }
350
351 /* Memory allocation macros.  */
352
353 #define OTF_MALLOC(p, size, arg)                                        \
354   do {                                                                  \
355     if (size == 0)                                                      \
356       (p) = NULL;                                                       \
357     else                                                                \
358       {                                                                 \
359         OTF_MemoryRecord *memrec                                        \
360           = ((OTF_InternalData *) otf->internal_data)->memory_record;   \
361         (p) = malloc (sizeof (*(p)) * (size));                          \
362         if (! (p)                                                       \
363             || (memrec->used >= OTF_MEMORY_RECORD_SIZE                  \
364                 && ! (memrec = allocate_memory_record (otf))))          \
365           OTF_ERROR (OTF_ERROR_MEMORY, (arg));                          \
366         memrec->memory[memrec->used++] = (p);                           \
367       }                                                                 \
368   } while (0)
369
370
371 #define OTF_CALLOC(p, size, arg)                                        \
372   do {                                                                  \
373     if (size == 0)                                                      \
374       (p) = NULL;                                                       \
375     else                                                                \
376       {                                                                 \
377         OTF_MemoryRecord *memrec                                        \
378           = ((OTF_InternalData *) otf->internal_data)->memory_record;   \
379         (p) = calloc ((size), sizeof (*(p)));                           \
380         if (! (p)                                                       \
381             || (memrec->used >= OTF_MEMORY_RECORD_SIZE                  \
382                 && ! (memrec = allocate_memory_record (otf))))          \
383           OTF_ERROR (OTF_ERROR_MEMORY, (arg));                          \
384         memrec->memory[memrec->used++] = (p);                           \
385       }                                                                 \
386   } while (0)
387
388 \f
389 /*** (1-2) "head" table */
390
391 static void *
392 read_head_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
393 {
394   OTF_Stream *stream = table->stream;
395   char *errfmt = "head%s";
396   void *errret = NULL;
397   OTF_head *head;
398
399   OTF_CALLOC (head, 1, "");
400   READ_FIXED (stream, head->TableVersionNumber);
401   READ_FIXED (stream, head->fontRevision);
402   READ_ULONG (stream, head->checkSumAdjustment);
403   READ_ULONG (stream, head->magicNumber);
404   READ_USHORT (stream, head->flags);
405   READ_USHORT (stream, head->unitsPerEm);
406
407   *table->address = head;
408   return head;
409 }
410
411 \f
412 /*** (1-3) "name" table */
413
414 static int
415 read_name (OTF *otf, OTF_Stream *stream, OTF_NameRecord *rec)
416 {
417   char errfmt[256];
418   int errret = -1;
419   OTF_StreamState state;
420   int ucs = 0;
421   int ascii = 0;
422   int i;
423
424   sprintf (errfmt, "nameID (%d)%%s", rec->nameID);
425   if (rec->platformID == 0)
426     ucs = (rec->encodingID <= 3) ? 2 : 4;
427   else if (rec->platformID == 1 && rec->encodingID == 0)
428     ascii = 1;
429   else if (rec->platformID == 3)
430     ucs = (rec->encodingID == 1  ? 2
431            : rec->encodingID == 10 ? 4
432            : 0);
433
434   OTF_MALLOC (rec->name, rec->length + 1, "");
435   SAVE_STREAM (stream, state);
436   SEEK_STREAM (stream, stream->pos + rec->offset);
437   READ_BYTES (stream, rec->name, rec->length);
438   RESTORE_STREAM (stream, state);
439   rec->name[rec->length] = 0;
440
441   if (ascii)
442     {
443       rec->ascii = 1;
444     }
445   else if (ucs == 2)
446     {
447       rec->ascii = 1;
448       for (i = 0; i < rec->length / 2; i++)
449         {
450           if (rec->name[i * 2] > 0
451               || rec->name[i * 2 + 1] >= 128)
452             {
453               rec->ascii = 0;
454               break;
455             }
456         }
457       if (rec->ascii)
458         for (i = 0; i < rec->length / 2; i++)
459           rec->name[i] = rec->name[i * 2 + 1];
460       rec->name[i] = 0;
461     }
462   else if (ucs == 4)
463     {
464       rec->ascii = 1;
465       for (i = 0; i < rec->length / 4; i++)
466         {
467           if (rec->name[i * 4] > 0
468               || rec->name[i * 4 + 1] > 0
469               || rec->name[i * 4 + 2] > 0
470               || rec->name[i * 2 + 3] >= 128)
471             {
472               rec->ascii = 0;
473               break;
474             }
475         }
476       if (rec->ascii)
477         for (i = 0; i < rec->length / 4; i++)
478           rec->name[i] = rec->name[i * 4 + 3];
479       rec->name[i] = 0;
480     }
481
482   return 0;
483 }
484
485 static void *
486 read_name_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
487 {
488   OTF_Stream *stream = table->stream;
489   char *errfmt = "name%s";
490   void *errret = NULL;
491   OTF_name *name;
492   int i;
493
494   OTF_CALLOC (name, 1, "");
495   READ_USHORT (stream, name->format);
496   READ_USHORT (stream, name->count);
497   READ_USHORT (stream, name->stringOffset);
498   OTF_MALLOC (name->nameRecord, name->count, "");
499   for (i = 0; i < name->count; i++)
500     {
501       OTF_NameRecord *rec = name->nameRecord + i;
502
503       READ_USHORT (stream, rec->platformID);
504       READ_USHORT (stream, rec->encodingID);
505       READ_USHORT (stream, rec->languageID);
506       READ_USHORT (stream, rec->nameID);
507       READ_USHORT (stream, rec->length);
508       READ_USHORT (stream, rec->offset);
509     }
510   for (i = 0; i < name->count; i++)
511     {
512       OTF_NameRecord *rec = name->nameRecord + i;
513       int nameID = rec->nameID;
514
515       read_name (otf, stream, rec);
516
517       if (nameID >= OTF_max_nameID)
518         continue;
519       if (! name->name[nameID]
520           && rec->ascii)
521         name->name[nameID] = (char *) rec->name;
522     }
523
524   *table->address = name;
525   return name;
526 }
527
528 \f
529 /*** (1-4) "cmap" table */
530
531 static OTF_EncodingSubtable14 *
532 read_cmap_uvs_table (OTF *otf, OTF_Stream *stream, OTF_Offset offset)
533 {
534   OTF_EncodingSubtable14 *sub14;
535   char *errfmt = "cmap-uvs%s";
536   void *errret = NULL;
537   unsigned nRecords;
538   unsigned i,j;
539
540   OTF_MALLOC (sub14, 1, " (EncodingSubtable14)");
541   READ_ULONG (stream, nRecords);
542   sub14->nRecords = nRecords;
543   OTF_MALLOC (sub14->Records, nRecords, "(EncodingSubtable14-Records)");
544   for (i = 0; i < sub14->nRecords; i++) 
545     {
546       unsigned varSelector=0, defaultUVSOffset, nonDefaultUVSOffset;
547
548       READ_UINT24 (stream, varSelector);
549       sub14->Records[i].varSelector = varSelector;
550       READ_ULONG (stream, defaultUVSOffset);
551       sub14->Records[i].defaultUVSOffset = defaultUVSOffset;
552       READ_ULONG (stream, nonDefaultUVSOffset);
553       sub14->Records[i].nonDefaultUVSOffset = nonDefaultUVSOffset;
554     }
555   for (i = 0; i < sub14->nRecords; i++) 
556     {
557       OTF_VariationSelectorRecord *record = &sub14->Records[i];
558       unsigned defaultUVSOffset = record->defaultUVSOffset;
559       unsigned nonDefaultUVSOffset = record->nonDefaultUVSOffset;
560
561       if (defaultUVSOffset) 
562         {
563           unsigned numUnicodeValueRanges;
564
565           SEEK_STREAM (stream, offset+defaultUVSOffset);
566           READ_ULONG (stream, numUnicodeValueRanges);
567           record->numUnicodeValueRanges = numUnicodeValueRanges;
568           OTF_MALLOC (record->unicodeValueRanges, 
569                       numUnicodeValueRanges,
570                       "(EncodingSubtable14-Records-unicodeValueRanges)");
571           for (j = 0; j < numUnicodeValueRanges; j++)
572             {
573               OTF_UnicodeValueRange *unicodeValueRange 
574                 = &record->unicodeValueRanges[j];
575               unsigned startUnicodeValue;
576               char additionalCount;
577
578               READ_UINT24 (stream, startUnicodeValue);
579               unicodeValueRange->startUnicodeValue=startUnicodeValue;
580               READ_BYTES (stream, &additionalCount, 1);
581               unicodeValueRange->additionalCount
582                 = (unsigned short) additionalCount;
583             }
584         }
585       if (nonDefaultUVSOffset) 
586         {
587           unsigned numUVSMappings;
588
589           SEEK_STREAM (stream, offset+nonDefaultUVSOffset);
590           READ_ULONG (stream, numUVSMappings);
591           record->numUVSMappings = numUVSMappings;
592           OTF_MALLOC (record->uvsMappings, numUVSMappings,
593                       "(EncodingSubtable14-Records-uvsMappings)");
594           for (j = 0; j < numUVSMappings; j++)
595             {
596               OTF_UVSMapping *uvsMapping = &record->uvsMappings[j];
597               unsigned unicodeValue;
598               unsigned short glyphID;
599
600               READ_UINT24 (stream, unicodeValue);
601               uvsMapping->unicodeValue = unicodeValue;
602               READ_USHORT (stream, glyphID);
603               uvsMapping->glyphID = glyphID;
604             }
605         }
606     }
607   return sub14;
608 }
609
610 static void *
611 read_cmap_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
612 {
613   OTF_Stream *stream = table->stream;
614   char *errfmt = "cmap%s";
615   void *errret = NULL;
616   OTF_cmap *cmap;
617   int unicode_bmp_index = -1, unicode_full_index = -1;
618   int i;
619
620   OTF_CALLOC (cmap, 1, "");
621   READ_USHORT (stream, cmap->version);
622   READ_USHORT (stream, cmap->numTables);
623   OTF_MALLOC (cmap->EncodingRecord, cmap->numTables, "");
624   for (i = 0; i < cmap->numTables; i++)
625     {
626       unsigned platformID, encodingID;
627
628       READ_USHORT (stream, platformID);
629       cmap->EncodingRecord[i].platformID = platformID;
630       READ_USHORT (stream, encodingID);
631       cmap->EncodingRecord[i].encodingID = encodingID;
632       READ_ULONG (stream, cmap->EncodingRecord[i].offset);
633       if (platformID == 0)
634         {
635           if (encodingID <= 3)
636             unicode_bmp_index = i;
637           else
638             unicode_full_index = i;
639         }
640       else if (platformID == 3)
641         {
642           if (encodingID == 1)
643             unicode_bmp_index = i;
644           else if (encodingID == 10)
645             unicode_full_index = i;
646         }
647     }
648   cmap->table_index = unicode_full_index;
649
650   for (i = 0; i < cmap->numTables; i++)
651     {
652       unsigned format;
653
654       SEEK_STREAM (stream, cmap->EncodingRecord[i].offset);
655       READ_USHORT (stream, format);
656       cmap->EncodingRecord[i].subtable.format = format;
657       if (format == 14)
658         {
659           READ_ULONG (stream, cmap->EncodingRecord[i].subtable.length);     
660           cmap->EncodingRecord[i].subtable.language = 0;
661         }
662       else
663         {
664           READ_USHORT (stream, cmap->EncodingRecord[i].subtable.length);
665           if (format == 8 || format == 10 || format == 12)
666             {
667               READ_ULONG (stream, cmap->EncodingRecord[i].subtable.length);
668               READ_ULONG (stream, cmap->EncodingRecord[i].subtable.language);
669             }
670           else
671             {
672               READ_USHORT (stream, cmap->EncodingRecord[i].subtable.language);
673             }
674         }
675       switch (format)
676         {
677         case 0:
678           {
679             OTF_MALLOC (cmap->EncodingRecord[i].subtable.f.f0, 1,
680                         " (EncodingRecord)");
681             READ_BYTES (stream,
682                         cmap->EncodingRecord[i].subtable.f.f0->glyphIdArray,
683                         256);
684           }
685           break;
686
687         case 2:
688           {
689             OTF_EncodingSubtable2 *sub2;
690             int j, max_key;
691
692             OTF_MALLOC (sub2, 1, " (EncodingSubtable2)");
693             cmap->EncodingRecord[i].subtable.f.f2 = sub2;
694             for (j = 0, max_key = 0; j < 256; j++)
695               {
696                 READ_USHORT (stream, sub2->subHeaderKeys[j]);
697                 if (max_key < sub2->subHeaderKeys[j])
698                   max_key = sub2->subHeaderKeys[j];
699               }
700             max_key += 8;
701             sub2->subHeaderCount = max_key / 8;
702             OTF_MALLOC (sub2->subHeaders, max_key / 8, " (subHeaders)");
703             for (j = 0; j < sub2->subHeaderCount; j++)
704               {
705                 READ_USHORT (stream, sub2->subHeaders[j].firstCode);
706                 READ_USHORT (stream, sub2->subHeaders[j].entryCount);
707                 READ_SHORT (stream, sub2->subHeaders[j].idDelta);
708                 READ_USHORT (stream, sub2->subHeaders[j].idRangeOffset);
709                 /* Make it offset from sub2->glyphIndexArray.  */
710                 sub2->subHeaders[j].idRangeOffset -= max_key - (j * 8 + 6);
711               }
712             sub2->glyphIndexCount = (cmap->EncodingRecord[i].subtable.length
713                                      - 262 - max_key);
714             OTF_MALLOC (sub2->glyphIndexArray, sub2->glyphIndexCount,
715                         " (glyphIndexArray)");
716             READ_BYTES (stream, sub2->glyphIndexArray, sub2->glyphIndexCount);
717           }
718           break;
719
720         case 4:
721           {
722             OTF_EncodingSubtable4 *sub4;
723             int segCount;
724             int j;
725             unsigned dummy;
726
727             OTF_MALLOC (sub4, 1, " (EncodingSubtable4)");
728             cmap->EncodingRecord[i].subtable.f.f4 = sub4;
729             READ_USHORT (stream, sub4->segCountX2);
730             segCount = sub4->segCountX2 / 2;
731             READ_USHORT (stream, sub4->searchRange);
732             READ_USHORT (stream, sub4->entrySelector);
733             READ_USHORT (stream, sub4->rangeShift);
734             OTF_MALLOC (sub4->segments, segCount, " (segCount)");
735             for (j = 0; j < segCount; j++)
736               READ_USHORT (stream, sub4->segments[j].endCount);
737             READ_USHORT (stream, dummy);
738             for (j = 0; j < segCount; j++)
739               READ_USHORT (stream, sub4->segments[j].startCount);
740             for (j = 0; j < segCount; j++)
741               READ_SHORT (stream, sub4->segments[j].idDelta);
742             for (j = 0; j < segCount; j++)
743               {
744                 unsigned off;
745                 unsigned rest = 2 * (segCount - j);
746                 
747                 READ_USHORT (stream, off);
748                 if (off == 0)
749                   sub4->segments[j].idRangeOffset = 0xFFFF;
750                 else
751                   sub4->segments[j].idRangeOffset = (off - rest) / 2;
752               }
753             j = (cmap->EncodingRecord[i].subtable.length
754                  - (14 + 2 * (segCount * 4 + 1)));
755             sub4->GlyphCount = j / 2;
756             OTF_MALLOC (sub4->glyphIdArray, sub4->GlyphCount, " (GlyphCount)");
757             for (j = 0; j < sub4->GlyphCount; j++)
758               READ_USHORT (stream, sub4->glyphIdArray[j]);
759           }
760           break;
761
762         case 6:
763           {
764             OTF_EncodingSubtable6 *sub6;
765             int j;
766
767             OTF_MALLOC (sub6, 1, " (EncodingSubtable6)");
768             cmap->EncodingRecord[i].subtable.f.f6 = sub6;
769             READ_USHORT (stream, sub6->firstCode);
770             READ_USHORT (stream, sub6->entryCount);
771             OTF_MALLOC (sub6->glyphIdArray, sub6->entryCount, " (GlyphCount)");
772             for (j = 0; j < sub6->entryCount; j++)
773               READ_USHORT (stream, sub6->glyphIdArray[j]);
774           }
775           break;
776
777         case 8:
778           {
779             OTF_EncodingSubtable8 *sub8;
780             int j;
781
782             OTF_MALLOC (sub8, 1, " (EncodingSubtable8)");
783             cmap->EncodingRecord[i].subtable.f.f8 = sub8;
784             for (j = 0; j < 8192; j++)
785               READ_BYTES (stream, sub8->is32, 8192);
786             READ_ULONG (stream, sub8->nGroups);
787             OTF_MALLOC (sub8->Groups, sub8->nGroups, " (Groups)");
788             for (j = 0; j < sub8->nGroups; j++)
789               {
790                 READ_ULONG (stream, sub8->Groups[i].startCharCode);
791                 READ_ULONG (stream, sub8->Groups[i].endCharCode);
792                 READ_ULONG (stream, sub8->Groups[i].startGlyphID);
793               }
794           }
795           break;
796
797         case 10:
798           {
799             OTF_EncodingSubtable10 *sub10;
800             int j;
801
802             OTF_MALLOC (sub10, 1, " (EncodingSubtable10)");
803             cmap->EncodingRecord[i].subtable.f.f10 = sub10;
804             READ_ULONG (stream, sub10->startCharCode);
805             READ_ULONG (stream, sub10->numChars);
806             OTF_MALLOC (sub10->glyphs, sub10->numChars, " (GlyphCount)");
807             for (j = 0; j < sub10->numChars; j++)
808               READ_USHORT (stream, sub10->glyphs[j]);
809           }
810           break;
811
812         case 12:
813           {
814             OTF_EncodingSubtable12 *sub12;
815             int j;
816
817             OTF_MALLOC (sub12, 1, " (EncodingSubtable12)");
818             cmap->EncodingRecord[i].subtable.f.f12 = sub12;
819             READ_ULONG (stream, sub12->nGroups);
820             OTF_MALLOC (sub12->Groups, sub12->nGroups, " (Groups)");
821             for (j = 0; j < sub12->nGroups; j++)
822               {
823                 READ_ULONG (stream, sub12->Groups[j].startCharCode);
824                 READ_ULONG (stream, sub12->Groups[j].endCharCode);
825                 READ_ULONG (stream, sub12->Groups[j].startGlyphID);
826               }
827           }
828           break;
829
830         case 14:
831           {
832             cmap->EncodingRecord[i].subtable.f.f14
833               = read_cmap_uvs_table (otf, stream,
834                                      cmap->EncodingRecord[i].offset);
835             break;
836           }
837
838         default:
839           OTF_ERROR (OTF_ERROR_TABLE, " (invalid Subtable format)");
840         }
841     }
842
843   if (unicode_bmp_index >= 0)
844     {
845       OTF_EncodingRecord *rec = cmap->EncodingRecord + unicode_bmp_index;
846       OTF_GlyphID glyph_id, max_glyph_id = 0;
847
848       OTF_CALLOC (cmap->unicode_table, 0x10000, "");
849       switch (rec->subtable.format)
850         {
851         case 4:
852           {
853             OTF_EncodingSubtable4 *sub4 = rec->subtable.f.f4;
854             int segCount = sub4->segCountX2 / 2;
855
856             for (i = 0; i < segCount; i++)
857               {
858                 OTF_cmapSegment *seg = sub4->segments + i;
859                 int c;
860
861                 if (seg->idRangeOffset == 0xFFFF)
862                   for (c = seg->startCount; c <= seg->endCount; c++)
863                     {
864                       glyph_id = (c + seg->idDelta) % 0x10000;
865                       cmap->unicode_table[c] = glyph_id;
866                       if (glyph_id > max_glyph_id)
867                         max_glyph_id = glyph_id;
868                     }
869                 else
870                   for (c = seg->startCount; c <= seg->endCount && c != 0xFFFF;
871                        c++)
872                     {
873                       glyph_id = sub4->glyphIdArray[seg->idRangeOffset
874                                                     + (c - seg->startCount)];
875                       cmap->unicode_table[c] = glyph_id;
876                       if (glyph_id > max_glyph_id)
877                         max_glyph_id = glyph_id;
878                     }
879               }
880           }
881         }
882
883       OTF_CALLOC (cmap->decode_table, max_glyph_id + 1, "");
884       for (i = 0; i < 0x10000; i++)
885         if (cmap->unicode_table[i])
886           cmap->decode_table[cmap->unicode_table[i]] = i;
887       cmap->max_glyph_id = max_glyph_id;
888     }
889
890   *table->address = cmap;
891   return cmap;
892 }
893
894 \f
895 /*** (1-5) Structures common to GDEF, GSUB, and GPOS */
896
897 /* Read Glyph-IDs from STREAM.  Allocate memory for IDS, and store the
898    Glyph-IDs there.  If COUNT is negative, read the number of
899    Glyphs-IDs at first.  MINUS if nozero is how few the actual
900    Glyph-IDs are in STREAM than COUNT.  */
901
902 static int
903 read_glyph_ids (OTF *otf, OTF_Stream *stream, OTF_GlyphID **ids,
904                 int minus, int count)
905 {
906   char *errfmt = "GlyphID List%s";
907   int errret = -1;
908   int i;
909
910   if (count < 0)
911     READ_UINT16 (stream, count);
912   if (! count)
913     return 0;
914   OTF_MALLOC (*ids, count, "");
915   for (i = 0; i < count + minus; i++)
916     READ_GLYPHID (stream, (*ids)[i]);
917   return count;
918 }
919
920 static unsigned
921 read_range_records (OTF *otf, OTF_Stream *stream, OTF_RangeRecord **record)
922 {
923   char *errfmt = "RangeRecord%s";
924   unsigned errret = 0;
925   unsigned count;
926   int i;
927
928   READ_UINT16 (stream, count);
929   if (! count)
930     return 0;
931   OTF_MALLOC (*record, count, "");
932   for (i = 0; i < count; i++)
933     {
934       READ_GLYPHID (stream, (*record)[i].Start);
935       READ_GLYPHID (stream, (*record)[i].End);
936       READ_UINT16 (stream, (*record)[i].StartCoverageIndex);
937     }
938   return count;
939 }
940
941
942 static int
943 read_coverage (OTF *otf, OTF_Stream *stream, long offset,
944                OTF_Coverage *coverage)
945 {
946   char *errfmt = "Coverage%s";
947   int errret = -1;
948   OTF_StreamState state;
949   int count;
950
951   READ_OFFSET (stream, coverage->offset);
952   SAVE_STREAM (stream, state);
953   SEEK_STREAM (stream, offset + coverage->offset);
954   READ_UINT16 (stream, coverage->CoverageFormat);
955   if (coverage->CoverageFormat == 1)
956     count = read_glyph_ids (otf, stream, &coverage->table.GlyphArray, 0, -1);
957   else if (coverage->CoverageFormat == 2)
958     count = read_range_records (otf, stream, &coverage->table.RangeRecord);
959   else
960     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid Format)");
961   if (count < 0)
962     return -1;
963   coverage->Count = (unsigned) count;
964   RESTORE_STREAM (stream, state);
965   return 0;
966 }
967
968 /* Read list of Coverages from STREAM.  Allocate memory for COVERAGE,
969    and store the Coverages there.  If COUNT is negative, read the
970    number of Coverages at first.  */
971
972 static int
973 read_coverage_list (OTF *otf, OTF_Stream *stream, long offset,
974                     OTF_Coverage **coverage, int count)
975 {
976   char *errfmt = "Coverage List%s";
977   int errret = -1;
978   int i;
979
980   if (count < 0)
981     READ_UINT16 (stream, count);
982   if (! count)
983     return 0;
984   OTF_MALLOC (*coverage, count, "");
985   for (i = 0; i < count; i++)
986     if (read_coverage (otf, stream, offset, (*coverage) + i) < 0)
987       return -1;
988   return count;
989 }
990
991
992 static int
993 read_class_def_without_offset (OTF *otf, OTF_Stream *stream,
994                                OTF_ClassDef *class)
995 {
996   char *errfmt = "ClassDef%s";
997   int errret = -1;
998
999   SEEK_STREAM (stream, class->offset);
1000   READ_UINT16 (stream, class->ClassFormat);
1001   if (class->ClassFormat == 1)
1002     {
1003       READ_GLYPHID (stream, class->f.f1.StartGlyph);
1004       class->f.f1.GlyphCount
1005         = (read_glyph_ids
1006            (otf, stream, (OTF_GlyphID **) &class->f.f1.ClassValueArray, 0, -1));
1007       if (! class->f.f1.GlyphCount)
1008         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1009     }
1010   else if (class->ClassFormat == 2)
1011     {
1012       class->f.f2.ClassRangeCount
1013         = (read_range_records
1014            (otf, stream, (OTF_RangeRecord **) &class->f.f2.ClassRangeRecord));
1015       if (! class->f.f2.ClassRangeCount)
1016         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1017     }
1018   else
1019     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
1020   return 0;
1021 }
1022
1023
1024 static int
1025 read_class_def (OTF *otf, OTF_Stream *stream, long offset, OTF_ClassDef *class)
1026 {
1027   char *errfmt = "ClassDef%s";
1028   int errret = -1;
1029   OTF_StreamState state;
1030
1031   READ_OFFSET (stream, class->offset);
1032   if (! class->offset)
1033     return 0;
1034   SAVE_STREAM (stream, state);
1035   SEEK_STREAM (stream, offset + class->offset);
1036   READ_UINT16 (stream, class->ClassFormat);
1037   if (class->ClassFormat == 1)
1038     {
1039       READ_GLYPHID (stream, class->f.f1.StartGlyph);
1040       class->f.f1.GlyphCount
1041         = read_glyph_ids (otf, stream,
1042                           (OTF_GlyphID **) &class->f.f1.ClassValueArray,
1043                           0, -1);
1044       if (! class->f.f1.GlyphCount)
1045         return -1;
1046     }
1047   else if (class->ClassFormat == 2)
1048     {
1049       class->f.f2.ClassRangeCount
1050         = read_range_records (otf, stream,
1051                               (OTF_RangeRecord **)
1052                               &class->f.f2.ClassRangeRecord);
1053       if (! class->f.f2.ClassRangeCount)
1054         return -1;
1055     }
1056   else
1057     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
1058
1059   RESTORE_STREAM (stream, state);
1060   return 0;
1061 }
1062
1063
1064 static int
1065 read_device_table (OTF *otf, OTF_Stream *stream, long offset,
1066                    OTF_DeviceTable *table)
1067 {
1068   char *errfmt = "Device Table%s";
1069   int errret = -1;
1070
1071   int num, i;
1072   unsigned val;
1073   struct {
1074     int int2 : 2;
1075     int int4 : 4;
1076     int int8 : 8;
1077   } intval;
1078
1079   SEEK_STREAM (stream, offset + table->offset);
1080   READ_UINT16 (stream, table->StartSize);
1081   READ_UINT16 (stream, table->EndSize);
1082   READ_UINT16 (stream, table->DeltaFormat);
1083   num = table->EndSize - table->StartSize + 1;
1084   if (num > 0 && table->DeltaFormat >= 1 && table->DeltaFormat <= 3)
1085     {
1086       OTF_MALLOC (table->DeltaValue, num, "");
1087
1088       if (table->DeltaFormat == 1)
1089         for (i = 0; i < num; i++)
1090           {
1091             if ((i % 8) == 0)
1092               READ_UINT16 (stream, val);
1093             intval.int2 = (val >> (14 - (i % 8) * 2)) & 0x03;
1094             table->DeltaValue[i] = intval.int2;
1095           }
1096       else if (table->DeltaFormat == 2)
1097         for (i = 0; i < num; i++)
1098           {
1099             if ((i % 4) == 0)
1100               READ_UINT16 (stream, val);
1101             intval.int4 = (val >> (12 - (i % 4) * 4)) & 0x0F;
1102             table->DeltaValue[i] = intval.int4;
1103           }
1104       else                              /* (table->DeltaFormat == 3) */
1105         for (i = 0; i < num; i++)
1106           {
1107             if ((i % 2) == 0)
1108               {
1109                 READ_UINT16 (stream, val);
1110                 intval.int8 = val >> 8;
1111                 table->DeltaValue[i] = intval.int8;
1112               }
1113             else
1114               {
1115                 intval.int8 = val >> 8;
1116                 table->DeltaValue[i] = intval.int8;
1117               }
1118           }
1119     }
1120   else
1121     {
1122       /* Invalid DeltaFormat but several fonts has such values (bug of
1123          fontforge?).  So accept it with NULL delta values.  */
1124       table->DeltaValue = NULL;
1125     }
1126   return 0;
1127 }
1128
1129 \f
1130 /*** (1-6) "GDEF" table */
1131
1132 static int
1133 read_attach_list (OTF *otf, OTF_Stream *stream, long offset,
1134                   OTF_AttachList *list)
1135 {
1136   char *errfmt = "AttachList%s";
1137   int errret = -1;
1138   int i, j;
1139
1140   if (read_coverage (otf, stream, offset, &list->Coverage) < 0)
1141     return -1;
1142   READ_UINT16 (stream, list->GlyphCount);
1143   OTF_MALLOC (list->AttachPoint, list->GlyphCount, "");
1144   for (i = 0; i < list->GlyphCount; i++)
1145     READ_OFFSET (stream, list->AttachPoint[i].offset);
1146   for (i = 0; i < list->GlyphCount; i++)
1147     {
1148       int count;
1149
1150       SEEK_STREAM (stream, offset + list->AttachPoint[i].offset);
1151       READ_UINT16 (stream, count);
1152       list->AttachPoint[i].PointCount = count;
1153       OTF_MALLOC (list->AttachPoint[i].PointIndex, count, " (PointIndex)");
1154       for (j = 0; j < count; j++)
1155         READ_UINT16 (stream, list->AttachPoint[i].PointIndex[j]);
1156     }
1157   return 0;
1158 }
1159
1160 static int
1161 read_caret_value (OTF *otf, OTF_Stream *stream, long offset,
1162                   OTF_CaretValue *caret)
1163 {
1164   char *errfmt = "CaretValue%s";
1165   int errret = -1;
1166
1167   SEEK_STREAM (stream, offset + caret->offset);
1168   READ_UINT16 (stream, caret->CaretValueFormat);
1169   if (caret->CaretValueFormat == 1)
1170     READ_INT16 (stream, caret->f.f1.Coordinate);
1171   else if (caret->CaretValueFormat == 2)
1172     READ_UINT16 (stream, caret->f.f2.CaretValuePoint);
1173   else if (caret->CaretValueFormat == 3)
1174     {
1175       READ_INT16 (stream, caret->f.f3.Coordinate);
1176       if (read_device_table (otf, stream, offset + caret->offset,
1177                              &caret->f.f3.DeviceTable) < 0)
1178         return -1;
1179     }
1180   else
1181     OTF_ERROR (OTF_ERROR_TABLE, " (Invalid format)");
1182   return 0;
1183 }
1184
1185 static int
1186 read_lig_caret_list (OTF *otf, OTF_Stream *stream, long offset,
1187                      OTF_LigCaretList *list)
1188 {
1189   char *errfmt = "LigCaretList%s";
1190   int errret = -1;
1191   int i, j;
1192
1193   if (read_coverage (otf, stream, offset, &list->Coverage) < 0)
1194     return -1;
1195   READ_UINT16 (stream, list->LigGlyphCount);
1196   OTF_MALLOC (list->LigGlyph, list->LigGlyphCount, "");
1197   for (i = 0; i < list->LigGlyphCount; i++)
1198     READ_OFFSET (stream, list->LigGlyph[i].offset);
1199   for (i = 0; i < list->LigGlyphCount; i++)
1200     {
1201       int count;
1202
1203       SEEK_STREAM (stream, offset + list->LigGlyph[i].offset);
1204       READ_UINT16 (stream, count);
1205       list->LigGlyph[i].CaretCount = count;
1206       OTF_MALLOC (list->LigGlyph[i].CaretValue, count, " (CaretValue)");
1207       for (j = 0; j < count; j++)
1208         READ_OFFSET (stream, list->LigGlyph[i].CaretValue[j].offset);
1209       for (j = 0; j < count; j++)
1210         if (read_caret_value (otf, stream, offset + list->LigGlyph[i].offset,
1211                               &list->LigGlyph[i].CaretValue[j]) < 0)
1212           return -1;
1213     }
1214   return 0;
1215 }
1216
1217 static int
1218 read_gdef_header (OTF_Stream *stream, OTF_GDEFHeader *header)
1219 {
1220   int errret = -1;
1221
1222   READ_FIXED (stream, header->Version);
1223   READ_OFFSET (stream, header->GlyphClassDef);
1224   READ_OFFSET (stream, header->AttachList);
1225   READ_OFFSET (stream, header->LigCaretList);
1226   READ_OFFSET (stream, header->MarkAttachClassDef);
1227   return 0;
1228 }
1229
1230 static void *
1231 read_gdef_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
1232 {
1233   OTF_Stream *stream = table->stream;
1234   char *errfmt = "GDEF%s";
1235   void *errret = NULL;
1236   OTF_GDEF *gdef;
1237
1238   OTF_CALLOC (gdef, 1, "");
1239   if (stream->buf)
1240     {
1241       read_gdef_header (stream, (OTF_GDEFHeader *) &gdef->header);
1242       if (gdef->header.GlyphClassDef)
1243         {
1244           gdef->glyph_class_def.offset = gdef->header.GlyphClassDef;
1245           read_class_def_without_offset (otf, stream,
1246                                          &gdef->glyph_class_def);
1247         }
1248       if (gdef->header.AttachList)
1249         read_attach_list (otf, stream, gdef->header.AttachList,
1250                           &gdef->attach_list);
1251       if (gdef->header.LigCaretList)
1252         read_lig_caret_list (otf, stream, gdef->header.LigCaretList,
1253                              &gdef->lig_caret_list);
1254       if (gdef->header.MarkAttachClassDef)
1255         {
1256           gdef->mark_attach_class_def.offset = gdef->header.MarkAttachClassDef;
1257           read_class_def_without_offset (otf, stream,
1258                                          &gdef->mark_attach_class_def);
1259         }
1260     }
1261
1262   *table->address = gdef;
1263   return gdef;
1264 }
1265
1266 \f
1267 /*** (1-7) Structures for ScriptList, FeatureList, and LookupList */
1268
1269 static int
1270 read_script_list (OTF *otf, OTF_Stream *stream, long offset,
1271                   OTF_ScriptList *list)
1272 {
1273   char *errfmt = "Script List%s";
1274   int errret = -1;
1275   int i, j, k;
1276
1277   SEEK_STREAM (stream, offset);
1278   READ_USHORT (stream, list->ScriptCount);
1279   OTF_CALLOC (list->Script, list->ScriptCount, "");
1280
1281   for (i = 0; i < list->ScriptCount; i++)
1282     {
1283       READ_TAG (stream, list->Script[i].ScriptTag);
1284       READ_OFFSET (stream, list->Script[i].offset);
1285     }
1286   for (i = 0;  i < list->ScriptCount; i++)
1287     {
1288       OTF_Script *script = list->Script + i;
1289       long script_offset = offset + script->offset;
1290
1291       SEEK_STREAM (stream, script_offset);
1292       READ_OFFSET (stream, script->DefaultLangSysOffset);
1293       READ_USHORT (stream, script->LangSysCount);
1294       OTF_MALLOC (script->LangSysRecord, script->LangSysCount, " (LangSys)");
1295       OTF_CALLOC (script->LangSys, script->LangSysCount, " (LangSys)");
1296       for (j = 0; j < script->LangSysCount; j++)
1297         {
1298           READ_TAG (stream, script->LangSysRecord[j].LangSysTag);
1299           READ_OFFSET (stream, script->LangSysRecord[j].LangSys);
1300         }
1301
1302       if (script->DefaultLangSysOffset)
1303         {
1304           OTF_LangSys *langsys = &script->DefaultLangSys;
1305
1306           SEEK_STREAM (stream, script_offset + script->DefaultLangSysOffset);
1307           READ_OFFSET (stream, langsys->LookupOrder);
1308           READ_USHORT (stream, langsys->ReqFeatureIndex);
1309           READ_USHORT (stream, langsys->FeatureCount);
1310           OTF_MALLOC (langsys->FeatureIndex, langsys->FeatureCount,
1311                       " (FeatureIndex)");
1312           for (k = 0; k < langsys->FeatureCount; k++)
1313             READ_USHORT (stream, langsys->FeatureIndex[k]);
1314         }
1315
1316       for (j = 0; j < script->LangSysCount; j++)
1317         {
1318           OTF_LangSys *langsys = script->LangSys + j;
1319
1320           SEEK_STREAM (stream,
1321                        script_offset + script->LangSysRecord[j].LangSys);
1322           READ_OFFSET (stream, langsys->LookupOrder);
1323           READ_USHORT (stream, langsys->ReqFeatureIndex);
1324           READ_USHORT (stream, langsys->FeatureCount);
1325           OTF_MALLOC (langsys->FeatureIndex, langsys->FeatureCount,
1326                       " (FeatureIndex)");
1327           for (k = 0; k < langsys->FeatureCount; k++)
1328             READ_USHORT (stream, langsys->FeatureIndex[k]);
1329         }
1330     }
1331
1332   return 0;
1333 }
1334
1335 static int
1336 read_feature_list (OTF *otf, OTF_Stream *stream, long offset,
1337                    OTF_FeatureList *list)
1338 {
1339   char *errfmt = "Feature List%s";
1340   int errret = -1;
1341   int i, j;
1342
1343   SEEK_STREAM (stream, offset);
1344   READ_UINT16 (stream, list->FeatureCount);
1345   OTF_CALLOC (list->Feature, list->FeatureCount, "");
1346   for (i = 0; i < list->FeatureCount; i++)
1347     {
1348       READ_TAG (stream, list->Feature[i].FeatureTag);
1349       READ_OFFSET (stream, list->Feature[i].offset);
1350     }
1351   for (i = 0; i < list->FeatureCount; i++)
1352     {
1353       OTF_Feature *feature = list->Feature + i;
1354
1355       SEEK_STREAM (stream, offset + feature->offset);
1356       READ_OFFSET (stream, feature->FeatureParams);
1357       READ_UINT16 (stream, feature->LookupCount);
1358       OTF_MALLOC (feature->LookupListIndex, feature->LookupCount,
1359                   " (LookupListIndex)");
1360       for (j = 0; j < feature->LookupCount; j++)
1361         READ_UINT16 (stream, feature->LookupListIndex[j]);
1362     }
1363
1364   return 0;
1365 }
1366
1367 static int read_lookup_subtable_gsub (OTF *otf, OTF_Stream *stream,
1368                                       long offset, unsigned type,
1369                                       OTF_LookupSubTableGSUB *subtable);
1370 static int read_lookup_subtable_gpos (OTF *otf, OTF_Stream *stream,
1371                                       long offset, unsigned type,
1372                                       OTF_LookupSubTableGPOS *subtable);
1373
1374 static int
1375 read_lookup_list (OTF *otf, OTF_Stream *stream, long offset,
1376                   OTF_LookupList *list, int gsubp)
1377 {
1378   char *errfmt = "Lookup List%s";
1379   int errret = -1;
1380   int i, j;
1381
1382   SEEK_STREAM (stream, offset);
1383   READ_UINT16 (stream, list->LookupCount);
1384   OTF_CALLOC (list->Lookup, list->LookupCount, "");
1385
1386   for (i = 0; i < list->LookupCount; i++)
1387     READ_OFFSET (stream, list->Lookup[i].offset);
1388   for (i = 0; i < list->LookupCount; i++)
1389     {
1390       OTF_Lookup *lookup = list->Lookup + i;
1391
1392       SEEK_STREAM (stream, offset + lookup->offset);
1393       READ_UINT16 (stream, lookup->LookupType);
1394       READ_UINT16 (stream, lookup->LookupFlag);
1395       READ_UINT16 (stream, lookup->SubTableCount);
1396       OTF_MALLOC (lookup->SubTableOffset, lookup->SubTableCount,
1397                   " (SubTableOffset)");
1398       if (gsubp)
1399         OTF_CALLOC (lookup->SubTable.gsub, lookup->SubTableCount,
1400                     " (SubTable)");
1401       else
1402         OTF_CALLOC (lookup->SubTable.gpos, lookup->SubTableCount,
1403                     " (SubTable)");
1404       for (j = 0; j < lookup->SubTableCount; j++)
1405         READ_OFFSET (stream, lookup->SubTableOffset[j]);
1406       for (j = 0; j < lookup->SubTableCount; j++)
1407         {
1408           long this_offset
1409             = offset + lookup->offset + lookup->SubTableOffset[j];
1410
1411           if (gsubp
1412               ? read_lookup_subtable_gsub (otf, stream, this_offset,
1413                                            lookup->LookupType,
1414                                            lookup->SubTable.gsub + j) < 0
1415               : read_lookup_subtable_gpos (otf, stream, this_offset,
1416                                            lookup->LookupType,
1417                                            lookup->SubTable.gpos + j) < 0)
1418             return errret;
1419         }
1420     }
1421
1422   return 0;
1423 }
1424
1425 \f
1426 /*** (1-8) Structures common to GSUB and GPOS */
1427
1428 static unsigned
1429 read_lookup_record_list (OTF *otf, OTF_Stream *stream,
1430                          OTF_LookupRecord **record, int count)
1431 {
1432   char *errfmt = "LookupRecord%s";
1433   unsigned errret = 0;
1434   int i;
1435
1436   if (count < 0)
1437     READ_UINT16 (stream, count);
1438   if (! count)
1439     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1440   OTF_MALLOC (*record, count, "");
1441   for (i = 0; i < count; i++)
1442     {
1443       READ_UINT16 (stream, (*record)[i].SequenceIndex);
1444       READ_UINT16 (stream, (*record)[i].LookupListIndex);
1445     }
1446   return count;
1447 }
1448
1449 static unsigned
1450 read_rule_list (OTF *otf, OTF_Stream *stream, long offset, OTF_Rule **rule)
1451 {
1452   char *errfmt = "List of Rule%s";
1453   unsigned errret = 0;
1454   OTF_StreamState state;
1455   unsigned count;
1456   int i;
1457
1458   READ_UINT16 (stream, count);
1459   if (! count)
1460     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1461   OTF_MALLOC (*rule, count, "");
1462   for (i = 0; i < count; i++)
1463     {
1464       READ_OFFSET (stream, (*rule)[i].offset);
1465       if (! (*rule)[i].offset)
1466         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1467     }
1468   SAVE_STREAM (stream, state);
1469   for (i = 0; i < count; i++)
1470     {
1471       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1472       READ_UINT16 (stream, (*rule)[i].GlyphCount);
1473       if ((*rule)[i].GlyphCount == 0)
1474         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1475       READ_UINT16 (stream, (*rule)[i].LookupCount);
1476       if (read_glyph_ids (otf, stream, &(*rule)[i].Input, 0,
1477                           (*rule)[i].GlyphCount) < 0)
1478         return errret;
1479       if (read_lookup_record_list (otf, stream, &(*rule)[i].LookupRecord,
1480                                    (*rule)[i].LookupCount) == 0)
1481         return errret;
1482     }
1483   RESTORE_STREAM (stream, state);
1484   return count;
1485 }
1486
1487
1488 static unsigned
1489 read_rule_set_list (OTF *otf, OTF_Stream *stream, long offset,
1490                     OTF_RuleSet **set)
1491 {
1492   char *errfmt = "List of RuleSet%s";
1493   unsigned errret = 0;
1494   OTF_StreamState state;
1495   unsigned count;
1496   int i;
1497
1498   READ_UINT16 (stream, count);
1499   if (! count)
1500     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1501   OTF_MALLOC (*set, count, "");
1502   for (i = 0; i < count; i++)
1503     {
1504       READ_OFFSET (stream, (*set)[i].offset);
1505       if (! (*set)[i].offset)
1506         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1507     }
1508   SAVE_STREAM (stream, state);
1509   for (i = 0; i < count; i++)
1510     {
1511       SEEK_STREAM (stream, offset + (*set)[i].offset);
1512       (*set)[i].RuleCount
1513         = read_rule_list (otf, stream, offset + (*set)[i].offset,
1514                           &(*set)[i].Rule);
1515       if (! (*set)[i].RuleCount)
1516         return errret;
1517     }
1518   RESTORE_STREAM (stream, state);
1519   return count;
1520 }
1521
1522 static unsigned
1523 read_class_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1524                       OTF_ClassRule **rule)
1525 {
1526   char *errfmt = "ClassRule%s";
1527   unsigned errret = 0;
1528   OTF_StreamState state;
1529   unsigned count;
1530   int i;
1531
1532   READ_UINT16 (stream, count);
1533   if (! count)
1534     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1535   OTF_MALLOC (*rule, count, "");
1536   for (i = 0; i < count; i++)
1537     {
1538       READ_OFFSET (stream, (*rule)[i].offset);
1539       if (! (*rule)[i].offset)
1540         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1541     }
1542   SAVE_STREAM (stream, state);
1543   for (i = 0; i < count; i++)
1544     {
1545       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1546       READ_USHORT (stream, (*rule)[i].GlyphCount);
1547       if (! (*rule)[i].GlyphCount)
1548         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1549       READ_USHORT (stream, (*rule)[i].LookupCount);
1550       if (read_glyph_ids (otf, stream, (OTF_GlyphID **) &(*rule)[i].Class,
1551                           0, (*rule)[i].GlyphCount - 1) < 0)
1552         return errret;
1553       if (read_lookup_record_list (otf, stream, &(*rule)[i].LookupRecord,
1554                                    (*rule)[i].LookupCount) == 0)
1555         return errret;
1556     }
1557   RESTORE_STREAM (stream, state);
1558   return count;
1559 }
1560
1561 static unsigned
1562 read_class_set_list (OTF *otf, OTF_Stream *stream, long offset,
1563                      OTF_ClassSet **set)
1564 {
1565   char *errfmt = "ClassSet%s";
1566   unsigned errret = 0;
1567   OTF_StreamState state;
1568   unsigned count;
1569   int i;
1570
1571   READ_UINT16 (stream, count);
1572   if (! count)
1573     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1574   OTF_CALLOC (*set, count, "");
1575   for (i = 0; i < count; i++)
1576     /* Offset can be zero.  */
1577     READ_OFFSET (stream, (*set)[i].offset);
1578   SAVE_STREAM (stream, state);
1579   for (i = 0; i < count; i++)
1580     if ((*set)[i].offset)
1581       {
1582         SEEK_STREAM (stream, offset + (*set)[i].offset);
1583         (*set)[i].ClassRuleCnt
1584           = read_class_rule_list (otf, stream, offset + (*set)[i].offset,
1585                                   &(*set)[i].ClassRule);
1586         if (! (*set)[i].ClassRuleCnt)
1587           return errret;
1588       }
1589   RESTORE_STREAM (stream, state);
1590   return count;
1591 }
1592
1593 static unsigned
1594 read_chain_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1595                       OTF_ChainRule **rule)
1596 {
1597   char *errfmt = "ChainRule%s";
1598   unsigned errret = 0;
1599   unsigned count;
1600   int i;
1601
1602   READ_UINT16 (stream, count);
1603   if (! count)
1604     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1605   OTF_MALLOC (*rule, count, "");
1606   for (i = 0; i < count; i++)
1607     READ_OFFSET (stream, (*rule)[i].offset);
1608   for (i = 0; i < count; i++)
1609     {
1610       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1611       (*rule)[i].BacktrackGlyphCount
1612         = read_glyph_ids (otf, stream, &(*rule)[i].Backtrack, 0, -1);
1613       (*rule)[i].InputGlyphCount
1614         = read_glyph_ids (otf, stream, &(*rule)[i].Input, -1, -1);
1615       if (! (*rule)[i].InputGlyphCount)
1616         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1617       (*rule)[i].LookaheadGlyphCount
1618         = read_glyph_ids (otf, stream, &(*rule)[i].LookAhead, 0, -1);
1619       (*rule)[i].LookupCount
1620         = read_lookup_record_list (otf, stream,
1621                                    &(*rule)[i].LookupRecord, -1);
1622       if (! (*rule)[i].LookupCount)
1623         return errret;
1624     }
1625   return count;
1626 }
1627
1628
1629 static unsigned
1630 read_chain_rule_set_list (OTF *otf, OTF_Stream *stream, long offset,
1631                      OTF_ChainRuleSet **set)
1632 {
1633   char *errfmt = "ChainRuleSet%s";
1634   unsigned errret = 0;
1635   OTF_StreamState state;
1636   unsigned count;
1637   int i;
1638
1639   READ_UINT16 (stream, count);
1640   if (! count)
1641     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1642   OTF_MALLOC (*set, count, "");
1643   for (i = 0; i < count; i++)
1644     {
1645       READ_OFFSET (stream, (*set)[i].offset);
1646       if (! (*set)[i].offset)
1647         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1648     }
1649   SAVE_STREAM (stream, state);
1650   for (i = 0; i < count; i++)
1651     {
1652       SEEK_STREAM (stream, offset + (*set)[i].offset);
1653       (*set)[i].ChainRuleCount
1654         = read_chain_rule_list (otf, stream, offset + (*set)[i].offset,
1655                                 &(*set)[i].ChainRule);
1656       if (! (*set)[i].ChainRuleCount)
1657         return errret;
1658     }
1659   RESTORE_STREAM (stream, state);
1660   return count;
1661 }
1662
1663 static unsigned
1664 read_chain_class_rule_list (OTF *otf, OTF_Stream *stream, long offset,
1665                             OTF_ChainClassRule **rule)
1666 {
1667   char *errfmt = "ChainClassRule%s";
1668   unsigned errret = 0;
1669   unsigned count;
1670   int i;
1671
1672   READ_UINT16 (stream, count);
1673   if (! count)
1674     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1675   OTF_MALLOC (*rule, count, "");
1676   for (i = 0; i < count; i++)
1677     {
1678       READ_OFFSET (stream, (*rule)[i].offset);
1679       if (! (*rule)[i].offset)
1680         OTF_ERROR (OTF_ERROR_TABLE, " (zero offset)");
1681     }
1682   for (i = 0; i < count; i++)
1683     {
1684       SEEK_STREAM (stream, offset + (*rule)[i].offset);
1685       (*rule)[i].BacktrackGlyphCount
1686         = read_glyph_ids (otf, stream,
1687                           (OTF_GlyphID **) &(*rule)[i].Backtrack, 0, -1);
1688       (*rule)[i].InputGlyphCount
1689         = read_glyph_ids (otf, stream,
1690                           (OTF_GlyphID **) &(*rule)[i].Input, -1, -1);
1691       if (! (*rule)[i].InputGlyphCount)
1692         OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1693       (*rule)[i].LookaheadGlyphCount
1694         = read_glyph_ids (otf, stream,
1695                           (OTF_GlyphID **) &(*rule)[i].LookAhead, 0, -1);
1696       (*rule)[i].LookupCount
1697         = read_lookup_record_list (otf, stream,
1698                                    &(*rule)[i].LookupRecord, -1);
1699       if (! (*rule)[i].LookupCount)
1700         return errret;
1701     }
1702   return count;
1703 }
1704
1705 static unsigned
1706 read_chain_class_set_list (OTF *otf, OTF_Stream *stream, long offset,
1707                            OTF_ChainClassSet **set)
1708 {
1709   char *errfmt = "ChainClassSet%s";
1710   unsigned errret = 0;
1711   OTF_StreamState state;
1712   unsigned count;
1713   int i;
1714
1715   READ_UINT16 (stream, count);
1716   if (! count)
1717     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1718   OTF_MALLOC (*set, count, "");
1719   for (i = 0; i < count; i++)
1720     /* Offset may be zero.  */
1721     READ_OFFSET (stream, (*set)[i].offset);
1722   SAVE_STREAM (stream, state);
1723   for (i = 0; i < count; i++)
1724     if ((*set)[i].offset)
1725       {
1726         SEEK_STREAM (stream, offset + (*set)[i].offset);
1727         (*set)[i].ChainClassRuleCnt
1728           = read_chain_class_rule_list (otf, stream, offset + (*set)[i].offset,
1729                                         &(*set)[i].ChainClassRule);
1730         if (! (*set)[i].ChainClassRuleCnt)
1731           return errret;
1732       }
1733   RESTORE_STREAM (stream, state);
1734   return count;
1735 }
1736
1737 static int
1738 read_context1 (OTF *otf, OTF_Stream *stream, long offset,
1739                OTF_Coverage *coverage,OTF_Context1 *context1)
1740 {
1741   if (read_coverage (otf, stream, offset, coverage) < 0)
1742     return -1;
1743   context1->RuleSetCount
1744     = read_rule_set_list (otf, stream, offset, &context1->RuleSet);
1745   if (! context1->RuleSetCount)
1746     return -1;
1747   return 0;
1748 }
1749
1750 static int
1751 read_context2 (OTF *otf, OTF_Stream *stream, long offset,
1752                OTF_Coverage *coverage,OTF_Context2 *context2)
1753 {
1754   if (read_coverage (otf, stream, offset, coverage) < 0
1755       || read_class_def (otf, stream, offset, &context2->ClassDef) < 0)
1756     return -1;
1757   context2->ClassSetCnt
1758     = read_class_set_list (otf, stream, offset, &context2->ClassSet);
1759   if (! context2->ClassSetCnt)
1760     return -1;
1761   return 0;
1762 }
1763
1764 static int
1765 read_context3 (OTF *otf, OTF_Stream *stream, long offset,
1766                OTF_Coverage *coverage,OTF_Context3 *context3)
1767 {
1768   char *errfmt = "Context1%s";
1769   int errret = -1;
1770
1771   READ_USHORT (stream, context3->GlyphCount);
1772   if (context3->GlyphCount < 0)
1773     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1774   READ_USHORT (stream, context3->LookupCount);
1775   if (read_coverage_list (otf, stream, offset, &context3->Coverage,
1776                           context3->GlyphCount) < 0)
1777     return errret;
1778   if (read_lookup_record_list (otf, stream, &context3->LookupRecord,
1779                                context3->LookupCount) < 0)
1780     return errret;
1781   return 0;
1782 }
1783
1784 static int
1785 read_chain_context1 (OTF *otf, OTF_Stream *stream, long offset,
1786                      OTF_Coverage *coverage, OTF_ChainContext1 *chain_context1)
1787 {
1788   if (read_coverage (otf, stream, offset, coverage) < 0)
1789     return -1;
1790   chain_context1->ChainRuleSetCount
1791     = read_chain_rule_set_list (otf, stream, offset,
1792                                 &chain_context1->ChainRuleSet);
1793   if (! chain_context1->ChainRuleSetCount)
1794     return -1;
1795   return 0;
1796 }
1797
1798 static int
1799 read_chain_context2 (OTF *otf, OTF_Stream *stream, long offset,
1800                      OTF_Coverage *coverage, OTF_ChainContext2 *chain_context2)
1801 {
1802   if (read_coverage (otf, stream, offset, coverage) < 0
1803       || read_class_def (otf, stream, offset,
1804                          &chain_context2->BacktrackClassDef) < 0
1805       || read_class_def (otf, stream, offset,
1806                          &chain_context2->InputClassDef) < 0
1807       || read_class_def (otf, stream, offset,
1808                          &chain_context2->LookaheadClassDef) < 0)
1809     return -1;
1810   chain_context2->ChainClassSetCnt
1811     = read_chain_class_set_list (otf, stream, offset,
1812                                  &chain_context2->ChainClassSet);
1813   if (! chain_context2->ChainClassSetCnt)
1814     return -1;
1815   return 0;
1816 }
1817
1818 static int
1819 read_chain_context3 (OTF *otf, OTF_Stream *stream, long offset,
1820                      OTF_Coverage *coverage, OTF_ChainContext3 *chain_context3)
1821 {
1822   int count;
1823
1824   count = read_coverage_list (otf, stream, offset,
1825                               &chain_context3->Backtrack, -1);
1826   if (count < 0)
1827     return -1;
1828   chain_context3->BacktrackGlyphCount = (unsigned) count;
1829   count = read_coverage_list (otf, stream, offset,
1830                               &chain_context3->Input, -1);
1831   if (count <= 0)
1832     return -1;
1833   chain_context3->InputGlyphCount = (unsigned) count;
1834   *coverage = chain_context3->Input[0];
1835   count = read_coverage_list (otf, stream, offset,
1836                               &chain_context3->LookAhead, -1);
1837   chain_context3->LookaheadGlyphCount = (unsigned) count;
1838   chain_context3->LookupCount
1839     = read_lookup_record_list (otf, stream,
1840                                &chain_context3->LookupRecord, -1);
1841   return 0;
1842 }
1843
1844 static void *
1845 read_gsub_gpos_table (OTF *otf, OTF_TableInfo *table, int gsubp,
1846                       enum OTF_ReaderFlag flag)
1847 {
1848   OTF_Stream *stream = table->stream;
1849   char *errfmt = gsubp ? "GSUB%s" : "GPOS%s";
1850   void *errret = NULL;
1851   OTF_GSUB_GPOS *gsub_gpos = *table->address;
1852
1853   if (gsub_gpos)
1854     SEEK_STREAM (stream, 10);
1855   else
1856     {
1857       SEEK_STREAM (stream, 0);
1858       OTF_CALLOC (gsub_gpos, 1, "");
1859       READ_FIXED (stream, gsub_gpos->Version);
1860       READ_OFFSET (stream, gsub_gpos->ScriptList.offset);
1861       READ_OFFSET (stream, gsub_gpos->FeatureList.offset);
1862       READ_OFFSET (stream, gsub_gpos->LookupList.offset);
1863       *table->address = gsub_gpos;
1864     }
1865
1866   if (! gsub_gpos->ScriptList.Script
1867       && read_script_list (otf, stream, gsub_gpos->ScriptList.offset,
1868                            &gsub_gpos->ScriptList) < 0)
1869     return NULL;
1870   if (flag != OTF_READ_SCRIPTS)
1871     {
1872       if (! gsub_gpos->FeatureList.Feature
1873           && read_feature_list (otf, stream, gsub_gpos->FeatureList.offset,
1874                                 &gsub_gpos->FeatureList) < 0)
1875         return NULL;
1876       if (flag != OTF_READ_FEATURES)
1877         {
1878           if (! gsub_gpos->LookupList.Lookup
1879               && read_lookup_list (otf, stream, gsub_gpos->LookupList.offset,
1880                                    &gsub_gpos->LookupList, gsubp) < 0)
1881             return NULL;
1882         }
1883     }
1884
1885   return gsub_gpos;
1886 }
1887
1888 \f
1889 /* (1-9) "GSUB" table */
1890
1891 static unsigned
1892 read_sequence (OTF *otf, OTF_Stream *stream, long offset, OTF_Sequence **seq)
1893 {
1894   char *errfmt = "Sequence%s";
1895   unsigned errret = 0;
1896   unsigned count;
1897   int i;
1898
1899   READ_UINT16 (stream, count);
1900   if (! count)
1901     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1902   OTF_MALLOC (*seq, count, "");
1903   for (i = 0; i < count; i++)
1904     READ_OFFSET (stream, (*seq)[i].offset);
1905   for (i = 0; i < count; i++)
1906     {
1907       SEEK_STREAM (stream, offset + (*seq)[i].offset);
1908       (*seq)[i].GlyphCount = read_glyph_ids (otf, stream,
1909                                              &(*seq)[i].Substitute, 0, -1);
1910       if (! (*seq)[i].GlyphCount)
1911         return 0;
1912     }
1913   return count;
1914 }
1915
1916 static int
1917 read_ligature (OTF *otf, OTF_Stream *stream, long offset,
1918                OTF_Ligature **ligature)
1919 {
1920   char *errfmt = "Ligature%s";
1921   int errret = -1;
1922   int count;
1923   int i;
1924
1925   READ_UINT16 (stream, count);
1926   if (! count)
1927     return 0;
1928   OTF_MALLOC (*ligature, count, "");
1929   for (i = 0; i < count; i++)
1930     READ_OFFSET (stream, (*ligature)[i].offset);
1931   for (i = 0; i < count; i++)
1932     {
1933       SEEK_STREAM (stream, offset + (*ligature)[i].offset);
1934       READ_GLYPHID (stream, (*ligature)[i].LigGlyph);
1935       (*ligature)[i].CompCount
1936         = read_glyph_ids (otf, stream, &(*ligature)[i].Component, -1, -1);
1937       if (! (*ligature)[i].CompCount)
1938         return -1;
1939     }
1940   return count;
1941 }
1942
1943 static unsigned
1944 read_ligature_set_list (OTF *otf, OTF_Stream *stream, long offset,
1945                         OTF_LigatureSet **ligset)
1946 {
1947   char *errfmt = "LigatureSet%s";
1948   int errret = 0;
1949   int count;
1950   int i;
1951
1952   READ_UINT16 (stream, count);
1953   if (! count)
1954     return errret;
1955   OTF_MALLOC (*ligset, count, "");
1956   for (i = 0; i < count; i++)
1957     READ_OFFSET (stream, (*ligset)[i].offset);
1958   for (i = 0; i < count; i++)
1959     {
1960       int lig_count;
1961
1962       SEEK_STREAM (stream, offset + (*ligset)[i].offset);
1963       lig_count = read_ligature (otf, stream, offset + (*ligset)[i].offset,
1964                                  &(*ligset)[i].Ligature);
1965       if (lig_count < 0)
1966         return errret;
1967       (*ligset)[i].LigatureCount = (unsigned) lig_count;
1968     }
1969   return count;
1970 }
1971
1972 static unsigned
1973 read_alternate_set_list (OTF *otf, OTF_Stream *stream, long offset,
1974                          OTF_AlternateSet **altset)
1975 {
1976   char *errfmt = "AlternateSet%s";
1977   int errret = 0;
1978   unsigned count;
1979   int i;
1980
1981   READ_UINT16 (stream, count);
1982   if (! count)
1983     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
1984   OTF_MALLOC (*altset, count, "");
1985   for (i = 0; i < count; i++)
1986     READ_OFFSET (stream, (*altset)[i].offset);
1987   for (i = 0; i < count; i++)
1988     {
1989       int alt_count;
1990
1991       SEEK_STREAM (stream, offset + (*altset)[i].offset);
1992       alt_count = read_glyph_ids (otf, stream, &(*altset)[i].Alternate, 0, -1);
1993       if (alt_count < 0)
1994         return errret;
1995       (*altset)[i].GlyphCount = (unsigned) alt_count;
1996     }
1997   return count;
1998 }
1999
2000 static int
2001 read_reverse_chain1 (OTF *otf, OTF_Stream *stream, long offset,
2002                      OTF_Coverage *coverage,
2003                      OTF_GSUB_ReverseChain1 *reverse_chain)
2004 {
2005   int count;
2006
2007   if (read_coverage (otf, stream, offset, coverage) < 0)
2008     return -1;
2009   count = read_coverage_list (otf, stream, offset,
2010                               &reverse_chain->Backtrack, -1);
2011   if (count < 0)
2012     return -1;
2013   reverse_chain->BacktrackGlyphCount = (unsigned) count;
2014   count = read_coverage_list (otf, stream, offset,
2015                               &reverse_chain->LookAhead, -1);
2016   if (count <= 0)
2017     return -1;
2018   reverse_chain->LookaheadGlyphCount = (unsigned) count;
2019   count = read_glyph_ids (otf, stream, &reverse_chain->Substitute, 0, -1);
2020   if (count <= 0)
2021     return -1;
2022   reverse_chain->GlyphCount = count;  
2023   return 0;
2024 }
2025
2026 static int
2027 read_lookup_subtable_gsub (OTF *otf, OTF_Stream *stream, long offset,
2028                            unsigned type, OTF_LookupSubTableGSUB *subtable)
2029 {
2030   char errfmt[256];
2031   int errret = -1;
2032
2033   SEEK_STREAM (stream, offset);
2034   READ_USHORT (stream, subtable->Format);
2035   sprintf (errfmt, "GSUB Lookup %d-%d%%s", type, subtable->Format);
2036   switch (type)
2037     {
2038     case 1:
2039       if (subtable->Format == 1)
2040         {
2041           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2042             return -1;
2043           READ_INT16 (stream, subtable->u.single1.DeltaGlyphID);
2044         }
2045       else if (subtable->Format == 2)
2046         {
2047           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2048             return -1;
2049           subtable->u.single2.GlyphCount
2050             = read_glyph_ids (otf, stream, &subtable->u.single2.Substitute,
2051                               0, -1);
2052           if (! subtable->u.single2.GlyphCount)
2053             return -1;
2054         }
2055       else
2056         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2057       break;
2058
2059     case 2:
2060       if (subtable->Format == 1)
2061         {
2062           read_coverage (otf, stream, offset, &subtable->Coverage);
2063           subtable->u.multiple1.SequenceCount
2064             = read_sequence (otf, stream, offset,
2065                              &subtable->u.multiple1.Sequence);
2066         }
2067       else
2068         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2069       break;
2070
2071     case 3:
2072       if (subtable->Format == 1)
2073         {
2074           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2075             return -1;
2076           subtable->u.alternate1.AlternateSetCount
2077             = read_alternate_set_list (otf, stream, offset,
2078                                        &subtable->u.alternate1.AlternateSet);
2079           if (! subtable->u.alternate1.AlternateSetCount)
2080             return -1;
2081         }
2082       else
2083         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2084       break;
2085
2086     case 4:
2087       if (subtable->Format == 1)
2088         {
2089           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2090             return -1;
2091           subtable->u.ligature1.LigSetCount
2092             = read_ligature_set_list (otf, stream, offset,
2093                                       &subtable->u.ligature1.LigatureSet);
2094           if (! subtable->u.ligature1.LigSetCount)
2095             return -1;
2096         }
2097       else
2098         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2099       break;
2100
2101     case 5:
2102       if (subtable->Format == 1)
2103         {
2104           if (read_context1 (otf, stream, offset, &subtable->Coverage,
2105                              &subtable->u.context1) < 0)
2106             return errret;
2107         }
2108       else if (subtable->Format == 2)
2109         {
2110           if (read_context2 (otf, stream, offset, &subtable->Coverage,
2111                              &subtable->u.context2) < 0)
2112             return errret;
2113         }
2114       else if (subtable->Format == 3)
2115         {
2116           if (read_context3 (otf, stream, offset, &subtable->Coverage,
2117                              &subtable->u.context3) < 0)
2118             return errret;
2119         }
2120       else
2121         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2122       break;
2123
2124     case 6:
2125       if (subtable->Format == 1)
2126         {
2127           if (read_chain_context1 (otf, stream, offset, &subtable->Coverage,
2128                                    &subtable->u.chain_context1) < 0)
2129             return errret;
2130         }
2131       else if (subtable->Format == 2)
2132         {
2133           if (read_chain_context2 (otf, stream, offset, &subtable->Coverage,
2134                                    &subtable->u.chain_context2) < 0)
2135             return errret;
2136         }
2137       else if (subtable->Format == 3)
2138         {
2139           if (read_chain_context3 (otf, stream, offset, &subtable->Coverage,
2140                                    &subtable->u.chain_context3) < 0)
2141             return errret;
2142         }
2143       else
2144         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2145       break;
2146
2147     case 7:
2148       if (subtable->Format == 1)
2149         {
2150           unsigned ex_type;
2151           long ex_offset;
2152           OTF_LookupSubTableGSUB *ex_subtable;
2153
2154           READ_USHORT (stream, ex_type);
2155           READ_ULONG (stream, ex_offset);
2156           OTF_CALLOC (ex_subtable, 1, " (SubTable)");
2157           if (read_lookup_subtable_gsub (otf, stream, offset + ex_offset,
2158                                          ex_type, ex_subtable) < 0)
2159             return errret;
2160           subtable->u.extension1.ExtensionLookupType = ex_type;
2161           subtable->u.extension1.ExtensionOffset = ex_offset;
2162           subtable->u.extension1.ExtensionSubtable = ex_subtable;
2163         }
2164       else
2165         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2166       break;
2167
2168     case 8:
2169       if (subtable->Format == 1)
2170         {
2171           if (read_reverse_chain1 (otf, stream, offset, &subtable->Coverage,
2172                                    &subtable->u.reverse_chain1) < 0)
2173             return errret;
2174         }
2175       else
2176         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2177       break;
2178
2179     default:
2180       OTF_ERROR (OTF_ERROR_TABLE, " (Invalid LookupType)");
2181     }
2182   return 0;
2183 }
2184
2185 static void *
2186 read_gsub_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
2187 {
2188   return read_gsub_gpos_table (otf, table, 1, flag);
2189 }
2190
2191 \f
2192 /* (1-10) "GPOS" table */
2193
2194 static int
2195 read_value_record (OTF *otf, OTF_Stream *stream, long offset,
2196                    enum OTF_ValueFormat bit, OTF_ValueRecord *value_record)
2197 {
2198   int errret = -1;
2199   OTF_StreamState state;
2200   int size, i;
2201
2202   memset (value_record, 0, sizeof (OTF_ValueRecord));
2203   if (! bit)
2204     return 0;
2205   for (i = 0, size = 0; i < 8; i++)
2206     if (bit & (1 << i))
2207       size += 2;
2208
2209   if (bit & OTF_XPlacement)
2210     READ_INT16 (stream, value_record->XPlacement);
2211   if (bit & OTF_YPlacement)
2212     READ_INT16 (stream, value_record->YPlacement);
2213   if (bit & OTF_XAdvance)
2214     READ_INT16 (stream, value_record->XAdvance);
2215   if (bit & OTF_YAdvance)
2216     READ_INT16 (stream, value_record->YAdvance);
2217   if (bit & OTF_XPlaDevice)
2218     READ_OFFSET (stream, value_record->XPlaDevice.offset);
2219   if (bit & OTF_YPlaDevice)
2220     READ_OFFSET (stream, value_record->YPlaDevice.offset);
2221   if (bit & OTF_XAdvDevice)
2222     READ_OFFSET (stream, value_record->XAdvDevice.offset);
2223   if (bit & OTF_YAdvDevice)
2224     READ_OFFSET (stream, value_record->YAdvDevice.offset);
2225   SAVE_STREAM (stream, state);
2226   if (value_record->XPlaDevice.offset)
2227     {
2228       if (read_device_table (otf, stream, offset, &value_record->XPlaDevice) < 0)
2229         return -1;
2230     }
2231   if (value_record->YPlaDevice.offset)
2232     {
2233       if (read_device_table (otf, stream, offset, &value_record->YPlaDevice) < 0)
2234         return -1;
2235     }
2236   if (value_record->XAdvDevice.offset)
2237     {
2238       if (read_device_table (otf, stream, offset, &value_record->XAdvDevice) < 0)
2239         return -1;
2240     }
2241   if (value_record->YAdvDevice.offset)
2242     {
2243       if (read_device_table (otf, stream, offset, &value_record->YAdvDevice) < 0)
2244         return -1;
2245     }
2246   RESTORE_STREAM (stream, state);
2247   return 0;
2248 }
2249
2250
2251 static int
2252 read_anchor (OTF *otf, OTF_Stream *stream, long offset, OTF_Anchor *anchor)
2253 {
2254   char *errfmt = "Anchor%s";
2255   int errret = -1;
2256
2257   SEEK_STREAM (stream, offset + anchor->offset);
2258   READ_UINT16 (stream, anchor->AnchorFormat);
2259   READ_INT16 (stream, anchor->XCoordinate);
2260   READ_INT16 (stream, anchor->YCoordinate);
2261   if (anchor->AnchorFormat == 1)
2262     ;
2263   else if (anchor->AnchorFormat == 2)
2264     {
2265       READ_UINT16 (stream, anchor->f.f1.AnchorPoint);
2266     }
2267   else if (anchor->AnchorFormat == 3)
2268     {
2269       READ_OFFSET (stream, anchor->f.f2.XDeviceTable.offset);
2270       READ_OFFSET (stream, anchor->f.f2.YDeviceTable.offset);
2271       if (anchor->f.f2.XDeviceTable.offset)
2272         {
2273           if (read_device_table (otf, stream, offset + anchor->offset,
2274                                  &anchor->f.f2.XDeviceTable) < 0)
2275             return -1;
2276         }
2277       if (anchor->f.f2.YDeviceTable.offset)
2278         {
2279           if (read_device_table (otf, stream, offset + anchor->offset,
2280                                  &anchor->f.f2.YDeviceTable) < 0)
2281             return -1;
2282         }
2283     }
2284   else
2285     OTF_ERROR (OTF_ERROR_TABLE, " (invalid format)");
2286
2287   return 0;
2288 }
2289
2290 static int
2291 read_mark_array (OTF *otf, OTF_Stream *stream, long offset,
2292                  OTF_MarkArray *array)
2293 {
2294   char *errfmt = "MarkArray%s";
2295   int errret = -1;
2296   OTF_StreamState state;
2297   int i;
2298
2299   READ_OFFSET (stream, array->offset);
2300   SAVE_STREAM (stream, state);
2301   SEEK_STREAM (stream, offset + array->offset);
2302   READ_UINT16 (stream, array->MarkCount);
2303   OTF_MALLOC (array->MarkRecord, array->MarkCount, "");
2304   for (i = 0; i < array->MarkCount; i++)
2305     {
2306       READ_UINT16 (stream, array->MarkRecord[i].Class);
2307       READ_OFFSET (stream, array->MarkRecord[i].MarkAnchor.offset);
2308     }
2309   for (i = 0; i < array->MarkCount; i++)
2310     if (read_anchor (otf, stream, offset + array->offset,
2311                      &array->MarkRecord[i].MarkAnchor) < 0)
2312       return -1;;
2313   RESTORE_STREAM (stream, state);
2314   return 0;
2315 }
2316
2317 static int
2318 read_anchor_array (OTF *otf, OTF_Stream *stream, long offset,
2319                    unsigned ClassCount, OTF_AnchorArray *array)
2320 {
2321   char *errfmt = "AnchorArray%s";
2322   int errret = -1;
2323   OTF_StreamState state;
2324   int i, j;
2325
2326   READ_OFFSET (stream, array->offset);
2327   SAVE_STREAM (stream, state);
2328   SEEK_STREAM (stream, offset + array->offset);
2329   READ_UINT16 (stream, array->Count);
2330   OTF_MALLOC (array->AnchorRecord, array->Count, "");
2331   for (i = 0; i < array->Count; i++)
2332     {
2333       OTF_MALLOC (array->AnchorRecord[i].Anchor, ClassCount,
2334                   " (AnchorRecord)");
2335       for (j = 0; j < ClassCount; j++)
2336         READ_OFFSET (stream, array->AnchorRecord[i].Anchor[j].offset);
2337     }
2338   for (i = 0; i < array->Count; i++)
2339     for (j = 0; j < ClassCount; j++)
2340       if (read_anchor (otf, stream, offset + array->offset,
2341                        &array->AnchorRecord[i].Anchor[j]) < 0)
2342         return -1;
2343   RESTORE_STREAM (stream, state);
2344   return 0;
2345 }
2346
2347 static OTF_PairSet *
2348 read_pair_set_list (OTF *otf, OTF_Stream *stream, long offset, unsigned num,
2349                     enum OTF_ValueFormat bit1, enum OTF_ValueFormat bit2)
2350 {
2351   char *errfmt = "PairSet%s";
2352   void *errret = NULL;
2353   OTF_StreamState state;
2354   OTF_PairSet *set;
2355   int i, j;
2356
2357   OTF_MALLOC (set, num, "");
2358   for (i = 0; i < num; i++)
2359     READ_OFFSET (stream, set[i].offset);
2360   SAVE_STREAM (stream, state);
2361   for (i = 0; i < num; i++)
2362     {
2363       SEEK_STREAM (stream, offset + set[i].offset);
2364       READ_UINT16 (stream, set[i].PairValueCount);
2365       OTF_MALLOC (set[i].PairValueRecord, set[i].PairValueCount, "");
2366       for (j = 0; j < set[i].PairValueCount; j++)
2367         {
2368           OTF_PairValueRecord *rec = set[i].PairValueRecord + j;
2369
2370           READ_UINT16 (stream, rec->SecondGlyph);
2371           read_value_record (otf, stream, offset, bit1, &rec->Value1);
2372           read_value_record (otf, stream, offset, bit2, &rec->Value2);
2373         }
2374     }
2375   RESTORE_STREAM (stream, state);
2376   return set;
2377 }
2378
2379 static OTF_Class1Record *
2380 read_class1_record_list (OTF *otf, OTF_Stream *stream, long offset,
2381                          unsigned num1, enum OTF_ValueFormat bit1,
2382                          unsigned num2, enum OTF_ValueFormat bit2)
2383 {
2384   char *errfmt = "Class1Record%s";
2385   void *errret = NULL;
2386   OTF_Class1Record *rec;
2387   int i, j;
2388
2389   OTF_MALLOC (rec, num1, "");
2390   for (i = 0; i < num1; i++)
2391     {
2392       OTF_CALLOC (rec[i].Class2Record, num2, " (Class2Record)");
2393       for (j = 0; j < num2; j++)
2394         {
2395           if (read_value_record (otf, stream, offset,
2396                                  bit1, &rec[i].Class2Record[j].Value1) < 0
2397               || read_value_record (otf, stream, offset,
2398                                     bit2, &rec[i].Class2Record[j].Value2) < 0)
2399             return NULL;
2400         }
2401     }
2402   return rec;
2403 }
2404
2405 static unsigned
2406 read_entry_exit_list (OTF *otf, OTF_Stream *stream, long offset,
2407                       OTF_EntryExitRecord **rec)
2408 {
2409   char *errfmt = "EntryExitSet%s";
2410   int errret = 0;
2411   unsigned count;
2412   int i;
2413   OTF_StreamState state;
2414
2415   READ_UINT16 (stream, count);
2416   if (! count)
2417     OTF_ERROR (OTF_ERROR_TABLE, " (zero count)");
2418   OTF_MALLOC (*rec, count, "");
2419   for (i = 0; i < count; i++)
2420     {
2421       READ_OFFSET (stream, (*rec)[i].EntryAnchor.offset);
2422       READ_OFFSET (stream, (*rec)[i].ExitAnchor.offset);
2423     }
2424   SAVE_STREAM (stream, state);
2425   for (i = 0; i < count; i++)
2426     {
2427       if (read_anchor (otf, stream, offset, &(*rec)[i].EntryAnchor) < 0)
2428         return -1;
2429       if (read_anchor (otf, stream, offset, &(*rec)[i].ExitAnchor) < 0)
2430         return -1;
2431     }
2432   RESTORE_STREAM (stream, state);
2433   return count;
2434 }
2435
2436 static int
2437 read_ligature_attach (OTF *otf, OTF_Stream *stream, long offset,
2438                       unsigned ClassCount, OTF_LigatureAttach *attach)
2439 {
2440   char *errfmt = "LigatureAttach%s";
2441   int errret = 1;
2442   int i, j;
2443
2444   SEEK_STREAM (stream, offset + attach->offset);
2445   READ_UINT16 (stream, attach->ComponentCount);
2446   OTF_MALLOC (attach->ComponentRecord, attach->ComponentCount, "");
2447   for (i = 0; i < attach->ComponentCount; i++)
2448     {
2449       OTF_MALLOC (attach->ComponentRecord[i].LigatureAnchor, ClassCount,
2450                   " (ComponentRecord)");
2451       for (j = 0; j < ClassCount; j++)
2452         READ_OFFSET (stream,
2453                      attach->ComponentRecord[i].LigatureAnchor[j].offset);
2454     }
2455   for (i = 0; i < attach->ComponentCount; i++)
2456     for (j = 0; j < ClassCount; j++)
2457       {
2458         if (attach->ComponentRecord[i].LigatureAnchor[j].offset)
2459           {
2460             if (read_anchor (otf, stream, offset + attach->offset,
2461                              &attach->ComponentRecord[i].LigatureAnchor[j]) < 0)
2462               return -1;
2463           }
2464         else
2465           attach->ComponentRecord[i].LigatureAnchor[j].AnchorFormat = 0;
2466       }
2467   return 0;
2468 }
2469
2470 static int
2471 read_ligature_array (OTF *otf, OTF_Stream *stream, long offset,
2472                      unsigned class_count, OTF_LigatureArray *array)
2473 {
2474   char *errfmt = "LigatureArray%s";
2475   int errret = -1;
2476   OTF_StreamState state;
2477   int i;
2478
2479   READ_OFFSET (stream, array->offset);
2480   SAVE_STREAM (stream, state);
2481   SEEK_STREAM (stream, offset + array->offset);
2482   READ_UINT16 (stream, array->LigatureCount);
2483   OTF_MALLOC (array->LigatureAttach, array->LigatureCount, "");
2484   for (i = 0; i < array->LigatureCount; i++)
2485     READ_OFFSET (stream, array->LigatureAttach[i].offset);
2486   for (i = 0; i < array->LigatureCount; i++)
2487     read_ligature_attach (otf, stream, offset + array->offset,
2488                           class_count, array->LigatureAttach + i);
2489   RESTORE_STREAM (stream, state);
2490   return 0;
2491 }
2492
2493 static int
2494 read_lookup_subtable_gpos (OTF *otf, OTF_Stream *stream,
2495                            long offset, unsigned type,
2496                            OTF_LookupSubTableGPOS *subtable)
2497 {
2498   char errfmt[256];
2499   int errret = -1;
2500
2501   SEEK_STREAM (stream, offset);
2502   READ_UINT16 (stream, subtable->Format);
2503   sprintf (errfmt, "GPOS Lookup %d-%d%%s", type, subtable->Format);
2504   switch (type)
2505     {
2506     case 1:
2507       if (subtable->Format == 1)
2508         {
2509           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2510             return -1;
2511           READ_UINT16 (stream, subtable->u.single1.ValueFormat);
2512           read_value_record (otf, stream, offset,
2513                              subtable->u.single1.ValueFormat,
2514                              &subtable->u.single1.Value);
2515         }
2516       else if (subtable->Format == 2)
2517         {
2518           OTF_GPOS_Single2 *single2 = &subtable->u.single2;
2519           int i;
2520
2521           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2522             return -1;
2523           READ_UINT16 (stream, single2->ValueFormat);
2524           READ_UINT16 (stream, single2->ValueCount);
2525           OTF_CALLOC (single2->Value, single2->ValueCount," (ValueRecord)");
2526           for (i = 0; i < single2->ValueCount; i++)
2527             read_value_record (otf, stream, offset, single2->ValueFormat,
2528                                single2->Value + i);
2529         }
2530       else
2531         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2532       break;
2533
2534     case 2:
2535       if (subtable->Format == 1)
2536         {
2537           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2538             return -1;
2539           READ_UINT16 (stream, subtable->u.pair1.ValueFormat1);
2540           READ_UINT16 (stream, subtable->u.pair1.ValueFormat2);
2541           READ_UINT16 (stream, subtable->u.pair1.PairSetCount);
2542           subtable->u.pair1.PairSet
2543             = read_pair_set_list (otf, stream, offset,
2544                                   subtable->u.pair1.PairSetCount,
2545                                   subtable->u.pair1.ValueFormat1,
2546                                   subtable->u.pair1.ValueFormat2);
2547           if (! subtable->u.pair1.PairSet)
2548             return -1;
2549         }
2550       else if (subtable->Format == 2)
2551         {
2552           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2553             return -1;
2554           READ_UINT16 (stream, subtable->u.pair2.ValueFormat1);
2555           READ_UINT16 (stream, subtable->u.pair2.ValueFormat2);
2556           if (read_class_def (otf, stream, offset,
2557                               &subtable->u.pair2.ClassDef1) < 0
2558               || read_class_def (otf, stream, offset,
2559                                  &subtable->u.pair2.ClassDef2) < 0)
2560             return -1;
2561           READ_UINT16 (stream, subtable->u.pair2.Class1Count);
2562           READ_UINT16 (stream, subtable->u.pair2.Class2Count);
2563           subtable->u.pair2.Class1Record
2564             = read_class1_record_list (otf, stream, offset,
2565                                        subtable->u.pair2.Class1Count,
2566                                        subtable->u.pair2.ValueFormat1,
2567                                        subtable->u.pair2.Class2Count,
2568                                        subtable->u.pair2.ValueFormat2);
2569           if (! subtable->u.pair2.Class1Record)
2570             return -1;
2571         }
2572       else
2573         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2574       break;
2575
2576     case 3:
2577       if (subtable->Format == 1)
2578         {
2579           if (read_coverage (otf, stream, offset, &subtable->Coverage) < 0)
2580             return -1;
2581           subtable->u.cursive1.EntryExitCount
2582             = read_entry_exit_list (otf, stream, offset,
2583                                     &subtable->u.cursive1.EntryExitRecord);
2584           if (! subtable->u.cursive1.EntryExitCount)
2585             return -1;
2586         }
2587       else
2588         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2589       break;
2590
2591     case 4:
2592       if (subtable->Format == 1)
2593         {
2594           read_coverage (otf, stream, offset, &subtable->Coverage);
2595           read_coverage (otf, stream, offset,
2596                          &subtable->u.mark_base1.BaseCoverage);
2597           READ_UINT16 (stream, subtable->u.mark_base1.ClassCount);
2598           read_mark_array (otf, stream, offset,
2599                            &subtable->u.mark_base1.MarkArray);
2600           read_anchor_array (otf, stream, offset,
2601                              subtable->u.mark_base1.ClassCount,
2602                              &subtable->u.mark_base1.BaseArray);
2603         }
2604       else
2605         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2606       break;
2607
2608     case 5:
2609       if (subtable->Format == 1)
2610         {
2611           read_coverage (otf, stream, offset, &subtable->Coverage);
2612           read_coverage (otf, stream, offset,
2613                          &subtable->u.mark_lig1.LigatureCoverage);
2614           READ_UINT16 (stream, subtable->u.mark_lig1.ClassCount);
2615           read_mark_array (otf, stream, offset,
2616                            &subtable->u.mark_lig1.MarkArray);
2617           read_ligature_array (otf, stream, offset,
2618                                subtable->u.mark_lig1.ClassCount,
2619                                &subtable->u.mark_lig1.LigatureArray);
2620         }
2621       break;
2622
2623     case 6:
2624       if (subtable->Format == 1)
2625         {
2626           read_coverage (otf, stream, offset, &subtable->Coverage);
2627           read_coverage (otf, stream, offset,
2628                          &subtable->u.mark_mark1.Mark2Coverage);
2629           READ_UINT16 (stream, subtable->u.mark_base1.ClassCount);
2630           read_mark_array (otf, stream, offset,
2631                            &subtable->u.mark_mark1.Mark1Array);
2632           read_anchor_array (otf, stream, offset,
2633                              subtable->u.mark_mark1.ClassCount,
2634                              &subtable->u.mark_mark1.Mark2Array);
2635         }
2636       else
2637         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2638       break;
2639
2640     case 7:
2641       if (subtable->Format == 1)
2642         {
2643           if (read_context1 (otf, stream, offset, &subtable->Coverage,
2644                              &subtable->u.context1) < 0)
2645             return errret;
2646         }
2647       else if (subtable->Format == 2)
2648         {
2649           if (read_context2 (otf, stream, offset, &subtable->Coverage,
2650                              &subtable->u.context2) < 0)
2651             return errret;
2652         }
2653       else if (subtable->Format == 3)
2654         {
2655           if (read_context3 (otf, stream, offset, &subtable->Coverage,
2656                              &subtable->u.context3) < 0)
2657             return errret;
2658         }
2659       else
2660         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2661       break;
2662
2663     case 8:
2664       if (subtable->Format == 1)
2665         {
2666           if (read_chain_context1 (otf, stream, offset, &subtable->Coverage,
2667                                    &subtable->u.chain_context1) < 0)
2668             return errret;
2669         }
2670       else if (subtable->Format == 2)
2671         {
2672           if (read_chain_context2 (otf, stream, offset, &subtable->Coverage,
2673                                    &subtable->u.chain_context2) < 0)
2674             return errret;
2675         }
2676       else if (subtable->Format == 3)
2677         {
2678           if (read_chain_context3 (otf, stream, offset, &subtable->Coverage,
2679                                    &subtable->u.chain_context3) < 0)
2680             return errret;
2681         }
2682       else
2683         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2684       break;
2685
2686     case 9:
2687       if (subtable->Format == 1)
2688         {
2689           unsigned ex_type;
2690           long ex_offset;
2691           OTF_LookupSubTableGPOS *ex_subtable;
2692
2693           READ_USHORT (stream, ex_type);
2694           READ_ULONG (stream, ex_offset);
2695           OTF_CALLOC (ex_subtable, 1, " (SubTable)");
2696           if (read_lookup_subtable_gpos (otf, stream, offset + ex_offset,
2697                                          ex_type, ex_subtable) < 0)
2698             return errret;
2699           subtable->u.extension1.ExtensionLookupType = ex_type;
2700           subtable->u.extension1.ExtensionOffset = ex_offset;
2701           subtable->u.extension1.ExtensionSubtable = ex_subtable;
2702         }
2703       else
2704         OTF_ERROR (OTF_ERROR_TABLE, " (Invalid SubFormat)");
2705       break;
2706
2707     default:
2708       OTF_ERROR (OTF_ERROR_TABLE, " (Invalid LookupType)");
2709     }
2710   return 0;
2711 }
2712
2713 static void *
2714 read_gpos_table (OTF *otf, OTF_TableInfo *table, enum OTF_ReaderFlag flag)
2715 {
2716   return read_gsub_gpos_table (otf, table, 0, flag);
2717 }
2718
2719 \f
2720 #if 0
2721 /* BASE */
2722
2723 static OTF_BASE *
2724 read_base_table (OTF_Stream *stream, long offset)
2725 {
2726   OTF_BASE *base;
2727
2728   OTF_MALLOC (base, 1);
2729
2730   return base;
2731 }
2732
2733 \f
2734 /* JSTF */
2735
2736 static OTF_JSTF *
2737 read_jstf_table (OTF_Stream *stream, long offset)
2738 {
2739   OTF_JSTF *jstf;
2740
2741   OTF_MALLOC (jstf, 1);
2742
2743   return jstf;
2744 }
2745 #endif /* 0 */
2746 \f
2747 /*** (1-11) Structure for OTF */
2748
2749 static int
2750 read_offset_table (OTF *otf, OTF_Stream *stream, OTF_OffsetTable *table)
2751 {
2752   int errret = -1;
2753
2754   READ_FIXED (stream, table->sfnt_version);
2755   READ_USHORT (stream, table->numTables);
2756   READ_USHORT (stream, table->searchRange);
2757   READ_USHORT (stream, table->enterSelector);
2758   READ_USHORT (stream, table->rangeShift);
2759   return 0;
2760 }
2761
2762 static OTF_Tag
2763 read_table_directory (OTF_Stream *stream, OTF_TableDirectory *table)
2764 {
2765   int errret = 0;
2766   OTF_Tag tag;
2767
2768   READ_TAG (stream, tag);
2769   table->tag = tag;
2770   table->name[0] = tag >> 24;
2771   table->name[1] = (tag >> 16) & 0xFF;
2772   table->name[2] = (tag >> 8) & 0xFF;
2773   table->name[3] = tag & 0xFF;
2774   table->name[4] = '\0';
2775   READ_ULONG (stream, table->checkSum);
2776   READ_ULONG (stream, table->offset);
2777   READ_ULONG (stream, table->length);
2778   return tag;
2779 }
2780
2781 static int
2782 read_header_part (OTF *otf, FILE *fp, FT_Face face)
2783 {
2784   char *errfmt = "otf header%s";
2785   int errret = -1;
2786   int i;
2787   OTF_InternalData *internal_data = (OTF_InternalData *) otf->internal_data;
2788
2789   internal_data->table_info[OTF_TABLE_TYPE_HEAD].address = (void *) &otf->head;
2790   internal_data->table_info[OTF_TABLE_TYPE_HEAD].reader = read_head_table;
2791   internal_data->table_info[OTF_TABLE_TYPE_NAME].address = (void *) &otf->name;
2792   internal_data->table_info[OTF_TABLE_TYPE_NAME].reader = read_name_table;
2793   internal_data->table_info[OTF_TABLE_TYPE_CMAP].address = (void *) &otf->cmap;
2794   internal_data->table_info[OTF_TABLE_TYPE_CMAP].reader = read_cmap_table;
2795   internal_data->table_info[OTF_TABLE_TYPE_GDEF].address = (void *) &otf->gdef;
2796   internal_data->table_info[OTF_TABLE_TYPE_GDEF].reader = read_gdef_table;
2797   internal_data->table_info[OTF_TABLE_TYPE_GSUB].address = (void *) &otf->gsub;
2798   internal_data->table_info[OTF_TABLE_TYPE_GSUB].reader = read_gsub_table;
2799   internal_data->table_info[OTF_TABLE_TYPE_GPOS].address = (void *) &otf->gpos;
2800   internal_data->table_info[OTF_TABLE_TYPE_GPOS].reader = read_gpos_table;
2801
2802   if (fp)
2803     {
2804       OTF_Tag head_tag = OTF_tag ("head");
2805       OTF_Tag name_tag = OTF_tag ("name");
2806       OTF_Tag cmap_tag = OTF_tag ("cmap");
2807       OTF_Tag gdef_tag = OTF_tag ("GDEF");
2808       OTF_Tag gsub_tag = OTF_tag ("GSUB");
2809       OTF_Tag gpos_tag = OTF_tag ("GPOS");
2810       OTF_Stream *stream = make_stream ("Offset Table");
2811
2812       if (! stream)
2813         return -1;
2814       internal_data->header_stream = stream;
2815
2816       /* Size of Offset Table is 12 bytes.  */
2817       if (setup_stream (stream, fp, 0, 12) < 0)
2818         return -1;
2819       if (read_offset_table (otf, stream, &otf->offset_table) < 0)
2820         return -1;
2821
2822       /* Size of each Table Directory is 16 bytes.  */
2823       if (setup_stream (stream, fp, 12, 16 * otf->offset_table.numTables) < 0)
2824         return -1;
2825
2826       OTF_CALLOC (otf->table_dirs, otf->offset_table.numTables,
2827                   " (OffsetTable)");
2828       for (i = 0; i < otf->offset_table.numTables; i++)
2829         {
2830           OTF_Tag tag = read_table_directory (stream, otf->table_dirs + i);
2831           OTF_TableInfo *table_info = NULL;
2832
2833           if (! tag)
2834             return -1;
2835           if (tag == head_tag)
2836             table_info = internal_data->table_info + OTF_TABLE_TYPE_HEAD;
2837           else if (tag == name_tag)
2838             table_info = internal_data->table_info + OTF_TABLE_TYPE_NAME;
2839           else if (tag == cmap_tag)
2840             table_info = internal_data->table_info + OTF_TABLE_TYPE_CMAP;
2841           else if (tag == gdef_tag)
2842             table_info = internal_data->table_info + OTF_TABLE_TYPE_GDEF;
2843           else if (tag == gsub_tag)
2844             table_info = internal_data->table_info + OTF_TABLE_TYPE_GSUB;
2845           else if (tag == gpos_tag)
2846             table_info = internal_data->table_info + OTF_TABLE_TYPE_GPOS;
2847
2848           if (table_info)
2849             {
2850               table_info->stream = make_stream (otf->table_dirs[i].name);
2851               if (setup_stream (table_info->stream, fp,
2852                                 otf->table_dirs[i].offset,
2853                                 otf->table_dirs[i].length) < 0)
2854                 return -1;
2855             }
2856         }
2857
2858       internal_data->header_stream = NULL;
2859       free_stream (stream);
2860     }
2861   else
2862     {
2863       OTF_Stream *stream;
2864
2865       internal_data->header_stream = NULL;
2866       if ((stream = make_stream_from_ft_face (face, "head")))
2867         internal_data->table_info[OTF_TABLE_TYPE_HEAD].stream = stream;
2868       if ((stream = make_stream_from_ft_face (face, "name")))
2869         internal_data->table_info[OTF_TABLE_TYPE_NAME].stream = stream;
2870       if ((stream = make_stream_from_ft_face (face, "cmap")))
2871         internal_data->table_info[OTF_TABLE_TYPE_CMAP].stream = stream;
2872       if ((stream = make_stream_from_ft_face (face, "GDEF")))
2873         internal_data->table_info[OTF_TABLE_TYPE_GDEF].stream = stream;
2874       if ((stream = make_stream_from_ft_face (face, "GSUB")))
2875         internal_data->table_info[OTF_TABLE_TYPE_GSUB].stream = stream;
2876       if ((stream = make_stream_from_ft_face (face, "GPOS")))
2877         internal_data->table_info[OTF_TABLE_TYPE_GPOS].stream = stream;
2878     }
2879
2880   if (! internal_data->table_info[OTF_TABLE_TYPE_GDEF].stream)
2881     /* We can simulate the GDEF table.  */
2882     internal_data->table_info[OTF_TABLE_TYPE_GDEF].stream
2883       = make_stream ("GDEF");
2884   return 0;
2885 }
2886
2887 static OTF_TableInfo *
2888 get_table_info (OTF *otf, const char *name)
2889 {
2890   char *errfmt = "OTF Table Read%s";
2891   OTF_TableInfo *errret = NULL;
2892   OTF_InternalData *internal_data = otf->internal_data;
2893   OTF_TableInfo *table_info;
2894   OTF_Tag tag = OTF_tag (name);
2895
2896   if (! tag)
2897     OTF_ERROR (OTF_ERROR_TABLE, " (invalid table name)");
2898
2899   if (tag == OTF_tag ("head"))
2900     table_info = internal_data->table_info + OTF_TABLE_TYPE_HEAD;
2901   else if (tag == OTF_tag ("name"))
2902     table_info = internal_data->table_info + OTF_TABLE_TYPE_NAME;
2903   else if (tag == OTF_tag ("cmap"))
2904     table_info = internal_data->table_info + OTF_TABLE_TYPE_CMAP;
2905   else if (tag == OTF_tag ("GDEF"))
2906     table_info = internal_data->table_info + OTF_TABLE_TYPE_GDEF;
2907   else if (tag == OTF_tag ("GSUB"))
2908     table_info = internal_data->table_info + OTF_TABLE_TYPE_GSUB;
2909   else if (tag == OTF_tag ("GPOS"))
2910     table_info = internal_data->table_info + OTF_TABLE_TYPE_GPOS;
2911   else
2912     OTF_ERROR (OTF_ERROR_TABLE, " (unsupported table name)");
2913
2914   if (*table_info->address)
2915     /* Already read.  */
2916     return table_info;
2917   if (! table_info->stream)
2918     OTF_ERROR (OTF_ERROR_TABLE, " (table not found)");
2919   if (! table_info->reader)
2920     OTF_ERROR (OTF_ERROR_TABLE, " (invalid contents)");
2921   return table_info;
2922 }
2923
2924
2925 \f
2926 /*** (2) API for reading OTF */
2927
2928 /*** (2-1) OTF_open() */
2929
2930 /* Note: We can't use memory allocation macros in the following
2931    functions because those macros return from the functions before
2932    freeing memory previously allocated.  */
2933
2934 OTF *
2935 OTF_open (const char *otf_name)
2936 {
2937   FILE *fp;
2938   char *errfmt = "opening otf (%s)";
2939   void *errret = NULL;
2940   OTF *otf;
2941   OTF_InternalData *internal_data;
2942   int len = strlen (otf_name);
2943   const char *ext = otf_name + (len - 4);
2944
2945   if (debug_flag < 0)
2946     set_debug_flag ();
2947
2948   if (len < 4
2949       || ext[0] != '.'
2950       || (ext[1] != 'O' && ext[1] != 'T' && ext[1] != 'o' && ext[1] != 't')
2951       || (ext[2] != 'T' && ext[2] != 't')
2952       || (ext[3] != 'F' && ext[3] != 'f'))
2953     OTF_ERROR (OTF_ERROR_FILE, otf_name);
2954   fp = fopen (otf_name, "r");
2955   if (! fp)
2956     OTF_ERROR (OTF_ERROR_FILE, otf_name);
2957   otf = calloc (1, sizeof (OTF));
2958   if (! otf)
2959     OTF_ERROR (OTF_ERROR_MEMORY, "body allocation");
2960   otf->filename = strdup (otf_name);
2961   if (! otf->filename)
2962     {
2963       OTF_close (otf);
2964       fclose (fp);
2965       OTF_ERROR (OTF_ERROR_MEMORY, "filename allocation");
2966     }
2967
2968   internal_data = calloc (1, sizeof (OTF_InternalData));
2969   if (! internal_data)
2970     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData");
2971   otf->internal_data = internal_data;
2972   if (! allocate_memory_record (otf))
2973     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData)");
2974
2975   /* Here after, all pointers to allocated memory are recorded in
2976      otf->internal_data->memory_record except for what allocated by
2977      the functions allocate_memory_record and make_stream.  */
2978
2979   if (read_header_part (otf, fp, NULL) < 0)
2980     {
2981       OTF_close (otf);
2982       fclose (fp);
2983       return NULL;
2984     }
2985
2986   fclose (fp);
2987   return otf;
2988 }
2989
2990 OTF *
2991 OTF_open_ft_face (FT_Face face)
2992 {
2993   char *errfmt = "opening otf from Freetype (%s)";
2994   void *errret = NULL;
2995   OTF *otf;
2996   OTF_InternalData *internal_data;
2997
2998   if (debug_flag < 0)
2999     set_debug_flag ();
3000
3001   if (! FT_IS_SFNT (face))
3002     OTF_ERROR (OTF_ERROR_FILE, (char *) face->family_name);
3003   otf = calloc (1, sizeof (OTF));
3004   if (! otf)
3005     OTF_ERROR (OTF_ERROR_MEMORY, "body allocation");
3006   otf->filename = NULL;
3007   
3008   internal_data = calloc (1, sizeof (OTF_InternalData));
3009   if (! internal_data)
3010     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData");
3011   otf->internal_data = internal_data;
3012   if (! allocate_memory_record (otf))
3013     OTF_ERROR (OTF_ERROR_MEMORY, " (InternalData)");
3014
3015   if (read_header_part (otf, NULL, face) < 0)
3016     {
3017       OTF_close (otf);
3018       return NULL;
3019     }
3020
3021   return otf;
3022 }
3023
3024 /*** (2-2) OTF_close() */
3025
3026 void
3027 OTF_close (OTF *otf)
3028 {
3029   OTF_InternalData *internal_data = otf->internal_data;
3030   int i;
3031
3032   if (internal_data)
3033     {
3034       OTF_MemoryRecord *memrec = internal_data->memory_record;
3035       OTF_ApplicationData *app_data = internal_data->app_data;
3036
3037       if (internal_data->header_stream)
3038         free_stream (internal_data->header_stream);
3039
3040       for (i = 0; i < OTF_TABLE_TYPE_MAX; i++)
3041         if (internal_data->table_info[i].stream)
3042           free_stream (internal_data->table_info[i].stream);
3043
3044       for (; app_data; app_data = app_data->next)
3045         if (app_data->data && app_data->freer)
3046           app_data->freer (app_data->data);
3047
3048       while (memrec)
3049         {
3050           OTF_MemoryRecord *next = memrec->next;
3051
3052           for (i = memrec->used - 1; i >= 0; i--)
3053             free (memrec->memory[i]);
3054           free (memrec);
3055           memrec = next;
3056         }
3057
3058       free (internal_data);
3059     }
3060   if (otf->filename)
3061     free (otf->filename);
3062   free (otf);
3063 }
3064
3065 /*** (2-3) OTF_get_table() */
3066
3067 int
3068 OTF_get_table (OTF *otf, const char *name)
3069 {
3070   OTF_TableInfo *table_info = get_table_info (otf, name);
3071   void *address;
3072
3073   if (! table_info)
3074     return -1;
3075   if (! table_info->stream)
3076     /* Already fully loaded.  */
3077     return 0;
3078
3079   address = (*table_info->reader) (otf, table_info, OTF_READ_FULL);
3080   free_stream (table_info->stream);
3081   table_info->stream = NULL;
3082   if (! address)
3083     {
3084       table_info->reader = NULL;
3085       return -1;
3086     }
3087   return 0;
3088 }
3089
3090 /*** (2-4) OTF_check_table() */
3091
3092 int
3093 OTF_check_table (OTF *otf, const char *name)
3094 {
3095   return (get_table_info (otf, name) ? 0 : -1);
3096 }
3097
3098 /*** (2-5) OTF_get_scripts()  */
3099
3100 int
3101 OTF_get_scripts (OTF *otf, int gsubp)
3102 {
3103   OTF_TableInfo *table_info
3104     = (otf->internal_data->table_info
3105        + (gsubp ? OTF_TABLE_TYPE_GSUB : OTF_TABLE_TYPE_GPOS));
3106   void *address;
3107
3108   if (! table_info->reader)
3109     return -1;
3110   if (! table_info->stream)
3111     /* Already fully loaded.  */
3112     return 0;
3113
3114   address = (*table_info->reader) (otf, table_info, OTF_READ_SCRIPTS);
3115   if (! address)
3116     {
3117       table_info->reader = NULL;
3118       return -1;
3119     }
3120   return 0;
3121 }
3122
3123 /*** (2-6) OTF_get_features()  */
3124
3125 int
3126 OTF_get_features (OTF *otf, int gsubp)
3127 {
3128   OTF_TableInfo *table_info
3129     = (otf->internal_data->table_info
3130        + (gsubp ? OTF_TABLE_TYPE_GSUB : OTF_TABLE_TYPE_GPOS));
3131   void *address;
3132
3133   if (! table_info->reader)
3134     return -1;
3135   if (! table_info->stream)
3136     {
3137       if (*table_info->address)
3138         /* Already fully loaded.  */
3139         return 0;
3140       return -1;
3141     }
3142
3143   address = (*table_info->reader) (otf, table_info, OTF_READ_FEATURES);
3144   if (! address)
3145     {
3146       table_info->reader = NULL;
3147       return -1;
3148     }
3149   return 0;
3150 }
3151
3152 /*** (2-7) OTF_check_features  */
3153
3154 int
3155 OTF_check_features (OTF *otf, int gsubp,
3156                     OTF_Tag script, OTF_Tag language, const OTF_Tag *features,
3157                     int n_features)
3158 {
3159   OTF_ScriptList *script_list;
3160   OTF_Script *Script = NULL;
3161   OTF_LangSys *LangSys = NULL;
3162   OTF_FeatureList *feature_list;
3163   int i, j;
3164
3165   if (OTF_get_features (otf, gsubp) < 0)
3166     {
3167       for (i = 0; i < n_features; i++)
3168         {
3169           OTF_Tag feature = features[i];
3170
3171           if (feature == 0)
3172             continue;
3173           if ((((unsigned) feature) & 0x80000000) == 0)
3174             return -1;
3175         }
3176       return 1;
3177     }
3178   if (gsubp)
3179     {
3180       script_list = &otf->gsub->ScriptList;
3181       feature_list = &otf->gsub->FeatureList;
3182     }
3183   else
3184     {
3185       script_list = &otf->gpos->ScriptList;
3186       feature_list = &otf->gpos->FeatureList;
3187     }
3188   for (i = 0; i < script_list->ScriptCount && ! Script; i++)
3189     if (script_list->Script[i].ScriptTag == script)
3190       Script = script_list->Script + i;
3191   if (! Script)
3192     return 0;
3193   if (language)
3194     {
3195       for (i = 0; i < Script->LangSysCount && ! LangSys; i++)
3196         if (Script->LangSysRecord[i].LangSysTag == language)
3197           LangSys = Script->LangSys + i;
3198     }
3199   if (! LangSys)
3200     LangSys = &Script->DefaultLangSys;
3201   for (j = 0; j < n_features; j++)
3202     {
3203       OTF_Tag feature = features[j];
3204       int negate = 0;
3205
3206       if (feature == 0)
3207         continue;
3208       if (((unsigned) feature) & 0x80000000)
3209         {
3210           feature = (OTF_Tag) (((unsigned) feature) & 0x7FFFFFFF);
3211           negate = 1;
3212         }
3213       for (i = 0; i < LangSys->FeatureCount; i++)
3214         if (feature_list->Feature[LangSys->FeatureIndex[i]].FeatureTag
3215             == feature)
3216           {
3217             if (negate)
3218               return 0;
3219             break;
3220           }
3221       if (i == LangSys->FeatureCount)
3222         return 0;
3223     }
3224   return 1;
3225 }
3226
3227 \f
3228 /*** (5) API miscellaneous ***/
3229
3230 OTF_Tag
3231 OTF_tag (const char *name)
3232 {
3233   const unsigned char *p = (unsigned char *) name;
3234
3235   if (! name)
3236     return (OTF_Tag) 0;
3237   return (OTF_Tag) ((p[0] << 24)
3238                     | (! p[1] ? 0
3239                        : ((p[1] << 16)
3240                           | (! p[2] ? 0
3241                              : (p[2] << 8) | p[3]))));
3242 }
3243
3244 void
3245 OTF_tag_name (OTF_Tag tag, char *name)
3246 {
3247   name[0] = (char) (tag >> 24);
3248   name[1] = (char) ((tag >> 16) & 0xFF);
3249   name[2] = (char) ((tag >> 8) & 0xFF);
3250   name[3] = (char) (tag & 0xFF);
3251   name[4] = '\0';
3252 }
3253
3254 int
3255 OTF_put_data (OTF *otf, char *id, void *data, void (*freer) (void *data))
3256 {
3257   char *errfmt = "appdata %s";
3258   int errret = -1;
3259   OTF_InternalData *internal_data = (OTF_InternalData *) otf->internal_data;
3260   OTF_ApplicationData *app_data = internal_data->app_data;
3261   int len = strlen (id) + 1;
3262
3263   for (; app_data; app_data = app_data->next)
3264     if (memcmp (app_data->id, id, len) == 0)
3265       {
3266         if (app_data->data && app_data->freer)
3267           app_data->freer (app_data->data);
3268         break;
3269       }
3270   if (! app_data)
3271     {
3272       OTF_MALLOC (app_data, sizeof (OTF_ApplicationData), id);
3273       app_data->next = internal_data->app_data;
3274       internal_data->app_data = app_data;
3275       OTF_MALLOC (app_data->id, len, id);
3276       memcpy (app_data->id, id, len);
3277     }
3278   app_data->data = data;
3279   app_data->freer = freer;
3280   return 0;
3281 }
3282
3283 void *
3284 OTF_get_data (OTF *otf, char *id)
3285 {
3286   OTF_InternalData *internal_data = (OTF_InternalData *) otf->internal_data;
3287   OTF_ApplicationData *app_data = internal_data->app_data;
3288   
3289   for (; app_data; app_data = app_data->next)
3290     if (strcmp (app_data->id, id) == 0)
3291       return app_data->data;
3292   return NULL;
3293 }