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