summaryrefslogtreecommitdiff
path: root/src/Type1/t1funcs.c
blob: ecbd4d2d98654f41015d4613a6ad5daa5bd25809 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
/* $Xorg: t1funcs.c,v 1.5 2001/02/09 02:04:01 xorgcvs Exp $ */
/* Copyright International Business Machines,Corp. 1991
 * All Rights Reserved
 *
 * License, subject to the license given below, to use,
 * copy, modify, and distribute this software * and its
 * documentation for any purpose and without fee is hereby
 * granted, provided that the above copyright notice appear
 * in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation,
 * and that the name of IBM not be used in advertising or
 * publicity pertaining to distribution of the software
 * without specific, written prior permission.
 *
 * IBM PROVIDES THIS SOFTWARE "AS IS", WITHOUT ANY WARRANTIES
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT
 * LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF
 * THIRD PARTY RIGHTS.  THE ENTIRE RISK AS TO THE QUALITY AND
 * PERFORMANCE OF THE SOFTWARE, INCLUDING ANY DUTY TO SUPPORT
 * OR MAINTAIN, BELONGS TO THE LICENSEE.  SHOULD ANY PORTION OF
 * THE SOFTWARE PROVE DEFECTIVE, THE LICENSEE (NOT IBM) ASSUMES
 * THE ENTIRE COST OF ALL SERVICING, REPAIR AND CORRECTION.  IN
 * NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 * SOFTWARE.
 *
 * Author: Jeffrey B. Lotspiech, IBM Almaden Research Center
 *   Modeled on spfuncs.c by Dave Lemke, Network Computing Devices, Inc
 *   which contains the following copyright and permission notices:
 *
 * Copyright 1990, 1991 Network Computing Devices;
 * Portions Copyright 1987 by Digital Equipment Corporation
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the names of Network Computing Devices
 * or Digital not be used in advertising or publicity pertaining to 
 * distribution of the software without specific, written prior permission.  
 * Network Computing Devices or Digital make no representations about the
 * suitability of this software for any purpose.  It is provided "as is"
 * without express or implied warranty.
 *
 * NETWORK COMPUTING DEVICES AND DIGITAL DISCLAIM ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS, IN NO EVENT SHALL NETWORK COMPUTING DEVICES OR DIGITAL BE
 * LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
/* Copyright (c) 1994-1999 Silicon Graphics, Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CID Font Code Public Licence
 * Version 1.0 (the "License"). You may not use this file except in compliance
 * with the Licence. You may obtain a copy of the License at Silicon Graphics,
 * Inc., attn: Legal Services, 2011 N. Shoreline Blvd., Mountain View, CA
 * 94043 or at http://www.sgi.com/software/opensource/cid/license.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis.
 * ALL WARRANTIES ARE DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED
 * WARRANTIES OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR PURPOSE OR OF
 * NON-INFRINGEMENT. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Software is CID font code that was developed by Silicon
 * Graphics, Inc.
 */
/* $XFree86: xc/lib/font/Type1/t1funcs.c,v 3.33 2003/07/19 13:16:40 tsi Exp $ */

/*

Copyright 1987, 1994, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from The Open Group.

*/

#ifndef FONTMODULE
#include <string.h>
#ifdef BUILDCID
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#endif
#ifdef _XOPEN_SOURCE
#include <math.h>
#else
#define _XOPEN_SOURCE	/* to get prototype for hypot on some systems */
#include <math.h>
#undef _XOPEN_SOURCE
#endif
#include "X11/Xfuncs.h"
#ifdef USE_MMAP
#include <sys/types.h>
#include <sys/mman.h>
#endif
#else
#include "Xmd.h"
#include "Xdefs.h"
#endif

#include "os.h"

#ifdef FONTMODULE
#include "xf86_ansic.h"
#endif

#include "fntfilst.h"
#include "fontutil.h"
#include "FSproto.h"
#include "fontenc.h"
#include "t1unicode.h"
 
#ifdef BUILDCID
#include "range.h"
#endif

#include "objects.h"
#include "spaces.h"
#include "paths.h"
#include "regions.h"
#include "t1stdio.h"
#include "util.h"
#include "fontfcn.h"
#include "t1intf.h"


static int Type1GetGlyphs ( FontPtr pFont, unsigned long count,
			    unsigned char *chars, FontEncoding charEncoding, 
			    unsigned long *glyphCount, CharInfoPtr *glyphs );

#ifdef BUILDCID
#define CMapDir "/CMap/"
#define CFMDir "/CFM/"
#define CIDFontDir "/CIDFont/"
#endif

static int Type1GetMetrics ( FontPtr pFont, unsigned long count, 
				    unsigned char *chars, 
				    FontEncoding charEncoding, 
				    unsigned long *glyphCount, 
				    xCharInfo **glyphs );

 
#define minchar(p) ((p).min_char_low + ((p).min_char_high << 8))
#define maxchar(p) ((p).max_char_low + ((p).max_char_high << 8))

static void fillrun ( char *p, pel x0, pel x1, int bit );
 
extern psfont *FontP;
extern psobj *ISOLatin1EncArrayP;

#ifdef BUILDCID
extern char CurCIDFontName[];
extern char CurCMapName[];

static CharInfoPtr CIDGetGlyph ( FontPtr pFont, unsigned int charcode, 
				 CharInfoPtr pci );

extern cidfont *CIDFontP;
extern cmapres *CMapP;
#endif

static void fill ( char *dest, int h, int w, struct region *area, int byte, 
		   int bit, int wordsize );

#ifdef BUILDCID
int 
CIDOpenScalable (FontPathElementPtr fpe, 
		 FontPtr *ppFont, 
		 int flags, 
		 FontEntryPtr entry, 
		 char *fileName, 
		 FontScalablePtr vals, 
		 fsBitmapFormat format,
		 fsBitmapFormatMask fmask, 
		 FontPtr non_cachable_font) /* We don't do licensing */
{
    FontPtr     pFont;
    int         bit,
                byte,
                glyph,
                scan,
                image;
    long *pool;           /* memory pool for ximager objects              */
    int size;             /* for memory size calculations                 */
    struct XYspace *S;    /* coordinate space for character               */
    register int i;
    int nchars, len, rc;
    cidglyphs *cid;
    char *p;
    double t1 = .001, t2 = 0.0, t3 = 0.0, t4 = .001;
    double sxmult;
    char CIDFontName[CID_NAME_MAX];
    char CMapName[CID_NAME_MAX];
    char cidfontname[CID_PATH_MAX];
    char cmapname[CID_PATH_MAX];
    char *path;
    char cidfontpath[CID_PATH_MAX];
    char cmappath[CID_PATH_MAX];
#if defined(HAVE_CFM) || defined(CID_ALL_CHARS)
    char cfmdir[CID_PATH_MAX];
    char cfmfilename[CID_NAME_MAX];
#endif
#if defined(CID_ALL_CHARS)
    char *cf;
#else
    long sAscent, sDescent;
#endif

    /* check the font name */
    len = strlen(fileName);
    if (len <= 0 || len > CID_NAME_MAX - 1)
        return BadFontName;

#if defined(HAVE_CFM) || defined(CID_ALL_CHARS)
    strcpy(cfmdir, fileName);
    p = strrchr(cfmdir, '/');
    if (p) *p = '\0';
#endif

    path = fileName;
    if (!(fileName = strrchr(fileName, '/')))
        return BadFontName;

    len = fileName - path;
    strncpy(cidfontpath, path, len);
    cidfontpath[len] = '\0';
    strcpy(cmappath, cidfontpath);
    strcat(cmappath, CMapDir);
#ifdef HAVE_CFM
    strcpy(cfmdir, cidfontpath);
    strcat(cfmdir, CFMDir);
#endif
    strcat(cidfontpath, CIDFontDir);

    fileName++;

    /* extract the CIDFontName and CMapName from the font name */
    /* check for <CIDFontName>--<CMapName> */
    if ((p = strstr(fileName, "--"))) {
        if (p == fileName)
            return BadFontName;
        else {
            strcpy(CIDFontName, fileName);
            CIDFontName[p - fileName] = '\0';
            p += 2;
            i = 0;
            while (*p && *p != '.')
                CMapName[i++] = *p++;
            CMapName[i] = '\0';
            if ((len = strlen(CMapName)) <= 0)
                return BadFontName;
        }
    } else
        return BadFontName;

    /* The CMap files whose names end with -V are not yet supported */
    len = strlen(CMapName);
    if ((len >= 2 && CMapName[len - 2] == '-' && CMapName[len - 1] == 'V') ||
        (len == 1 && CMapName[len - 1] == 'V'))
        return BadFontName;

    /* Reject ridiculously small font sizes that will blow up the math */
    if (hypot(vals->pixel_matrix[0], vals->pixel_matrix[1]) < 1.0 ||
           hypot(vals->pixel_matrix[2], vals->pixel_matrix[3]) < 1.0)
           return BadFontName;

#ifdef CID_ALL_CHARS
    if ((cf = getenv("CFMDIR")) == NULL)
        strcat(cfmdir, CFMDir);
    else {
        strcpy(cfmdir, cf);
        strcat(cfmdir, "/");
    }
#endif

#if defined(HAVE_CFM) || defined(CID_ALL_CHARS)
    strcpy(cfmfilename, cfmdir);
    strcat(cfmfilename, CIDFontName);
    strcat(cfmfilename, "--");
    strcat(cfmfilename, CMapName);
    strcat(cfmfilename, ".cfm");
#endif

    /* create a full-path name for a CIDFont file */
    if (strlen(cidfontpath) + strlen(CIDFontName) + 2 >
        CID_PATH_MAX)
        return BadFontName;
    strcpy(cidfontname, cidfontpath);
    strcat(cidfontname, CIDFontName);

    /* create a full-path name for a CMap file */
    if (strlen(cmappath) + strlen(CMapName) + 2 > CID_PATH_MAX)
        return BadFontName;
    strcpy(cmapname, cmappath);
    strcat(cmapname, CMapName);

    /* set up default values */
    FontDefaultFormat(&bit, &byte, &glyph, &scan);
    /* get any changes made from above */
    rc = CheckFSFormat(format, fmask, &bit, &byte, &scan, &glyph, &image);
    if (rc != Successful)
        return rc;

#define  PAD(bits, pad)  (((bits)+(pad)-1)&-(pad))

    if (!(pFont = CreateFontRec()))
        return AllocError;

    cid = (cidglyphs *)xalloc(sizeof(cidglyphs));
    if (cid == NULL) {
        DestroyFontRec(pFont);
        return AllocError;
    }
    bzero(cid, sizeof(cidglyphs));

    /* heuristic for "maximum" size of pool we'll need: */
    size = 200000 + 600 *
              (int)hypot(vals->pixel_matrix[2], vals->pixel_matrix[3])
              * sizeof(short);
    if (size < 0 || NULL == (pool = (long *) xalloc(size))) {
            xfree(cid);
            DestroyFontRec(pFont);
            return AllocError;
    }

    addmemory(pool, size);

    /* load font if not already loaded */
    if (!CIDfontfcnA(cidfontname, cmapname, &rc)) {
      FontP = NULL;
      delmemory();
      xfree(pool);
      xfree(cid);
      DestroyFontRec(pFont);
      return Type1ReturnCodeToXReturnCode(rc);
    }

    FontP = NULL;

    S = (struct XYspace *) t1_Transform((struct xobject *)IDENTITY, 
					t1, t2, t3, t4);

    S = (struct XYspace *) Permanent(t1_Transform((struct xobject *)S, 
						   vals->pixel_matrix[0],
						   -vals->pixel_matrix[1],
						   vals->pixel_matrix[2],
						   -vals->pixel_matrix[3]));

    /* multiplier for computation of raw values */
    sxmult = hypot(vals->pixel_matrix[0], vals->pixel_matrix[1]);
    if (sxmult > EPS) sxmult = 1000.0 / sxmult;

    pFont->info.firstRow = CMapP->firstRow;
    pFont->info.firstCol = CMapP->firstCol;
    pFont->info.lastRow = CMapP->lastRow;
    pFont->info.lastCol = CMapP->lastCol;

    nchars = (pFont->info.lastRow - pFont->info.firstRow + 1) *
        (pFont->info.lastCol - pFont->info.firstCol + 1);

    delmemory();
    xfree(pool);

    if (pFont->info.firstCol > pFont->info.lastCol)
    {
      xfree(cid);
      DestroyFontRec(pFont);
      return BadFontName;
    }

    cid->glyphs = (CharInfoRec **)xalloc(nchars*sizeof(CharInfoRec *));
    if (cid->glyphs == NULL) {
      xfree(cid);
      DestroyFontRec(pFont);
      return AllocError;
    }
    bzero(cid->glyphs, nchars*sizeof(CharInfoRec *));

    pFont->info.defaultCh = 0;
    pFont->format      = format;

    pFont->bit         = bit;
    pFont->byte        = byte;
    pFont->glyph       = glyph;
    pFont->scan        = scan;

    pFont->get_metrics = CIDGetMetrics;
    pFont->get_glyphs  = CIDGetGlyphs;
    pFont->unload_font = CIDCloseFont;
    pFont->unload_glyphs = NULL;
    pFont->refcnt = 0;

    len = strlen(cidfontname);
    cid->CIDFontName = (char *)xalloc(len + 1);
    if (cid->CIDFontName == NULL) {
      xfree(cid->glyphs);
      xfree(cid);
      DestroyFontRec(pFont);
      return AllocError;
    }
    strcpy(cid->CIDFontName, cidfontname);

    len = strlen(cmapname);
    cid->CMapName = (char *)xalloc(len + 1);
    if (cid->CMapName == NULL) {
      xfree(cid->CIDFontName);
      xfree(cid->glyphs);
      xfree(cid);
      DestroyFontRec(pFont);
      return AllocError;
    }
    strcpy(cid->CMapName, cmapname);

    cid->pixel_matrix[0] = vals->pixel_matrix[0];
    cid->pixel_matrix[1] = vals->pixel_matrix[1];
    cid->pixel_matrix[2] = vals->pixel_matrix[2];
    cid->pixel_matrix[3] = vals->pixel_matrix[3];

    pFont->fontPrivate = (unsigned char *)cid;

    pFont->info.fontAscent =
      (CIDFontP->CIDfontInfoP[CIDFONTBBOX].value.data.arrayP[3].data.integer *
      vals->pixel_matrix[3] +
      (CIDFontP->CIDfontInfoP[CIDFONTBBOX].value.data.arrayP[3].data.integer >
      0 ? 500 : -500)) / 1000;

    pFont->info.fontDescent =
      -(int)((double)CIDFontP->CIDfontInfoP[CIDFONTBBOX].value.data.arrayP[1].data.integer
      * vals->pixel_matrix[3] +
      (CIDFontP->CIDfontInfoP[CIDFONTBBOX].value.data.arrayP[1].data.integer >
      0 ? 500 : -500)) / 1000;

    /* Adobe does not put isFixedPitch entries in CID-keyed fonts.  */
    /* CID-keyed are not constant-width fonts.                      */
    pFont->info.constantWidth = 0;

#ifndef CID_ALL_CHARS
    sAscent = CIDFontP->CIDfontInfoP[CIDFONTBBOX].value.data.arrayP[3].data.integer;
    sDescent = -CIDFontP->CIDfontInfoP[CIDFONTBBOX].value.data.arrayP[1].data.integer;
#endif

    if (strncmp(entry->name.name, "-bogus", 6)) {
#ifdef CID_ALL_CHARS
      ComputeBoundsAllChars(pFont, cfmfilename, sxmult);
#else
#ifdef HAVE_CFM
      CIDFillFontInfo(pFont, vals, cidfontname, entry->name.name, cmapname,
                    cfmfilename, sAscent, sDescent, sxmult);
#else
      CIDFillFontInfo(pFont, vals, cidfontname, entry->name.name, cmapname,
                    sAscent, sDescent, sxmult);
#endif /* HAVE_CFM */
#endif /* CID_ALL_CHARS */
    }

    *ppFont = pFont;

    return Successful;
}
#endif
 
/*ARGSUSED*/
int 
Type1OpenScalable (FontPathElementPtr fpe, 
		   FontPtr *ppFont, 
		   int flags, 
		   FontEntryPtr entry, 
		   char *fileName, 
		   FontScalablePtr vals, 
		   fsBitmapFormat format,
		   fsBitmapFormatMask fmask, 
		   FontPtr non_cachable_font) 	/* We don't do licensing */
{
       FontPtr     pFont;
       int         bit,
                   byte,
                   glyph,
                   scan,
                   image;
       int pad,wordsize;     /* scan & image in bits                         */
       long *pool;           /* memory pool for ximager objects              */
       int size;             /* for memory size calculations                 */
       struct XYspace *S;    /* coordinate space for character               */
       struct region *area;
       CharInfoRec *glyphs;
       int len, rc, count = 0, i = 0;
       struct type1font *type1;
       char *p;
       FontMapPtr mapping = NULL;
       int no_mapping;
       psobj *fontmatrix;
       long x0, total_width = 0, total_raw_width = 0;
       double x1, y1, t1 = .001, t2 = 0.0, t3 = 0.0, t4 = .001;
       double sxmult;

       /* Reject ridiculously small font sizes that will blow up the math */
       if (hypot(vals->pixel_matrix[0], vals->pixel_matrix[1]) < 1.0 ||
	   hypot(vals->pixel_matrix[2], vals->pixel_matrix[3]) < 1.0)
	   return BadFontName;

       /* set up default values */
       FontDefaultFormat(&bit, &byte, &glyph, &scan);
       /* get any changes made from above */
       rc = CheckFSFormat(format, fmask, &bit, &byte, &scan, &glyph, &image);
       if (rc != Successful)
               return rc;
 
       pad                = glyph * 8;
       wordsize           = scan * 8;
 
#define  PAD(bits, pad)  (((bits)+(pad)-1)&-(pad))
 
       pFont = CreateFontRec();
       if (pFont == NULL)
           return AllocError;

       type1 = (struct type1font *)xalloc(sizeof(struct type1font));
       if (type1 == NULL) {
               DestroyFontRec(pFont);
               return AllocError;
       }
       bzero(type1, sizeof(struct type1font));
 
       /* heuristic for "maximum" size of pool we'll need: */
#ifdef BUILDCID
       size = 400000 + 600 *
#else
       size = 200000 + 600 *
#endif
	      (int)hypot(vals->pixel_matrix[2], vals->pixel_matrix[3])
	      * sizeof(short);
       if (size < 0 || NULL == (pool = (long *) xalloc(size))) {
               xfree(type1);
               DestroyFontRec(pFont);
               return AllocError;
       }
 
       addmemory(pool, size);
 
 
       glyphs = type1->glyphs;
 
       /* load font if not already loaded */
       if (!fontfcnA(fileName, &rc)) {
         delmemory();
	 xfree(type1);
	 DestroyFontRec(pFont);
         xfree(pool);
         return Type1ReturnCodeToXReturnCode(rc);
       }

       fontmatrix = &FontP->fontInfoP[FONTMATRIX].value;
       if (objPIsArray(fontmatrix) && fontmatrix->len == 6)
       {
#define assign(n,d,f) if (objPIsInteger(fontmatrix->data.arrayP + n)) \
			  d = fontmatrix->data.arrayP[n].data.integer; \
		      else if (objPIsReal(fontmatrix->data.arrayP + n)) \
			  d = fontmatrix->data.arrayP[n].data.real; \
		      else d = f;

	   assign(0, t1, .001);
	   assign(1, t2, 0.0);
	   assign(2, t3, 0.0);
	   assign(3, t4, .001);
       }

       S = (struct XYspace *) t1_Transform((struct xobject *)IDENTITY,
					   t1, t2, t3, t4);

       S = (struct XYspace *) Permanent(t1_Transform((struct xobject *)S, 
						     vals->pixel_matrix[0],
						     -vals->pixel_matrix[1],
						     vals->pixel_matrix[2],
						     -vals->pixel_matrix[3]));


       /* multiplier for computation of raw values */
       sxmult = hypot(vals->pixel_matrix[0], vals->pixel_matrix[1]);
       if (sxmult > EPS) sxmult = 1000.0 / sxmult;

       no_mapping=0;
       p = FontEncFromXLFD(entry->name.name, entry->name.length);

       if(p==0) {               /* XLFD does not specify an encoding */
           mapping=0;
           no_mapping=2;        /* ISO 8859-1 */
       }

       if(!strcmp(p, "adobe-fontspecific")) {
           mapping=0;
           no_mapping=1;        /* font's native encoding vector */
       }

       pFont->info.firstCol = 255;
       pFont->info.lastCol  = 0;

       if(!no_mapping) {
           mapping = FontEncMapFind(p, 
                                    FONT_ENCODING_POSTSCRIPT, -1, -1,
                                    fileName);
           if(!mapping)
               mapping = FontEncMapFind(p, 
                                        FONT_ENCODING_UNICODE, -1, -1,
                                        fileName);
           if(!mapping)
	       goto NoEncoding;
           else
               no_mapping=0;
       }

       for (i=0; i < 256; i++) {
               long h,w;
               long paddedW;
	       int j;
	       char *codename;

               if(no_mapping == 1) {
                   codename = FontP->fontInfoP[ENCODING].
                       value.data.arrayP[i].data.valueP;
                   len = FontP->fontInfoP[ENCODING].
                       value.data.arrayP[i].len;
               } else if(no_mapping) {
                   codename = unicodetoPSname(i);
                 len = codename ? strlen(codename) : 0;
               } else {
                 if(mapping->type == FONT_ENCODING_UNICODE) {
                     codename = unicodetoPSname(FontEncRecode(i, mapping));
                 } else
                     codename = FontEncName(i, mapping);
                 len=codename?strlen(codename):0;
               }

               /* Avoid multiply rasterising the undefined glyph */
               if(len==7 && !strncmp(codename, ".notdef", 7)) {
                   len=0;
                   codename=0;
               }

               /* But do rasterise it at least once */
               if(len==0) {
                   if(i==0) {
                       codename=".notdef";
                       len=7;
                   } else
                       continue;
               }

	       /* See if this character is in the list of ranges specified
		  in the XLFD name */
               if(i!=0) {
                   for (j = 0; j < vals->nranges; j++)
                       if (i >= minchar(vals->ranges[j]) &&
                           i <= maxchar(vals->ranges[j]))
                           break;

                   /* If not, don't realize it. */
                   if (vals->nranges && j == vals->nranges)
                       continue;
               }

               rc = 0;
               area = (struct region *)fontfcnB(S, (unsigned char *)codename,
                                                &len, &rc);
               if (rc < 0) {
                       rc = Type1ReturnCodeToXReturnCode(rc);
                       break;
               }
               else if (rc > 0)
                       continue;
 
               if (area == NULL)
                       continue;
 
	       if (pFont->info.firstCol > i)
		   pFont->info.firstCol = i;
	       if (pFont->info.lastCol < i)
		   pFont->info.lastCol = i;

               h       = area->ymax - area->ymin;
               w       = area->xmax - area->xmin;
               paddedW = PAD(w, pad);
 
               if (h > 0 && w > 0) {
                       size = h * paddedW / 8;
                       glyphs[i].bits = (char *)xalloc(size);
                       if (glyphs[i].bits == NULL) {
                               rc = AllocError;
                               break;
                       }
               }
               else {
		       size = 0;
                       h = w = 0;
                       area->xmin = area->xmax = 0;
                       area->ymax = area->ymax = 0;
               }
 
               glyphs[i].metrics.leftSideBearing  = area->xmin;
	       x1 = (double)(x0 = area->ending.x - area->origin.x);
	       y1 = (double)(area->ending.y - area->origin.y);
               glyphs[i].metrics.characterWidth   =
		   (x0 + (x0 > 0 ? FPHALF : -FPHALF)) / (1 << FRACTBITS);
               if (!glyphs[i].metrics.characterWidth && size == 0)
	       {
		   /* Zero size and zero extents: presumably caused by
		      the choice of transformation.  Let's create a
		      small bitmap so we're not mistaken for an undefined
		      character. */
		   h = w = 1;
		   size = paddedW = PAD(w, pad);
		   glyphs[i].bits = (char *)xalloc(size);
                   if (glyphs[i].bits == NULL) {
                       rc = AllocError;
                       break;
                   }
	       }
               glyphs[i].metrics.attributes =
		   NEARESTPEL((long)(hypot(x1, y1) * sxmult));
	       total_width += glyphs[i].metrics.attributes;
	       total_raw_width += abs((int)(INT16)glyphs[i].metrics.attributes);
	       count++;
               glyphs[i].metrics.rightSideBearing = w + area->xmin;
               glyphs[i].metrics.descent          = area->ymax - NEARESTPEL(area->origin.y);
               glyphs[i].metrics.ascent           = h - glyphs[i].metrics.descent;
 
 
               bzero(glyphs[i].bits, size);
               if (h > 0 && w > 0) {
                   fill(glyphs[i].bits, h, paddedW, area, byte, bit, wordsize );
               }
 
               Destroy(area);
       }
 NoEncoding:
       
       delmemory();
       xfree(pool);
 
       if (pFont->info.firstCol > pFont->info.lastCol)
       {
               xfree(type1);
               DestroyFontRec(pFont);
               return BadFontName;
       }
 
       if (i != 256) {
               for (i--; i >= 0; i--)
                       if (glyphs[i].bits != NULL)
                               xfree(glyphs[i].bits);
               xfree(type1);
               DestroyFontRec(pFont);
               return rc;
       }
       type1->pDefault    = NULL;
 
       pFont->format      = format;
 
       pFont->bit         = bit;
       pFont->byte        = byte;
       pFont->glyph       = glyph;
       pFont->scan        = scan;
 
       pFont->info.firstRow = 0;
       pFont->info.lastRow  = 0;
 
       pFont->get_metrics = Type1GetMetrics;
       pFont->get_glyphs  = Type1GetGlyphs;
       pFont->unload_font = Type1CloseFont;
       pFont->unload_glyphs = NULL;
       pFont->refcnt = 0;
 
       pFont->fontPrivate = (unsigned char *) type1;

       if (count)
       {
	   total_raw_width = (total_raw_width * 10 + count / 2) / count;
	   if (total_width < 0)
	   {
	       /* Predominant direction is R->L */
	       total_raw_width = -total_raw_width;
	   }
	   vals->width = (int)((double)total_raw_width *
			       vals->pixel_matrix[0] / 1000.0 +
			       (vals->pixel_matrix[0] > 0 ? .5 : -.5));
       }

       T1FillFontInfo(pFont, vals, fileName, entry->name.name, total_raw_width);
 
       *ppFont = pFont;
       return Successful;
}

#ifdef BUILDCID
unsigned int 
getCID(FontPtr pFont, unsigned int charcode)
{
    unsigned int cidcode = 0;
    Bool charvalid = FALSE;
    cidglyphs *cid;
    int i, j;
    unsigned int char_row, char_col, rangelo_row, rangelo_col, k;
    unsigned int rangehi_row, rangehi_col;
    spacerange *spacerangeP;
    cidrange *notdefrangeP, *cidrangeP;

    cid = (cidglyphs *)pFont->fontPrivate;

    if (cid == NULL)
        return cidcode;

    char_row = (charcode >> 8) & 0xff;
    char_col = charcode & 0xff;

    spacerangeP = CIDFontP->spacerangeP;
    for (i = 0; i < CIDFontP->spacerangecnt; i++) {
      for (j = 0; j < spacerangeP->rangecnt; j++) {
        rangelo_row =
          (spacerangeP->spacecode[j].srcCodeLo >> 8) & 0xff;
        rangelo_col = spacerangeP->spacecode[j].srcCodeLo & 0xff;
        rangehi_row =
          (spacerangeP->spacecode[j].srcCodeHi >> 8) & 0xff;
        rangehi_col = spacerangeP->spacecode[j].srcCodeHi & 0xff;
        if (char_row >= rangelo_row && char_row <= rangehi_row &&
            char_col >= rangelo_col && char_col <= rangehi_col) {
            charvalid = TRUE;
            break;
        }
      }
      if (charvalid) break;
      spacerangeP = spacerangeP->next;
    }

    if (charvalid) {
      charvalid = FALSE;
      cidrangeP = CIDFontP->cidrangeP;
      for (i = 0; i < CIDFontP->cidrangecnt; i++) {
        for (j = 0; j < cidrangeP->rangecnt; j++) {
          rangelo_row =
            (cidrangeP->range[j].srcCodeLo >> 8) & 0xff;
          rangelo_col = cidrangeP->range[j].srcCodeLo & 0xff;
          rangehi_row =
            (cidrangeP->range[j].srcCodeHi >> 8) & 0xff;
          rangehi_col = cidrangeP->range[j].srcCodeHi & 0xff;
          if (char_row >= rangelo_row && char_row <= rangehi_row &&
            char_col >= rangelo_col && char_col <= rangehi_col) {
            charvalid = TRUE;
            for (k = cidrangeP->range[j].srcCodeLo;
              k <= cidrangeP->range[j].srcCodeHi; k++) {
              if (k == charcode)
                cidcode = cidrangeP->range[j].dstCIDLo + k -
                  cidrangeP->range[j].srcCodeLo;
            }
            break;
          }
        }
        if (charvalid) break;
        cidrangeP = cidrangeP->next;
      }
    }

    if (charvalid) {
      charvalid = FALSE;
      notdefrangeP = CIDFontP->notdefrangeP;
      for (i = 0; i < CIDFontP->notdefrangecnt; i++) {
        for (j = 0; j < notdefrangeP->rangecnt; j++) {
          rangelo_row =
            (notdefrangeP->range[j].srcCodeLo >> 8) & 0xff;
          rangelo_col = notdefrangeP->range[j].srcCodeLo & 0xff;
          rangehi_row =
            (notdefrangeP->range[j].srcCodeHi >> 8) & 0xff;
          rangehi_col = notdefrangeP->range[j].srcCodeHi & 0xff;
          if (char_row >= rangelo_row && char_row <= rangehi_row &&
            char_col >= rangelo_col && char_col <= rangehi_col) {
            charvalid = TRUE;
            for (k = notdefrangeP->range[j].srcCodeLo;
              k <= notdefrangeP->range[j].srcCodeHi; k++) {
              if (k == charcode)
                /* the whole range is mapped to a single CID code */
                cidcode = notdefrangeP->range[j].dstCIDLo;
            }
            break;
          }
        }
        if (charvalid) break;
        notdefrangeP = notdefrangeP->next;
      }
    }

    /* If you specify a CMap that has more CIDs than a specified CIDFont, */
    /* the program could go beyond the number of entries in CIDMap. Make  */
    /* sure that that does not happen.                                    */
    if (cidcode < CIDFontP->CIDfontInfoP[CIDCOUNT].value.data.integer)
        return cidcode;
    else
        return 0;
}

static CharInfoPtr
CIDGetGlyph(FontPtr pFont, unsigned int charcode, CharInfoPtr pci)
{
    int  rc;
    CharInfoPtr cp = NULL;
    unsigned int cidcode;

    /* character code -> CID */
    cidcode = getCID(pFont, charcode);

    cp = CIDGetGlyphInfo(pFont, cidcode, pci, &rc);

    if (rc != Successful && cidcode) {
        cidcode = 0;
        cp = CIDGetGlyphInfo(pFont, cidcode, pci, &rc);
    }

    return cp;
}

int 
CIDGetGlyphs(FontPtr pFont, 
	     unsigned long count, 
	     unsigned char *chars, 
	     FontEncoding charEncoding, 
	     unsigned long *glyphCount, /* RETURN */
	     CharInfoPtr *glyphs)	/* RETURN */
{
    unsigned int code, char_row, char_col;
    CharInfoPtr *glyphsBase;
    register unsigned int c;
    CharInfoPtr pci;
    CharInfoPtr pDefault;
    cidglyphs *cid;
    register int firstCol;
    int rc = 0;
    int cid_valid = 0;

    cid = (cidglyphs *)pFont->fontPrivate;

    FontP = NULL;

    firstCol   = pFont->info.firstCol;
    pDefault   = cid->pDefault;
    glyphsBase = glyphs;

    switch (charEncoding) {

#define EXIST(pci) \
    ((pci)->metrics.attributes || \
     (pci)->metrics.ascent != -(pci)->metrics.descent || \
     (pci)->metrics.leftSideBearing != (pci)->metrics.rightSideBearing)

    case Linear8Bit:
    case TwoD8Bit:
        if (pFont->info.firstRow > 0)
            break;
        while (count--) {
            c = (*chars++);
            if (c >= firstCol && c <= pFont->info.lastCol) {
                code = c - firstCol;
                if (!(pci = (CharInfoRec *)cid->glyphs[code]) ||
                    ((long)pci->bits == CID_BITMAP_UNDEFINED)) {
                    /* load font if not already loaded */
                    if(!cid_valid) {
                        if(!CIDfontfcnA(cid->CIDFontName, cid->CMapName, &rc)) {                            FontP = NULL;
                            return Type1ReturnCodeToXReturnCode(rc);
                        }
                        cid_valid = 1;
                    }
                    pci = CIDGetGlyph(pFont, c, pci);
                }
                if (pci && EXIST(pci)) {
                    *glyphs++ = pci;
                    cid->glyphs[code] = pci;
                } else if (pDefault) {
                    *glyphs++ = pDefault;
                    cid->glyphs[code] = pDefault;
                }
            } else if (pDefault)
                *glyphs++ = pDefault;
        }
        break;
    case Linear16Bit:
        while (count--) {
            char_row = *chars++;
            char_col = *chars++;
            c = char_row << 8;
            c = (c | char_col);
            if (pFont->info.firstRow <= char_row && char_row <=
                pFont->info.lastRow && pFont->info.firstCol <= char_col &&
                char_col <= pFont->info.lastCol) {
                code = pFont->info.lastCol - pFont->info.firstCol + 1;
                char_row = char_row - pFont->info.firstRow;
                char_col = char_col - pFont->info.firstCol;
                code = char_row * code + char_col;
                if (!(pci = (CharInfoRec *)cid->glyphs[code]) ||
                    ((long)pci->bits == CID_BITMAP_UNDEFINED)) {
                    /* load font if not already loaded */
                    if(!cid_valid) {
                        if(!CIDfontfcnA(cid->CIDFontName, cid->CMapName, &rc)) {                            FontP = NULL;
                            return Type1ReturnCodeToXReturnCode(rc);
                        }
                        cid_valid = 1;
                    }
                    pci = CIDGetGlyph(pFont, c, pci);
                }
                if (pci && EXIST(pci)) {
                    *glyphs++ = pci;
                    cid->glyphs[code] = pci;
                } else if (pDefault) {
                    *glyphs++ = pDefault;
                    cid->glyphs[code] = pDefault;
                }
            } else if (pDefault)
                *glyphs++ = pDefault;
        }
        break;

    case TwoD16Bit:
        while (count--) {
            char_row = (*chars++);
            char_col = (*chars++);
            c = char_row << 8;
            c = (c | char_col);
            if (pFont->info.firstRow <= char_row && char_row <=
                pFont->info.lastRow && pFont->info.firstCol <= char_col &&
                char_col <= pFont->info.lastCol) {
                code = pFont->info.lastCol - pFont->info.firstCol + 1;
                char_row = char_row - pFont->info.firstRow;
                char_col = char_col - pFont->info.firstCol;
                code = char_row * code + char_col;
                if (!(pci = (CharInfoRec *)cid->glyphs[code]) ||
                    ((long)pci->bits == CID_BITMAP_UNDEFINED)) {
                    /* load font if not already loaded */
                    if(!cid_valid) {
                        if(!CIDfontfcnA(cid->CIDFontName, cid->CMapName, &rc)) {                            FontP = NULL;
                            return Type1ReturnCodeToXReturnCode(rc);
                        }
                        cid_valid = 1;
                    }
                    pci = CIDGetGlyph(pFont, c, pci);
                }
                if (pci && EXIST(pci)) {
                    *glyphs++ = pci;
                    cid->glyphs[code] = pci;
                } else if (pDefault) {
                    *glyphs++ = pDefault;
                    cid->glyphs[code] = pDefault;
                }
            } else if (pDefault)
                *glyphs++ = pDefault;
        }
        break;
    }
    *glyphCount = glyphs - glyphsBase;
    return Successful;

#undef EXIST
}
#endif
 
static int
Type1GetGlyphs(FontPtr pFont, 
	       unsigned long count, 
	       unsigned char *chars, 
	       FontEncoding charEncoding, 
	       unsigned long *glyphCount,  /* RETURN */
	       CharInfoPtr *glyphs)	   /* RETURN */
{
    unsigned int firstRow;
    unsigned int numRows;
    CharInfoPtr *glyphsBase;
    register unsigned int c;
    register CharInfoPtr pci;
    unsigned int r;
    CharInfoPtr pDefault;
    register struct type1font *type1Font;
    register int firstCol;
 
    type1Font  = (struct type1font *) pFont->fontPrivate;
    firstCol   = pFont->info.firstCol;
    pDefault   = type1Font->pDefault;
    glyphsBase = glyphs;
 
    switch (charEncoding) {

#define EXIST(pci) \
    ((pci)->metrics.attributes || \
     (pci)->metrics.ascent != -(pci)->metrics.descent || \
     (pci)->metrics.leftSideBearing != (pci)->metrics.rightSideBearing)
 
    case Linear8Bit:
    case TwoD8Bit:
        if (pFont->info.firstRow > 0)
            break;
        while (count--) {
                c = (*chars++);
                if (c >= firstCol &&
                       (pci = &type1Font->glyphs[c]) &&
		       EXIST(pci))
                    *glyphs++ = pci;
                else if (pDefault)
                    *glyphs++ = pDefault;
        }
        break;
    case Linear16Bit:
        while (count--) {
                c = *chars++ << 8;
                c = (c | *chars++);
                if (c < 256 && c >= firstCol &&
                        (pci = &type1Font->glyphs[c]) &&
			EXIST(pci))
                    *glyphs++ = pci;
                else if (pDefault)
                    *glyphs++ = pDefault;
        }
        break;
 
    case TwoD16Bit:
        firstRow = pFont->info.firstRow;
        numRows = pFont->info.lastRow - firstRow + 1;
        while (count--) {
            r = (*chars++) - firstRow;
            c = (*chars++);
            if (r < numRows && c < 256 && c >= firstCol &&
                    (pci = &type1Font->glyphs[(r << 8) + c]) &&
		    EXIST(pci))
                *glyphs++ = pci;
            else if (pDefault)
                *glyphs++ = pDefault;
        }
        break;
    }
    *glyphCount = glyphs - glyphsBase;
    return Successful;

#undef EXIST
}

#ifdef BUILDCID
static CharInfoRec nonExistantChar;

int
CIDGetMetrics(FontPtr pFont, 
	      unsigned long count, 
	      unsigned char *chars, 
	      FontEncoding charEncoding, 
	      unsigned long *glyphCount, /* RETURN */
	      xCharInfo **glyphs)	 /* RETURN */
{
    int         ret;
    cidglyphs *cid;
    CharInfoPtr oldDefault;
    char cidafmname[CID_PATH_MAX];
    char CIDFontName[CID_NAME_MAX];
    char *ptr;

    cid = (cidglyphs *)pFont->fontPrivate;

    strcpy(cidafmname, cid->CIDFontName);
    if (!(ptr = strrchr(cidafmname, '/')))
        return BadFontName;

    *ptr = '\0';

    strcpy(CIDFontName, ptr + 1);

    if (!(ptr = strrchr(cidafmname, '/')))
        return BadFontName;

    *ptr = '\0';

    strcat(cidafmname, "/AFM/");
    strcat(cidafmname, CIDFontName);

    strcat(cidafmname, ".afm");

    oldDefault = cid->pDefault;
    cid->pDefault = &nonExistantChar;

    ret = CIDGetAFM(pFont, count, chars, charEncoding, glyphCount, (CharInfoPtr
*)glyphs, cidafmname);
    if (ret != Successful)
        ret = CIDGetGlyphs(pFont, count, chars, charEncoding, glyphCount, 
			   (CharInfoPtr *)glyphs);

    *ptr = 0;
    cid->pDefault = oldDefault;
    return ret;
}
#endif

static int
Type1GetMetrics(FontPtr pFont, 
		unsigned long count, 
		unsigned char *chars, 
		FontEncoding charEncoding, 
		unsigned long *glyphCount, /* RETURN */
		xCharInfo **glyphs) 	   /* RETURN */
{
    static CharInfoRec nonExistantChar;
 
    int         ret;
    struct type1font *type1Font;
    CharInfoPtr oldDefault;
 
    type1Font = (struct type1font *) pFont->fontPrivate;
    oldDefault = type1Font->pDefault;
    type1Font->pDefault = &nonExistantChar;
    ret = Type1GetGlyphs(pFont, count, chars, charEncoding, glyphCount, (CharInfoPtr *) glyphs);
    type1Font->pDefault = oldDefault;
    return ret;
}

#ifdef BUILDCID
void 
CIDCloseFont(FontPtr pFont)
{
    register int i;
    cidglyphs *cid;
    int nchars;

    if (pFont) {

        cid = (cidglyphs *)pFont->fontPrivate;

        if (cid) {

            if (cid->CIDFontName && !strcmp(cid->CIDFontName, CurCIDFontName)
                 && cid->CMapName && !strcmp(cid->CMapName, CurCMapName)){
                 strcpy(CurCIDFontName, ""); /* initialize to none */
                 strcpy(CurCMapName, "");    /* initialize to none */
            }

            if (cid->CIDFontName)
                xfree(cid->CIDFontName);

            if (cid->CMapName)
                xfree(cid->CMapName);

            nchars = (pFont->info.lastRow - pFont->info.firstRow + 1) *
                (pFont->info.lastCol - pFont->info.firstCol + 1);

            for (i = 0; i < nchars; i++) {
                if (cid->glyphs[i] && (cid->glyphs[i] != &nonExistantChar)) {
                    if (cid->glyphs[i]->bits)
                        xfree(cid->glyphs[i]->bits);
                    xfree(cid->glyphs[i]);
                }
            }

            if (cid->glyphs)
                xfree(cid->glyphs);

            if (cid->AFMinfo)
                xfree(cid->AFMinfo);
#ifdef USE_MMAP
            if (cid->CIDdata)
               munmap(cid->CIDdata, cid->CIDsize);
#endif
            xfree(cid);
        }

        if (pFont->info.props)
            xfree(pFont->info.props);

        if (pFont->info.isStringProp)
            xfree(pFont->info.isStringProp);

        DestroyFontRec(pFont);
    }
}
#endif

void 
Type1CloseFont(FontPtr pFont)
{
       register int i;
       struct type1font *type1;
 
       type1 = (struct type1font *) pFont->fontPrivate;
       for (i=0; i < 256; i++)
               if (type1->glyphs[i].bits != NULL)
                        xfree(type1->glyphs[i].bits);
       xfree(type1);

       if (pFont->info.props)
	   xfree(pFont->info.props);

       if (pFont->info.isStringProp)
	   xfree(pFont->info.isStringProp);

       DestroyFontRec(pFont);
}

static void 
fill(char *dest,             /* destination bitmap                           */
     int h, int w,           /* dimensions of 'dest', w padded               */
     struct region *area,    /* region to write to 'dest'                    */
     int byte, int bit,      /* flags; LSBFirst or MSBFirst                  */
     int wordsize)           /* number of bits per word for LSB/MSB purposes */
{
       register struct edgelist *edge;  /* for looping through edges         */
       register char *p;     /* current scan line in 'dest'                  */
       register int y;       /* for looping through scans                    */
       register int wbytes = w / 8;  /* number of bytes in width             */
       register pel *leftP,*rightP;  /* pointers to X values, left and right */
       int xmin = area->xmin;  /* upper left X                               */
       int ymin = area->ymin;  /* upper left Y                               */
 
       for (edge = area->anchor; VALIDEDGE(edge); edge = edge->link->link) {
 
               p = dest + (edge->ymin - ymin) * wbytes;
               leftP = edge->xvalues;
               rightP = edge->link->xvalues;
 
               for (y = edge->ymin; y < edge->ymax; y++) {
                       fillrun(p, *leftP++ - xmin, *rightP++ - xmin, bit);
                       p += wbytes;
               }
       }
/*
Now, as an afterthought, we'll go reorganize if odd byte order requires
it:
*/
       if (byte == LSBFirst && wordsize != 8) {
               register int i;
 
               switch (wordsize) {
                   case 16:
                   {
                       register unsigned short data,*p;
 
                       p = (unsigned short *) dest;
 
                       for (i = h * w /16; --i >= 0;) {
                               data = *p;
                               *p++ = (data << 8) + (data >> 8);
                       }
                       break;
                   }
                   case 64:
                   case 32:
                   {
                       register unsigned long data,*p;
 
                       p = (unsigned long *) dest;
 
                       for (i = h * w / 32; --i >= 0;) {
                               data = *p;
                               *p++ = (data << 24) + (data >> 24)
                                      + (0xFF00 & (data >> 8))
                                      + (0xFF0000 & (data << 8));
                       }
                       if (wordsize == 64) {
 
                               p = (unsigned long *) dest;
 
                               for (i = h * w / 64; --i >= 0;) {
                                       data = *p++;
                                       p[-1] = p[0];
                                       *p++ = data;
                               }
                       }
                       break;
                   }
                   default:
                       Abort("xiFill: unknown format");
               }
       }
 
}
 
#define  ALLONES  0xFF
 
static void 
fillrun(char *p,             /* address of this scan line                    */
	pel x0, pel x1,      /* left and right X                             */
	int bit)             /* format:  LSBFirst or MSBFirst                */
{
       register int startmask,endmask;  /* bits to set in first and last char*/
       register int middle;  /* number of chars between start and end + 1    */
 
       if (x1 <= x0)
               return;
       middle = x1/8 - x0/8;
       p += x0/8;
       x0 &= 7;  x1 &= 7;
       if (bit == LSBFirst) {
               startmask = ALLONES << x0;
               endmask = ~(ALLONES << x1);
       }
       else {
               startmask = ALLONES >> x0;
               endmask = ~(ALLONES >> x1);
       }
       if (middle == 0)
               *p++ |= startmask & endmask;
       else {
               *p++ |= startmask;
               while (--middle > 0)
                       *p++ = (char)ALLONES;
               *p |= endmask;
       }
}
 
#define CAPABILITIES (CAP_MATRIX | CAP_CHARSUBSETTING)

#ifdef BUILDCID
FontRendererRec CIDRendererInfo[] = {
  { ".cid", 4, NULL, CIDOpenScalable,
        NULL, CIDGetInfoScalable, 0, CAPABILITIES }
};
#endif
 
#ifdef BUILDCID
FontRendererRec Type1RendererInfo[] = {
#else
static FontRendererRec renderers[] = {
#endif
  { ".pfa", 4, NULL, Type1OpenScalable,
        NULL, Type1GetInfoScalable, 0, CAPABILITIES },
  { ".pfb", 4, NULL, Type1OpenScalable,
        NULL, Type1GetInfoScalable, 0, CAPABILITIES }
};

#ifdef BUILDCID
void 
CIDRegisterFontFileFunctions(void)
{
    int i;

    Type1InitStdProps();
    for (i=0; i < sizeof(CIDRendererInfo) / sizeof(FontRendererRec); i++)
            FontFileRegisterRenderer(&CIDRendererInfo[i]);
}
#endif
 
void
Type1RegisterFontFileFunctions(void)
{
    int i;
 
#ifdef BUILDCID
    Type1InitStdProps();
    for (i=0; i < sizeof(Type1RendererInfo) / sizeof(FontRendererRec); i++)
            FontFilePriorityRegisterRenderer(&Type1RendererInfo[i], -10);
#else
    T1InitStdProps();
    for (i=0; i < sizeof(renderers) / sizeof(FontRendererRec); i++)
            FontFilePriorityRegisterRenderer(&renderers[i], -10);
#endif
}

int 
Type1ReturnCodeToXReturnCode(int rc)
{
    switch(rc) {
    case SCAN_OK:
	return Successful;
    case SCAN_FILE_EOF:
	/* fall through to BadFontFormat */
    case SCAN_ERROR:
	return BadFontFormat;
    case SCAN_OUT_OF_MEMORY:
	return AllocError;
    case SCAN_FILE_OPEN_ERROR:
	return BadFontName;
    case SCAN_TRUE:
    case SCAN_FALSE:
    case SCAN_END:
	/* fall through */
    default:
	/* this should not happen */
#ifdef BUILDCID
        ErrorF("Font return code cannot be converted to X return code: %d\n", rc);
#else
	ErrorF("Type1 return code not convertable to X return code: %d\n", rc);
#endif
	return rc;
    }
}

#ifdef BUILDCID
CharInfoPtr 
CIDRenderGlyph(FontPtr pFont, psobj *charstringP, psobj *subarrayP,
	       struct blues_struct *bluesP, CharInfoPtr pci, int *mode)
{
       int         bit,
                   byte,
                   glyph,
                   scan,
                   image;
       int pad,wordsize;     /* scan & image in bits                         */
       long *pool;           /* memory pool for ximager objects              */
       int size;             /* for memory size calculations                 */
       struct XYspace *S;    /* coordinate space for character               */
       struct region *area;
       CharInfoRec *glyphs;
       int len, rc;
       long x0;
       double x1, y1, t1 = .001, t2 = 0.0, t3 = 0.0, t4 = .001;
       double sxmult;
       long h,w;
       long paddedW;
       cidglyphs *cid;
       fsBitmapFormat      format = 0;
       fsBitmapFormatMask  fmask = 0;

       cid = (cidglyphs *)pFont->fontPrivate;

       /* set up default values */
       FontDefaultFormat(&bit, &byte, &glyph, &scan);
       /* get any changes made from above */
       rc = CheckFSFormat(format, fmask, &bit, &byte, &scan, &glyph, &image);
       if (rc != Successful) {
               *mode = rc;
               return(NULL);
       }

       pad                = glyph * 8;
       wordsize           = scan * 8;

#define  PAD(bits, pad)  (((bits)+(pad)-1)&-(pad))

       /* heuristic for "maximum" size of pool we'll need: */
       size = 200000 + 600 *
              (int)hypot(cid->pixel_matrix[2], cid->pixel_matrix[3])
              * sizeof(short);
       if (size < 0 || NULL == (pool = (long *) xalloc(size))) {
              *mode = AllocError;
              return(NULL);
       }

       addmemory(pool, size);

       if (pci && (long)pci->bits == CID_BITMAP_UNDEFINED)
           glyphs = pci;
       else {
           if (!(glyphs = (CharInfoRec *)xalloc(sizeof(CharInfoRec)))) {
             delmemory();
             xfree(pool);
             *mode = AllocError;
             return(NULL);
           }
           bzero(glyphs, sizeof(CharInfoRec));
       }

       S = (struct XYspace *) t1_Transform((struct xobject *)IDENTITY, 
					   t1, t2, t3, t4);

       S = (struct XYspace *) Permanent(t1_Transform((struct xobject *)S,
						     cid->pixel_matrix[0],
						     -cid->pixel_matrix[1],
						     cid->pixel_matrix[2],
						     -cid->pixel_matrix[3]));

       /* multiplier for computation of raw values */
       sxmult = hypot(cid->pixel_matrix[0], cid->pixel_matrix[1]);
       if (sxmult > EPS) sxmult = 1000.0 / sxmult;

       rc = 0;
       area = (struct region *)CIDfontfcnC(S, charstringP, subarrayP, bluesP, 
					   &len, &rc);
       if (rc < 0 || area == NULL) {
         delmemory();
         xfree(pool);
         if (pci != glyphs) xfree(glyphs);
         *mode = Type1ReturnCodeToXReturnCode(rc);
         return(NULL);
       }

       h       = area->ymax - area->ymin;
       w       = area->xmax - area->xmin;
       paddedW = PAD(w, pad);

       if (h > 0 && w > 0) {
               size = h * paddedW / 8;
               glyphs[0].bits = (char *)xalloc(size);
               if (glyphs[0].bits == NULL) {
                       Destroy(area);
                       delmemory();
                       xfree(pool);
                       if (pci != glyphs) xfree(glyphs);
                       *mode = AllocError;
                       return(NULL);
               }
               bzero(glyphs[0].bits, size);
       }
       else {
               size = 0;
               h = w = 0;
               area->xmin = area->xmax = 0;
               area->ymax = area->ymax = 0;
               glyphs[0].bits = NULL;
       }

       glyphs[0].metrics.leftSideBearing  = area->xmin;
       x1 = (double)(x0 = area->ending.x - area->origin.x);
       y1 = (double)(area->ending.y - area->origin.y);
       glyphs[0].metrics.characterWidth   =
           (x0 + (x0 > 0 ? FPHALF : -FPHALF)) / (1 << FRACTBITS);
       if (!glyphs[0].metrics.characterWidth && size == 0)
       {
           /* Zero size and zero extents: presumably caused by
              the choice of transformation.  Let's create a
              small bitmap so we're not mistaken for an undefined
              character. */
           h = w = 1;
           size = paddedW = PAD(w, pad);
           glyphs[0].bits = (char *)xalloc(size);
           if (glyphs[0].bits == NULL) {
               Destroy(area);
               delmemory();
               xfree(pool);
               if (pci != glyphs) xfree(glyphs);
               *mode = AllocError;
               return(NULL);
           }
           bzero(glyphs[0].bits, size);
       }
       glyphs[0].metrics.attributes =
           NEARESTPEL((long)(hypot(x1, y1) * sxmult));
       glyphs[0].metrics.rightSideBearing = w + area->xmin;
       glyphs[0].metrics.descent          = area->ymax - NEARESTPEL(area->origin.y);
       glyphs[0].metrics.ascent           = h - glyphs[0].metrics.descent;

       if (h > 0 && w > 0)
           fill(glyphs[0].bits, h, paddedW, area, byte, bit, wordsize);
       Destroy(area);
       delmemory();
       xfree(pool);
       *mode = Successful;
       return(glyphs);
}
#endif