summaryrefslogtreecommitdiff
path: root/Build/source/texk/dvipdfm-x/spc_pdfm.c
blob: f19d9a081cb041cf9568008b6d825339e03bb22f (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
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
/* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.

    Copyright (C) 2007-2019 by Jin-Hwan Cho and Shunsaku Hirata,
    the dvipdfmx project team.
    
    Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <ctype.h>

#include "system.h"
#include "mem.h"
#include "error.h"
#include "mfileio.h"

#include "numbers.h"

#include "fontmap.h"
#include "dpxfile.h"
#include "dpxutil.h"
#include "dpxconf.h"

#include "unicode.h"

#include "pdfobj.h"
#include "pdfparse.h"

#include "pdfdoc.h"

#include "pdfximage.h"
#include "pdfdraw.h"
#include "pdfcolor.h"
#include "pdfdev.h"

#include "specials.h"

#include "spc_util.h"
#include "spc_pdfm.h"

#include "dvipdfmx.h"


/* PLEASE REMOVE THIS */
struct resource_map {
  int   type;
  int   res_id;
};

struct tounicode {
  int       cmap_id;
  int       unescape_backslash;
  pdf_obj  *taintkeys; /* An array of PDF names. */
};

struct spc_pdf_
{
   pdf_obj          *annot_dict;   /* pending annotation dict       */
   int               lowest_level; /* current min level of outlines */
   struct ht_table  *resourcemap;  /* see remark below (somewhere)  */
   struct tounicode  cd;           /* For to-UTF16-BE conversion :( */
   pdf_obj          *pageresources; /* Add to all page resource dict */
};

static struct spc_pdf_  _pdf_stat = {
  NULL,
  255,
  NULL,
  { -1, 0, NULL },
  NULL
};

/* PLEASE REMOVE THIS */
static void
hval_free (void *vp)
{
  RELEASE(vp);
}


static int
addresource (struct spc_pdf_ *sd, const char *ident, int res_id)
{
  struct resource_map *r;

  if (!ident || res_id < 0)
    return  -1;

  r = NEW(1, struct resource_map);
  r->type   = 0; /* unused */
  r->res_id = res_id;

  ht_append_table(sd->resourcemap, ident, strlen(ident), r);
  spc_push_object(ident, pdf_ximage_get_reference(res_id));

  return 0;
}

static int
findresource (struct spc_pdf_ *sd, const char *ident)
{
  struct resource_map *r;

  if (!ident)
    return  -1;

  r = ht_lookup_table(sd->resourcemap, ident, strlen(ident));

  return (r ? r->res_id : -1);
}


static int
spc_handler_pdfm__init (void *dp)
{
  struct spc_pdf_ *sd = dp;
  /* The folllowing dictionary entry keys are considered as keys for
   * text strings. Be sure that string object is NOT always a text string.
   */
  static const char *default_taintkeys[] = {
    "Title",   "Author",   "Subject", "Keywords",
    "Creator", "Producer", "Contents", "Subj",
    "TU",      "T",        "TM",        NULL /* EOD */
  };
  int  i;

  sd->annot_dict   = NULL;
  sd->lowest_level = 255;
  sd->resourcemap  = NEW(1, struct ht_table);
  ht_init_table(sd->resourcemap, hval_free);

  sd->cd.taintkeys = pdf_new_array();
  for (i = 0; default_taintkeys[i] != NULL; i++) {
    pdf_add_array(sd->cd.taintkeys,
		  pdf_new_name(default_taintkeys[i]));
  }
  sd->pageresources = NULL;

  return 0;
}

static int
spc_handler_pdfm__clean (void *dp)
{
  struct spc_pdf_ *sd = dp;

  if (sd->annot_dict) {
    WARN("Unbalanced bann and eann found.");
    pdf_release_obj(sd->annot_dict);
  }
  sd->lowest_level = 255;
  sd->annot_dict   = NULL;
  if (sd->resourcemap) {
    ht_clear_table(sd->resourcemap);
    RELEASE(sd->resourcemap);
  }
  sd->resourcemap = NULL;

  if (sd->cd.taintkeys)
    pdf_release_obj(sd->cd.taintkeys);
  sd->cd.taintkeys = NULL;
  if (sd->pageresources)
    pdf_release_obj(sd->pageresources);
  sd->pageresources = NULL;

  return 0;
}


int
spc_pdfm_at_begin_document (void)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  return  spc_handler_pdfm__init(sd);
}

int
spc_pdfm_at_end_document (void)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  return  spc_handler_pdfm__clean(sd);
}

static
int putpageresources (pdf_obj *kp, pdf_obj *vp, void *dp)
{
  char *resource_name;

  ASSERT(kp && vp);

  resource_name = pdf_name_value(kp);
  pdf_doc_add_page_resource(dp, resource_name, pdf_ref_obj(vp));

  return 0;
}

static
int forallresourcecategory (pdf_obj *kp, pdf_obj *vp, void *dp)
{
  char *category;

  ASSERT(kp && vp);

  category = pdf_name_value(kp);
  if (!PDF_OBJ_DICTTYPE(vp)) {
    return -1;
  }

  return pdf_foreach_dict(vp, putpageresources, category);
}

int
spc_pdfm_at_end_page (void)
{
  struct spc_pdf_ *sd = &_pdf_stat;

  if (sd->pageresources) {
    pdf_foreach_dict(sd->pageresources, forallresourcecategory, NULL);
  }

  return 0;
}

/* Dvipdfm specials */
static int
spc_handler_pdfm_bop (struct spc_env *spe, struct spc_arg *args)
{
  if (args->curptr < args->endptr) {
    pdf_doc_set_bop_content(args->curptr,
			    (int) (args->endptr - args->curptr));
  }

  args->curptr = args->endptr;

  return 0;
}

static int
spc_handler_pdfm_eop (struct spc_env *spe, struct spc_arg *args)
{
  if (args->curptr < args->endptr) {
    pdf_doc_set_eop_content(args->curptr,
			    (int) (args->endptr - args->curptr));
  }

  args->curptr = args->endptr;

  return 0;
}

#define streamfiltered(o) \
  (pdf_lookup_dict(pdf_stream_dict((o)), "Filter") ? 1 : 0)

/* Why should we have this kind of things? */
static int
safeputresdent (pdf_obj *kp, pdf_obj *vp, void *dp)
{
  char  *key;

  ASSERT(kp && vp && dp);

  key = pdf_name_value(kp);
  if (pdf_lookup_dict(dp, key))
    WARN("Object \"%s\" already defined in dict! (ignored)", key);
  else {
    pdf_add_dict(dp,
                 pdf_link_obj(kp), pdf_link_obj(vp));
  }
  return 0;
}

#ifndef pdf_obj_isaref
#define pdf_obj_isaref(o) (pdf_obj_typeof((o)) == PDF_INDIRECT)
#endif

static int
safeputresdict (pdf_obj *kp, pdf_obj *vp, void *dp)
{
  char    *key;
  pdf_obj *dict;

  ASSERT(kp && vp && dp);

  key  = pdf_name_value(kp);
  dict = pdf_lookup_dict(dp, key);

  if (pdf_obj_isaref(vp)) {
    pdf_add_dict(dp, pdf_new_name(key), pdf_link_obj(vp));
  } else if (pdf_obj_typeof(vp) == PDF_DICT) {
    if (dict)
      pdf_foreach_dict(vp, safeputresdent, dict);
    else {
      pdf_add_dict(dp, pdf_new_name(key), pdf_link_obj(vp));
    }
  } else {
    WARN("Invalid type (not DICT) for page/form resource dict entry: key=\"%s\"", key);
    return  -1;
  }

  return 0;
}


/* Think what happens if you do
 *
 *  pdf:put @resources << /Font << >> >>
 * 
 */
static int
spc_handler_pdfm_put (struct spc_env *spe, struct spc_arg *ap)
{
  pdf_obj  *obj1, *obj2; /* put obj2 into obj1 */
  char     *ident;
  int       error = 0;

  skip_white(&ap->curptr, ap->endptr);

  ident = parse_opt_ident(&ap->curptr, ap->endptr);
  if (!ident) {
    spc_warn(spe, "Missing object identifier.");
    return  -1;
  }
  obj1 = spc_lookup_object(ident);
  if (!obj1) {
    spc_warn(spe, "Specified object not exist: %s", ident);
    RELEASE(ident);
    return  -1;
  }
  skip_white(&ap->curptr, ap->endptr);

  obj2 = parse_pdf_object(&ap->curptr, ap->endptr, NULL);
  if (!obj2) {
    spc_warn(spe, "Missing (an) object(s) to put into \"%s\"!", ident);
    RELEASE(ident);
    return  -1;
  }

  switch (pdf_obj_typeof(obj1)) {
  case  PDF_DICT:
    if (pdf_obj_typeof(obj2) != PDF_DICT) {
      spc_warn(spe, "Inconsistent object type for \"put\" (expecting DICT): %s", ident);
      error = -1;
    } else {
      if (!strcmp(ident, "resources"))
        error = pdf_foreach_dict(obj2, safeputresdict, obj1);
      else {
        pdf_merge_dict(obj1, obj2);
      }
    }
    break;

  case  PDF_STREAM:
    if (pdf_obj_typeof(obj2) == PDF_DICT)
      pdf_merge_dict(pdf_stream_dict(obj1), obj2);
    else if (pdf_obj_typeof(obj2) == PDF_STREAM)
#if  0
    {
      pdf_merge_dict(pdf_stream_dict(obj1), pdf_stream_dict(obj2));
      pdf_add_stream(obj1, pdf_stream_dataptr(obj2), pdf_stream_length(obj2));
    }
#else
    {
      spc_warn(spe, "\"put\" operation not supported for STREAM <- STREAM: %s", ident);
      error = -1;
    }
#endif
    else {
      spc_warn(spe, "Invalid type: expecting a DICT or STREAM: %s", ident);
      error = -1;
    }
    break;

  case PDF_ARRAY:
    /* dvipdfm */
    pdf_add_array(obj1, pdf_link_obj(obj2));
    while (ap->curptr < ap->endptr) {
      pdf_obj *obj3 = parse_pdf_object(&ap->curptr, ap->endptr, NULL);
      if (!obj3)
	break;
      pdf_add_array(obj1, obj3);
      skip_white(&ap->curptr, ap->endptr);
    }
    break;

  default:
    spc_warn(spe, "Can't \"put\" object into non-DICT/STREAM/ARRAY type object: %s", ident);
    error = -1;
    break;
  }
  pdf_release_obj(obj2);
  RELEASE(ident);

  return  error;
}


/* For pdf:tounicode support
 * This feature is provided for convenience. TeX can't do
 * input encoding conversion.
 */
#include "cmap.h"

static int
reencodestring (CMap *cmap, pdf_obj *instring)
{
#define WBUF_SIZE 4096
  unsigned char  wbuf[WBUF_SIZE];
  unsigned char *obufcur;
  const unsigned char *inbufcur;
  int inbufleft, obufleft;

  if (!cmap || !instring)
    return 0;

  inbufleft = pdf_string_length(instring);
  inbufcur  = pdf_string_value (instring);

  wbuf[0]  = 0xfe;
  wbuf[1]  = 0xff;
  obufcur  = wbuf + 2;
  obufleft = WBUF_SIZE - 2;

  CMap_decode(cmap,
	      &inbufcur, &inbufleft,
	      &obufcur, &obufleft);

  if (inbufleft > 0) {
    return  -1;
  }

  pdf_set_string(instring, wbuf, WBUF_SIZE - obufleft);

  return 0;
}

static int
maybe_reencode_utf8(pdf_obj *instring)
{
  unsigned char* inbuf;
  int            inlen;
  int            non_ascii = 0;
  unsigned char* cp;
  unsigned char* op;
  unsigned char  wbuf[WBUF_SIZE];

  if (!instring)
    return 0;

  inlen = pdf_string_length(instring);
  inbuf = pdf_string_value(instring);

  /* check if the input string is strictly ASCII */
  for (cp = inbuf; cp < inbuf + inlen; ++cp) {
    if (*cp > 127) {
      non_ascii = 1;
    }
  }
  if (non_ascii == 0)
    return 0; /* no need to reencode ASCII strings */

  /* Check if the input string is valid UTF8 string
   * This routine may be called against non-text strings.
   * We need to re-encode string only when string is a text string
   * endcoded in UTF8.
   */
  if (!UC_UTF8_is_valid_string(inbuf, inbuf + inlen))
    return 0;
  else if (inbuf[0] == 0xfe && inbuf[1] == 0xff &&
      UC_UTF16BE_is_valid_string(inbuf + 2, inbuf + inlen))
    return 0; /* no need to reencode UTF16BE with BOM */

  cp = inbuf;
  op = wbuf;
  *op++ = 0xfe;
  *op++ = 0xff;
  while (cp < inbuf + inlen) {
    int32_t usv;
    int     len;

    usv = UC_UTF8_decode_char((const unsigned char **)&cp, inbuf + inlen);
    if (!UC_is_valid(usv))
      return -1; /* out of valid Unicode range, give up (redundant) */
    len = UC_UTF16BE_encode_char(usv, &op, wbuf + WBUF_SIZE);
    if (len == 0)
      return -1;
  }

  pdf_set_string(instring, wbuf, op - wbuf);

  return 0;
}

/* The purpose of this routine is to check if given string object is
 * surely an object for *text* strings. It does not do a complete check
 * but does a quick check. Please add entries for taintkeys if you have found
 * additional dictionary entries which is considered as a text string.
 */
static int
needreencode (pdf_obj *kp, pdf_obj *vp, struct tounicode *cd)
{
  int      r = 0, i;
  pdf_obj *tk;

  ASSERT( cd && cd->taintkeys );
  ASSERT( pdf_obj_typeof(kp) == PDF_NAME );
  ASSERT( pdf_obj_typeof(vp) == PDF_STRING );

  for (i = 0; i < pdf_array_length(cd->taintkeys); i++) {
    tk = pdf_get_array(cd->taintkeys, i);
    ASSERT( tk && pdf_obj_typeof(tk) == PDF_NAME );
    if (!strcmp(pdf_name_value(kp), pdf_name_value(tk))) {
      r = 1;
      break;
    }
  }
  if (r) {
    /* Check UTF-16BE BOM. */
    if (pdf_string_length(vp) >= 2 &&
        !memcmp(pdf_string_value(vp), "\xfe\xff", 2))
      r = 0;
  }

  return  r;
}

static int
modstrings (pdf_obj *kp, pdf_obj *vp, void *dp)
{
  int               r = 0; /* continue */
  struct tounicode *cd = dp;

  ASSERT( pdf_obj_typeof(kp) == PDF_NAME );

  switch (pdf_obj_typeof(vp)) {
  case  PDF_STRING:
    if (cd && cd->cmap_id >= 0 && cd->taintkeys) {
      CMap *cmap = CMap_cache_get(cd->cmap_id);
      if (needreencode(kp, vp, cd))
        r = reencodestring(cmap, vp);
    } else if ((dpx_conf.compat_mode == dpx_mode_xdv_mode) && cd && cd->taintkeys) {
      /* Please fix this... PDF string object is not always a text string.
       * needreencode() is assumed to do a simple check if given string
       * object is actually a text string.
       */
      if (needreencode(kp, vp, cd))
        r = maybe_reencode_utf8(vp);
    }
    if (r < 0) /* error occured... */
      WARN("Failed to convert input string to UTF16...");
    break;
  case  PDF_DICT:
    r = pdf_foreach_dict(vp, modstrings, dp);
    break;
  case  PDF_STREAM:
    r = pdf_foreach_dict(pdf_stream_dict(vp), modstrings, dp);
    break;
  }

  return  r;
}

static pdf_obj *
parse_pdf_dict_with_tounicode (const char **pp, const char *endptr, struct tounicode *cd)
{
  pdf_obj  *dict;

  /* disable this test for XDV files, as we do UTF8 reencoding with no cmap */
  if ((dpx_conf.compat_mode != dpx_mode_xdv_mode) && cd->cmap_id < 0)
    return  parse_pdf_dict(pp, endptr, NULL);

  /* :( */
  if (cd && cd->unescape_backslash) 
    dict = parse_pdf_tainted_dict(pp, endptr);
  else {
    dict = parse_pdf_dict(pp, endptr, NULL);
  }
  if (dict)
    pdf_foreach_dict(dict, modstrings, cd);

  return  dict;
}

static int
spc_handler_pdfm_annot (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  pdf_obj       *annot_dict;
  pdf_rect       rect;
  char          *ident = NULL;
  pdf_coord      cp;
  transform_info ti;

  skip_white(&args->curptr, args->endptr);
  if (args->curptr[0] == '@') {
    ident = parse_opt_ident(&args->curptr, args->endptr);
    skip_white(&args->curptr, args->endptr);
  }

  transform_info_clear(&ti);
  if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
    if (ident)
      RELEASE(ident);
    return  -1;
  }

  if ((ti.flags & INFO_HAS_USER_BBOX) &&
      ((ti.flags & INFO_HAS_WIDTH) || (ti.flags & INFO_HAS_HEIGHT))) {
    spc_warn(spe, "You can't specify both bbox and width/height.");
    if (ident)
      RELEASE(ident);
    return  -1;
  }

  annot_dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
  if (!annot_dict) {
    spc_warn(spe, "Could not find dictionary object.");
    if (ident)
      RELEASE(ident);
    return  -1;
  } else if (!PDF_OBJ_DICTTYPE(annot_dict)) {
    spc_warn(spe, "Invalid type: not dictionary object.");
    if (ident)
      RELEASE(ident);
    pdf_release_obj(annot_dict);
    return  -1;
  }

  cp.x = spe->x_user; cp.y = spe->y_user;
  pdf_dev_transform(&cp, NULL);
  if (ti.flags & INFO_HAS_USER_BBOX) {
    rect.llx = ti.bbox.llx + cp.x;
    rect.lly = ti.bbox.lly + cp.y;
    rect.urx = ti.bbox.urx + cp.x;
    rect.ury = ti.bbox.ury + cp.y;
  } else {
    rect.llx = cp.x;
    rect.lly = cp.y - spe->mag * ti.depth;
    rect.urx = cp.x + spe->mag * ti.width;
    rect.ury = cp.y + spe->mag * ti.height;
  }

  /* Order is important... */
  if (ident)
    spc_push_object(ident, pdf_link_obj(annot_dict));
  /* Add this reference. */
  pdf_doc_add_annot(pdf_doc_current_page_number(), &rect, annot_dict, 1);

  if (ident) {
    spc_flush_object(ident);
    RELEASE(ident);
  }
  pdf_release_obj(annot_dict);

  return 0;
}

/* NOTE: This can't have ident. See "Dvipdfm User's Manual". */
static int
spc_handler_pdfm_bann (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  int    error = 0;

  if (sd->annot_dict) {
    spc_warn(spe, "Can't begin an annotation when one is pending.");
    return  -1;
  }

  skip_white(&args->curptr, args->endptr);

  sd->annot_dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
  if (!sd->annot_dict) {
    spc_warn(spe, "Ignoring annotation with invalid dictionary.");
    return  -1;
  } else if (!PDF_OBJ_DICTTYPE(sd->annot_dict)) {
    spc_warn(spe, "Invalid type: not a dictionary object.");
    pdf_release_obj(sd->annot_dict);
    sd->annot_dict = NULL;
    return  -1;
  }

  error = spc_begin_annot(spe, sd->annot_dict);

  return  error;
}

static int
spc_handler_pdfm_eann (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  int    error = 0;

  if (!sd->annot_dict) {
    spc_warn(spe, "Tried to end an annotation without starting one!");
    return  -1;
  }

  error = spc_end_annot(spe);

  pdf_release_obj(sd->annot_dict);
  sd->annot_dict = NULL;

  return  error;
}


/* Color:.... */
static int
spc_handler_pdfm_bcolor (struct spc_env *spe, struct spc_arg *ap)
{
  int       error;
  pdf_color fc, sc;
  pdf_color *pfc, *psc;

  pdf_color_get_current(&psc, &pfc);
  error = spc_util_read_pdfcolor(spe, &fc, ap, pfc);
  if (!error) {
    if (ap->curptr < ap->endptr) {
      error = spc_util_read_pdfcolor(spe, &sc, ap, psc);
    } else {
      pdf_color_copycolor(&sc, &fc);
    }
  }

  if (error)
    spc_warn(spe, "Invalid color specification?");
  else {
    pdf_color_push(&sc, &fc); /* save currentcolor */
  }

  return  error;
}

/*
 * This special changes the current color without clearing the color stack.
 * It therefore differs from "color rgb 1 0 0".
 */
static int
spc_handler_pdfm_scolor (struct spc_env *spe, struct spc_arg *ap)
{
  int       error;
  pdf_color fc, sc;
  pdf_color *pfc, *psc;

  pdf_color_get_current(&psc, &pfc);
  error = spc_util_read_pdfcolor(spe, &fc, ap, pfc);
  if (!error) {
    if (ap->curptr < ap->endptr) {
      error = spc_util_read_pdfcolor(spe, &sc, ap, psc);
    } else {
      pdf_color_copycolor(&sc, &fc);
    }
  }

  if (error)
    spc_warn(spe, "Invalid color specification?");
  else
    pdf_color_set(&sc, &fc);

  return  error;
}

static int
spc_handler_pdfm_ecolor (struct spc_env *spe, struct spc_arg *args)
{
  pdf_color_pop();
  return 0;
}


static int
spc_handler_pdfm_btrans (struct spc_env *spe, struct spc_arg *args)
{
  pdf_tmatrix     M;
  transform_info  ti;

  transform_info_clear(&ti);
  if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
    return -1;
  }

  /* Create transformation matrix */
  pdf_copymatrix(&M, &(ti.matrix));
  M.e += ((1.0 - M.a) * spe->x_user - M.c * spe->y_user);
  M.f += ((1.0 - M.d) * spe->y_user - M.b * spe->x_user);

  pdf_dev_gsave();
  pdf_dev_concat(&M);

  return 0;
}

static int
spc_handler_pdfm_etrans (struct spc_env *spe, struct spc_arg *args)
{
  pdf_dev_grestore();

  /*
   * Unfortunately, the following line is necessary in case
   * of a color change inside of the save/restore pair.
   * (Font changes are automatically corrected by pdf_dev_grestore().)
   * Anything that was done there must be redone, so in effect,
   * we make no assumptions about what fonts. We act like we are
   * starting a new page.
   */
  pdf_dev_reset_color(0);

  return 0;
}

static int
spc_handler_pdfm_outline (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  pdf_obj   *item_dict, *tmp;
  int        level, is_open = -1;
  int        current_depth;

  skip_white(&args->curptr, args->endptr);

  /*
   * pdf:outline is extended to support open/close feature
   *
   * pdf:outline 1 ... (as DVIPDFM)
   * pdf:outline [] 1 ... (open bookmark)
   * pdf:outline [-] 1 ... (closed bookmark)
   */
  if (args->curptr+3 < args->endptr && *args->curptr == '[') {
    args->curptr++;
    if (*args->curptr == '-') {
      args->curptr++;
    } else {
      is_open = 1;
    }
    args->curptr++;
  }
  skip_white(&args->curptr, args->endptr);

  tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!tmp) {
    spc_warn(spe, "Missing number for outline item depth.");
    return  -1;
  } else if (!PDF_OBJ_NUMBERTYPE(tmp)) {
    pdf_release_obj(tmp);
    spc_warn(spe, "Expecting number for outline item depth.");
    return  -1;
  }

  item_dict = NULL;

  level = (int) pdf_number_value(tmp);
  pdf_release_obj(tmp);

  /* What is this? Starting at level 3 and can go down to level 1?
   *
   * Here is the original comment:
   *  Make sure we know where the starting level is
   *
   * NOTE: added
   *  We need this for converting pages from 3rd to... :(
   */
  sd->lowest_level = MIN(sd->lowest_level, level);

  level  +=  1 - sd->lowest_level;

  item_dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
  if (!item_dict) {
    spc_warn(spe, "Ignoring invalid dictionary.");
    return  -1;
  }
  current_depth = pdf_doc_bookmarks_depth();
  if (current_depth > level) {
    while (current_depth-- > level)
      pdf_doc_bookmarks_up();
  } else if (current_depth < level) {
    while (current_depth++ < level)
      pdf_doc_bookmarks_down();
  }

  pdf_doc_bookmarks_add(item_dict, is_open);

  return 0;
}

static int
spc_handler_pdfm_article (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  char    *ident;
  pdf_obj *info_dict;

  skip_white (&args->curptr, args->endptr);

  ident = parse_opt_ident(&args->curptr, args->endptr);
  if (!ident) {
    spc_warn(spe,  "Article name expected but not found.");
    return -1;
  }

  info_dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
  if (!info_dict) {
    spc_warn(spe, "Ignoring article with invalid info dictionary.");
    RELEASE(ident);
    return  -1;
  }

  pdf_doc_begin_article(ident, pdf_link_obj(info_dict));
  spc_push_object(ident, info_dict);
  RELEASE(ident);

  return 0;
}

static int
spc_handler_pdfm_bead (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  pdf_obj         *article;
  pdf_obj         *article_info;
  char            *article_name;
  pdf_rect         rect;
  int              page_no;
  transform_info   ti;
  pdf_coord        cp;

  skip_white(&args->curptr, args->endptr);

  if (args->curptr[0] != '@') {
    spc_warn(spe, "Article identifier expected but not found.");
    return  -1;
  }

  article_name = parse_opt_ident(&args->curptr, args->endptr);
  if (!article_name) {
    spc_warn(spe, "Article reference expected but not found.");
    return  -1;
  }

  /* If okay so far, try to get a bounding box */
  transform_info_clear(&ti);
  if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
    RELEASE(article_name);
    return  -1;
  }

  if ((ti.flags & INFO_HAS_USER_BBOX) &&
      ((ti.flags & INFO_HAS_WIDTH) || (ti.flags & INFO_HAS_HEIGHT))) {
    spc_warn(spe, "You can't specify both bbox and width/height.");
    RELEASE(article_name);
    return -1;
  }

  cp.x = spe->x_user; cp.y = spe->y_user;
  pdf_dev_transform(&cp, NULL);
  if (ti.flags & INFO_HAS_USER_BBOX) {
    rect.llx = ti.bbox.llx + cp.x;
    rect.lly = ti.bbox.lly + cp.y;
    rect.urx = ti.bbox.urx + cp.x;
    rect.ury = ti.bbox.ury + cp.y;
  } else {
    rect.llx = cp.x;
    rect.lly = cp.y - spe->mag * ti.depth;
    rect.urx = cp.x + spe->mag * ti.width;
    rect.ury = cp.y + spe->mag * ti.height;
  }

  skip_white(&args->curptr, args->endptr);
  if (args->curptr[0] != '<') {
    article_info = pdf_new_dict();
  } else {
    article_info = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
    if (!article_info) {
      spc_warn(spe, "Error in reading dictionary.");
      RELEASE(article_name);
      return -1;
    }
  }

  /* Does this article exist yet */
  article = spc_lookup_object(article_name);
  if (article) {
    pdf_merge_dict (article, article_info);
    pdf_release_obj(article_info);
  } else {
    pdf_doc_begin_article(article_name, pdf_link_obj(article_info));
    spc_push_object(article_name, article_info);
  }
  page_no = pdf_doc_current_page_number();
  pdf_doc_add_bead(article_name, NULL, page_no, &rect);

  RELEASE(article_name);
  return 0;
}

static int
spc_handler_pdfm_image (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  int              xobj_id;
  char            *ident = NULL;
  pdf_obj         *fspec;
  transform_info   ti;
  load_options     options = {1, 0, NULL};

  skip_white(&args->curptr, args->endptr);
  if (args->curptr[0] == '@') {
    ident = parse_opt_ident(&args->curptr, args->endptr);
    xobj_id = findresource(sd, ident);
    if (xobj_id >= 0) {
      spc_warn(spe, "Object reference name for image \"%s\" already used.", ident);
      RELEASE(ident);
      return  -1;
    }
  }

  /* 2015/12/29
   * There should not be "page" and "pagebox" in read_dimtrns().
   * It is for reading "dimensions" and "transformations" and "page" is
   * completely unrelated.
   */
  transform_info_clear(&ti);
  if (spc_util_read_blahblah(spe, &ti,
                             &options.page_no, &options.bbox_type, args) < 0) {
    spc_warn(spe, "Reading option field in pdf:image failed.");
    if (ident)
      RELEASE(ident);
    return  -1;
  }

  skip_white(&args->curptr, args->endptr);
  fspec = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!fspec) {
    spc_warn(spe, "Missing filename string for pdf:image.");
    if (ident)
      RELEASE(ident);
    return  -1;
  } else if (!PDF_OBJ_STRINGTYPE(fspec)) {
    spc_warn(spe, "Missing filename string for pdf:image.");
    pdf_release_obj(fspec);
    if (ident)
      RELEASE(ident);
    return  -1;
  }

  skip_white(&args->curptr, args->endptr);
  if (args->curptr < args->endptr) {
    options.dict = parse_pdf_object(&args->curptr, args->endptr, NULL);
  }

  xobj_id = pdf_ximage_findresource(pdf_string_value(fspec), options);

  if (xobj_id < 0) {
    spc_warn(spe, "Could not find image resource...");
    pdf_release_obj(fspec);
    if (ident)
      RELEASE(ident);
    return  -1;
  }

  if (!(ti.flags & INFO_DO_HIDE))
    pdf_dev_put_image(xobj_id, &ti, spe->x_user, spe->y_user);

  if (ident) {
    if ((dpx_conf.compat_mode == dpx_mode_compat_mode) &&
        pdf_ximage_get_subtype(xobj_id) == PDF_XOBJECT_TYPE_IMAGE)
      pdf_ximage_set_attr(xobj_id, 1, 1, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0);
    addresource(sd, ident, xobj_id);
    RELEASE(ident);
  }

  pdf_release_obj(fspec);

  return 0;
}

/* Use do_names instead. */
static int
spc_handler_pdfm_dest (struct spc_env *spe, struct spc_arg *args)
{
  pdf_obj  *name, *array;

  skip_white(&args->curptr, args->endptr);

  name = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!name) {
    spc_warn(spe, "PDF string expected for destination name but not found.");
    return  -1;
  } else if (!PDF_OBJ_STRINGTYPE(name)) {
    spc_warn(spe, "PDF string expected for destination name but invalid type.");
    pdf_release_obj(name);
    return  -1;
  }

#if 0
  if ((dpx_conf.compat_mode == dpx_mode_xdv_mode) && maybe_reencode_utf8(name) < 0)
    WARN("Failed to convert input string to UTF16...");
#endif

  array = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!array) {
    spc_warn(spe, "No destination specified for pdf:dest.");
    pdf_release_obj(name);
    return  -1;
  } else if (!PDF_OBJ_ARRAYTYPE(array)) {
    spc_warn(spe, "Destination not specified as an array object!");
    pdf_release_obj(name);
    pdf_release_obj(array);
    return  -1;
  }

  pdf_doc_add_names("Dests",
                    pdf_string_value (name),
                    pdf_string_length(name),
                    array);
  pdf_release_obj(name);

  return 0;
}

static int
spc_handler_pdfm_names (struct spc_env *spe, struct spc_arg *args)
{
  pdf_obj *category, *key, *value, *tmp;
  int      i, size;

  category = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!category) {
    spc_warn(spe, "PDF name expected but not found.");
    return  -1;
  } else if (!PDF_OBJ_NAMETYPE(category)) {
    spc_warn(spe, "PDF name expected but not found.");
    pdf_release_obj(category);
    return  -1;
  }

  tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!tmp) {
    spc_warn(spe, "PDF object expected but not found.");
    pdf_release_obj(category);
    return  -1;
  } else if (PDF_OBJ_ARRAYTYPE(tmp)) {
    size = pdf_array_length(tmp);
    if (size % 2 != 0) {
      spc_warn(spe, "Array size not multiple of 2 for pdf:names.");
      pdf_release_obj(category);
      pdf_release_obj(tmp);
      return  -1;
    }

    for (i = 0; i < size / 2; i++) {
      key   = pdf_get_array(tmp, 2 * i);
      value = pdf_get_array(tmp, 2 * i + 1);
      if (!PDF_OBJ_STRINGTYPE(key)) {
        spc_warn(spe, "Name tree key must be string.");
        pdf_release_obj(category);
        pdf_release_obj(tmp);
        return -1;
      } else if (pdf_doc_add_names(pdf_name_value(category),
                                   pdf_string_value (key),
                                   pdf_string_length(key),
                                   pdf_link_obj(value)) < 0) {
        spc_warn(spe, "Failed to add Name tree entry...");
        pdf_release_obj(category);
        pdf_release_obj(tmp);
        return -1;
      }
    }
    pdf_release_obj(tmp);
  } else if (PDF_OBJ_STRINGTYPE(tmp)) {
    key   = tmp;
    value = parse_pdf_object(&args->curptr, args->endptr, NULL);
    if (!value) {
      pdf_release_obj(category);
      pdf_release_obj(key);
      spc_warn(spe, "PDF object expected but not found.");
      return -1;
    }
    if (pdf_doc_add_names(pdf_name_value(category),
                          pdf_string_value (key),
                          pdf_string_length(key),
                          value) < 0) {
      spc_warn(spe, "Failed to add Name tree entry...");
      pdf_release_obj(category);
      pdf_release_obj(key);
      return -1;
    }
    pdf_release_obj(key);
  } else {
    pdf_release_obj(tmp);
    pdf_release_obj(category);
    spc_warn(spe, "Invalid object type for pdf:names.");
    return  -1;
  }
  pdf_release_obj(category);

  return 0;
}

static int
spc_handler_pdfm_docinfo (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  pdf_obj *docinfo, *dict;

  dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
  if (!dict) {
    spc_warn(spe, "Dictionary object expected but not found.");
    return  -1;
  }

  docinfo = pdf_doc_docinfo();
  pdf_merge_dict(docinfo, dict);
  pdf_release_obj(dict);

  return 0;
}

static int
spc_handler_pdfm_docview (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  pdf_obj   *catalog,  *dict;
  pdf_obj   *pref_old, *pref_add;

  dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
  if (!dict) {
    spc_warn(spe, "Dictionary object expected but not found.");
    return  -1;
  }

  catalog  = pdf_doc_catalog();
  /* Avoid overriding whole ViewerPreferences */
  pref_old = pdf_lookup_dict(catalog, "ViewerPreferences");
  pref_add = pdf_lookup_dict(dict,    "ViewerPreferences");
  if (pref_old && pref_add) {
    pdf_merge_dict (pref_old, pref_add);
    pdf_remove_dict(dict, "ViewerPreferences");
  }
  pdf_merge_dict (catalog, dict);
  pdf_release_obj(dict);

  return 0;
}

static int
spc_handler_pdfm_close (struct spc_env *spe, struct spc_arg *args)
{
  char *ident;

  skip_white(&args->curptr, args->endptr);
  ident = parse_opt_ident(&args->curptr, args->endptr);
  if (ident) {
    spc_flush_object(ident);
    RELEASE(ident);
  } else { /* Close all? */
    spc_clear_objects();
  }

  return 0;
}

static int
spc_handler_pdfm_object (struct spc_env *spe, struct spc_arg *args)
{
  char    *ident;
  pdf_obj *object;

  skip_white(&args->curptr, args->endptr);
  ident = parse_opt_ident(&args->curptr, args->endptr);
  if (!ident) {
    spc_warn(spe, "Could not find a object identifier.");
    return  -1;
  }

  object = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!object) {
    spc_warn(spe, "Could not find an object definition for \"%s\".", ident);
    RELEASE(ident);
    return  -1;
  } else {
    spc_push_object(ident, object);
  }
  RELEASE(ident);

  return 0;
}

static int
spc_handler_pdfm_content (struct spc_env *spe, struct spc_arg *args)
{
  int  len = 0;

  skip_white(&args->curptr, args->endptr);
  if (args->curptr < args->endptr) {
    pdf_tmatrix M;

    pdf_setmatrix(&M, 1.0, 0.0, 0.0, 1.0, spe->x_user, spe->y_user);
    work_buffer[len++] = ' ';
    work_buffer[len++] = 'q';
    work_buffer[len++] = ' ';
    len += pdf_sprint_matrix(work_buffer + len, &M);
    work_buffer[len++] = ' ';
    work_buffer[len++] = 'c';
    work_buffer[len++] = 'm';
    work_buffer[len++] = ' ';

    pdf_doc_add_page_content(work_buffer, len);  /* op: q cm */
    len = (int) (args->endptr - args->curptr);
    pdf_doc_add_page_content(args->curptr, len);  /* op: ANY */
    pdf_doc_add_page_content(" Q", 2);  /* op: Q */
  }
  args->curptr = args->endptr;

  return 0;
}

static int
spc_handler_pdfm_literal (struct spc_env *spe, struct spc_arg *args)
{
  int       direct = 0;

  skip_white(&args->curptr, args->endptr);
  while (args->curptr < args->endptr) {
    if (args->curptr + 7 <= args->endptr &&
	!strncmp(args->curptr, "reverse", 7)) {
      args->curptr += 7;
      WARN("The special \"pdf:literal reverse ...\" is no longer supported.\nIgnore the \"reverse\" option.");
    } else if (args->curptr + 6 <= args->endptr &&
	       !strncmp(args->curptr, "direct", 6)) {
      direct      = 1;
      args->curptr += 6;
    } else {
      break;
    }
    skip_white(&args->curptr, args->endptr);
  }

  if (args->curptr < args->endptr) {
    pdf_tmatrix M;
    if (!direct) {
      M.a = M.d = 1.0; M.b = M.c = 0.0;
      M.e = spe->x_user; M.f = spe->y_user;
      pdf_dev_concat(&M);
    }
    pdf_doc_add_page_content(" ", 1);  /* op: */
    pdf_doc_add_page_content(args->curptr, (int) (args->endptr - args->curptr));  /* op: ANY */
    if (!direct) {
      M.e = -spe->x_user; M.f = -spe->y_user;
      pdf_dev_concat(&M);
    }
  }

  args->curptr = args->endptr;

  return 0;
}

static int
spc_handler_pdfm_bcontent (struct spc_env *spe, struct spc_arg *args)
{
  pdf_tmatrix M;
  double xpos, ypos;

  pdf_dev_gsave();
  pdf_dev_get_coord(&xpos, &ypos);
  pdf_setmatrix(&M, 1.0, 0.0, 0.0, 1.0, spe->x_user - xpos, spe->y_user - ypos);
  pdf_dev_concat(&M);
  pdf_dev_push_coord(spe->x_user, spe->y_user);
  return 0;
}

static int
spc_handler_pdfm_econtent (struct spc_env *spe, struct spc_arg *args)
{
  pdf_dev_pop_coord();
  pdf_dev_grestore();
  pdf_dev_reset_color(0);

  return 0;
}

static int
spc_handler_pdfm_code (struct spc_env *spe, struct spc_arg *args)
{
  skip_white(&args->curptr, args->endptr);

  if (args->curptr < args->endptr) {
    pdf_doc_add_page_content(" ", 1);  /* op: */
    pdf_doc_add_page_content(args->curptr, (int) (args->endptr - args->curptr));  /* op: ANY */
    args->curptr = args->endptr;
  }

  return 0;
}

static int
spc_handler_pdfm_do_nothing (struct spc_env *spe, struct spc_arg *args)
{
  args->curptr = args->endptr;
  return 0;
}

#define STRING_STREAM 0
#define FILE_STREAM   1

static int
spc_handler_pdfm_stream_with_type (struct spc_env *spe, struct spc_arg *args, int type)
{
  pdf_obj *fstream;
  int      nb_read;
  char    *ident, *instring, *fullname;
  pdf_obj *tmp;
  FILE    *fp;

  skip_white(&args->curptr, args->endptr);

  ident = parse_opt_ident(&args->curptr, args->endptr);
  if (!ident) {
    spc_warn(spe, "Missing objname for pdf:(f)stream.");
    return  -1;
  }

  skip_white(&args->curptr, args->endptr);

  tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!tmp) {
    spc_warn(spe, "Missing input string for pdf:(f)stream.");
    RELEASE(ident);
    return  -1;
  } else if (!PDF_OBJ_STRINGTYPE(tmp)) {
    spc_warn(spe, "Invalid type of input string for pdf:(f)stream.");
    pdf_release_obj(tmp);
    RELEASE(ident);
    return  -1;
  }

  instring = pdf_string_value(tmp);

  switch (type) {
  case FILE_STREAM:
    if (!instring) {
      spc_warn(spe, "Missing filename for pdf:fstream.");
      pdf_release_obj(tmp);
      RELEASE(ident);
      return  -1;
    }
    fullname = kpse_find_pict(instring);
    if (!fullname) {
      spc_warn(spe, "File \"%s\" not found.", instring);
      pdf_release_obj(tmp);
      RELEASE(ident);
      return  -1;
    }
    fp = DPXFOPEN(fullname, DPX_RES_TYPE_BINARY);
    if (!fp) {
      spc_warn(spe, "Could not open file: %s", instring);
      pdf_release_obj(tmp);
      RELEASE(ident);
      RELEASE(fullname);
      return -1;
    }
    fstream = pdf_new_stream(STREAM_COMPRESS);
    while ((nb_read =
	    fread(work_buffer, sizeof(char), WORK_BUFFER_SIZE, fp)) > 0)
      pdf_add_stream(fstream, work_buffer, nb_read);
    MFCLOSE(fp);
    RELEASE(fullname);
    break;
  case STRING_STREAM:
    fstream = pdf_new_stream(STREAM_COMPRESS);
    pdf_add_stream(fstream, pdf_string_value(tmp), pdf_string_length(tmp));
    break;
  default:
    pdf_release_obj(tmp);
    RELEASE(ident);
    return -1;
  }
  pdf_release_obj(tmp);

  /*
   * Optional dict.
   *
   *  TODO: check Length, Filter...
   */
  skip_white(&args->curptr, args->endptr);

  if (args->curptr[0] == '<') {
    pdf_obj *stream_dict;

    stream_dict = pdf_stream_dict(fstream);

    tmp = parse_pdf_dict(&args->curptr, args->endptr, NULL);
    if (!tmp) {
      spc_warn(spe, "Parsing dictionary failed.");
      pdf_release_obj(fstream);
      RELEASE(ident);
      return -1;
    }
    if (pdf_lookup_dict(tmp, "Length")) {
      pdf_remove_dict(tmp, "Length");
    } else if (pdf_lookup_dict(tmp, "Filter")) {
      pdf_remove_dict(tmp, "Filter");
    }
    pdf_merge_dict(stream_dict, tmp);
    pdf_release_obj(tmp);
  }

  /* Users should explicitly close this. */
  spc_push_object(ident, fstream);
  RELEASE(ident);

  return 0;
}

/*
 * STREAM: Create a PDF stream object from an input string.
 *
 *  pdf: stream @objname (input_string) [PDF_DICT]
 */
static int
spc_handler_pdfm_stream (struct spc_env *spe, struct spc_arg *args)
{
  return spc_handler_pdfm_stream_with_type (spe, args, STRING_STREAM);
}

/*
 * FSTREAM: Create a PDF stream object from an existing file.
 *
 *  pdf: fstream @objname (filename) [PDF_DICT]
 */
static int
spc_handler_pdfm_fstream (struct spc_env *spe, struct spc_arg *args)
{
  return spc_handler_pdfm_stream_with_type (spe, args, FILE_STREAM);
}

/* Grab page content as follows:
 *
 * Reference point = (x_user, y_user)
 *
 * Case 1. \special{pdf:bxobj @obj width WD height HT depth DP}
 *
 *     Grab the box with the lower-left corner (x_user, y_user-DP)
 *     and the upper right corner (x_user+WD, y_user+HT).
 *
 * Case 2. \special{pdf:bxobj @obj bbox LLX LLY URX, URY}
 *
 *     Grab the box with the lower-left corner (x_user+LLX, y_user+LLY)
 *     and the upper right corner (x_user+URX, y_user+URY).
 *
 * Note that scale, xscale, yscale, xoffset, yoffset options are ignored.
 */
static int
spc_handler_pdfm_bform (struct spc_env *spe, struct spc_arg *args)
{
  int             xobj_id;
  char           *ident;
  pdf_rect        cropbox;
  transform_info  ti;

  skip_white(&args->curptr, args->endptr);

  ident = parse_opt_ident(&args->curptr, args->endptr);
  if (!ident) {
    spc_warn(spe, "A form XObject must have name.");
    return  -1;
  }

  transform_info_clear(&ti);
  if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
    RELEASE(ident);
    return  -1;
  }

  /* A XForm with zero dimension results in a non-invertible transformation
   * matrix. And it may result in unpredictable behaviour. It might be an
   * error in Acrobat. Bounding box with zero dimension may cause division
   * by zero.
   */
  if (ti.flags & INFO_HAS_USER_BBOX) {
    if (ti.bbox.urx - ti.bbox.llx == 0.0 ||
        ti.bbox.ury - ti.bbox.lly == 0.0) {
      spc_warn(spe, "Bounding box has a zero dimension.");
      RELEASE(ident);
      return -1;
    }
    cropbox.llx = ti.bbox.llx;
    cropbox.lly = ti.bbox.lly;
    cropbox.urx = ti.bbox.urx;
    cropbox.ury = ti.bbox.ury;
  } else {
    if (ti.width == 0.0 ||
        ti.depth + ti.height == 0.0) {
      spc_warn(spe, "Bounding box has a zero dimension.");
      RELEASE(ident);
      return -1;
    }
    cropbox.llx = 0.0;
    cropbox.lly = -ti.depth;
    cropbox.urx = ti.width;
    cropbox.ury = ti.height;
  }

  xobj_id = pdf_doc_begin_grabbing(ident, spe->x_user, spe->y_user, &cropbox);

  if (xobj_id < 0) {
    RELEASE(ident);
    spc_warn(spe, "Couldn't start form object.");
    return -1;
  }

  spc_push_object(ident, pdf_ximage_get_reference(xobj_id));
  RELEASE(ident);

  return 0;
}

/* An extra dictionary after exobj must be merged to the form dictionary,
 * not resource dictionary.
 * Please use pdf:put @resources (before pdf:exobj) instead.
 */
static int
spc_handler_pdfm_eform (struct spc_env *spe, struct spc_arg *args)
{
  pdf_obj   *attrib = NULL;

  skip_white(&args->curptr, args->endptr);

  if (args->curptr < args->endptr) {
    attrib = parse_pdf_dict(&args->curptr, args->endptr, NULL);
    if (attrib && !PDF_OBJ_DICTTYPE(attrib)) {
      pdf_release_obj(attrib);
      attrib = NULL;
    }
  }
  pdf_doc_end_grabbing(attrib);

  return 0;
}

/* Saved XObjects can be used as follows:
 *
 * Reference point = (x_user, y_user)
 *
 * Case 1. \special{pdf:uxobj @obj width WD height HT depth DP}
 *
 *     Scale the XObject to fit in the box
 *     [x_user, y_user-DP, x_user+WD, y_user+HT].
 *
 * Case 2. \special{pdf:uxobj @obj xscale XS yscale YS}
 *
 *     Scale the XObject with XS and YS. Note that width and xscale
 *     or height and yscale cannot be used together.
 *
 * Case 3. \special{pdf:bxobj @obj bbox LLX LLY URX, URY}
 *
 *     Scale the XObject to fit in the box
 *     [x_user+LLX, y_user+LLY, x_user+URX, y_user+URY].
 *
 * Note that xoffset and yoffset moves the reference point where the
 * lower-left corner of the XObject will be put.
 */
static int
spc_handler_pdfm_uxobj (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  int              xobj_id;
  char            *ident;
  transform_info   ti;
  load_options     options = {1, 0, NULL};

  skip_white(&args->curptr, args->endptr);

  ident = parse_opt_ident(&args->curptr, args->endptr);
  if (!ident) {
    spc_warn(spe, "No object identifier given.");
    return  -1;
  }

  transform_info_clear(&ti);
  if (args->curptr < args->endptr) {
    if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
      RELEASE(ident);
      return  -1;
    }
  }

  /* Dvipdfmx was suddenly changed to use file name to identify
   * external images. We can't use ident to find image resource
   * here.
   */
  xobj_id = findresource(sd, ident);
  if (xobj_id < 0) {
    xobj_id = pdf_ximage_findresource(ident, options);
    if (xobj_id < 0) {
      spc_warn(spe, "Specified (image) object doesn't exist: %s", ident);
      RELEASE(ident);
      return  -1;
    }
  }

  pdf_dev_put_image(xobj_id, &ti, spe->x_user, spe->y_user);
  RELEASE(ident);

  return 0;
}

static int
spc_handler_pdfm_link (struct spc_env *spe, struct spc_arg *args)
{
  return  spc_resume_annot(spe);
}

static int
spc_handler_pdfm_nolink (struct spc_env *spe, struct spc_arg *args)
{
  return  spc_suspend_annot(spe);
}



/* Handled at BOP */
static int
spc_handler_pdfm_pagesize (struct spc_env *spe, struct spc_arg *args)
{
  args->curptr = args->endptr;

  return 0;
}

/* Please remove this.
 * This should be handled before processing pages!
 */
static int
spc_handler_pdfm_bgcolor (struct spc_env *spe, struct spc_arg *args)
{
  int       error;
  pdf_color colorspec;

  error = spc_util_read_pdfcolor(spe, &colorspec, args, NULL);
  if (error)
    spc_warn(spe, "No valid color specified?");
  else {
    pdf_doc_set_bgcolor(&colorspec);
  }

  return  error;
}

#define THEBUFFLENGTH 1024
static int
spc_handler_pdfm_mapline (struct spc_env *spe, struct spc_arg *ap)
{
  fontmap_rec *mrec;
  char        *map_name, opchr;
  int          error = 0;
  static char  buffer[THEBUFFLENGTH];
  const char  *p;
  char        *q;
  int         count;

  skip_white(&ap->curptr, ap->endptr);
  if (ap->curptr >= ap->endptr) {
    spc_warn(spe, "Empty mapline special?");
    return  -1;
  }

  opchr = ap->curptr[0];
  if (opchr == '-' || opchr == '+')
    ap->curptr++;

  skip_white(&ap->curptr, ap->endptr);

  switch (opchr) {
  case  '-':
    map_name = parse_ident(&ap->curptr, ap->endptr);
    if (map_name) {
      pdf_remove_fontmap_record(map_name);
      RELEASE(map_name);
    } else {
      spc_warn(spe, "Invalid fontmap line: Missing TFM name.");
      error = -1;
    }
    break;
  default:
    p = ap->curptr;
    q = buffer;
    count = 0;
    while (p < ap->endptr && count < THEBUFFLENGTH - 1) {
      *q++ = *p++;
      count++;
    }
    if (count == THEBUFFLENGTH - 1) {
      spc_warn(spe, "Invalid fontmap line: Too long a line.");
      *q = 0;
      return -1;
    }
    *q = '\0';
    mrec = NEW(1, fontmap_rec);
    pdf_init_fontmap_record(mrec);
    error = pdf_read_fontmap_line(mrec, buffer, (int) (ap->endptr - ap->curptr), is_pdfm_mapline(buffer));
    if (error)
      spc_warn(spe, "Invalid fontmap line.");
    else if (opchr == '+')
      pdf_append_fontmap_record(mrec->map_name, mrec);
    else
      pdf_insert_fontmap_record(mrec->map_name, mrec);
    pdf_clear_fontmap_record(mrec);
    RELEASE(mrec);
    break;
  }
  if (!error)
    ap->curptr = ap->endptr;

  return 0;
}

static int
spc_handler_pdfm_mapfile (struct spc_env *spe, struct spc_arg *args)
{
  char  *mapfile;
  int    mode, error = 0;

  skip_white(&args->curptr, args->endptr);
  if (args->curptr >= args->endptr)
    return 0;

  switch (args->curptr[0]) {
  case  '-':
    mode = FONTMAP_RMODE_REMOVE;
    args->curptr++;
    break;
  case  '+':
    mode = FONTMAP_RMODE_APPEND;
    args->curptr++;
    break;
  default:
    mode = FONTMAP_RMODE_REPLACE;
    break;
  }

  mapfile = parse_val_ident(&args->curptr, args->endptr);
  if (!mapfile) {
    spc_warn(spe, "No fontmap file specified.");
    return  -1;
  } else {
    error = pdf_load_fontmap_file(mapfile, mode);
  }
  RELEASE(mapfile);

  return  error;
}


static int
spc_handler_pdfm_tounicode (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  char *cmap_name;
  pdf_obj *taint_keys;

  /* First clear */
  sd->cd.cmap_id = -1;
  sd->cd.unescape_backslash = 0;

  skip_white(&args->curptr, args->endptr);
  if (args->curptr >= args->endptr) {
    spc_warn(spe, "Missing CMap name for pdf:tounicode.");
    return  -1;
  }

  /* _FIXME_
   * Any valid char allowed for PDF name object should be allowed here.
   * The argument to this special should be a PDF name obejct.
   * But it's too late to change this special.
   */
  cmap_name = parse_ident(&args->curptr, args->endptr);
  if (!cmap_name) {
    spc_warn(spe, "Missing ToUnicode mapping name...");
    return -1;
  }

  sd->cd.cmap_id = CMap_cache_find(cmap_name);
  if (sd->cd.cmap_id < 0) {
    spc_warn(spe, "Failed to load ToUnicode mapping: %s", cmap_name);
    RELEASE(cmap_name);
    return -1;
  }

  /* Shift-JIS like encoding may contain backslash in 2nd byte.
   * WARNING: This will add nasty extension to PDF parser.
   */
  if (sd->cd.cmap_id >= 0) {
    if (strstr(cmap_name, "RKSJ") ||
        strstr(cmap_name, "B5")   ||
        strstr(cmap_name, "GBK")  ||
        strstr(cmap_name, "KSC"))
      sd->cd.unescape_backslash = 1;
  }
  RELEASE(cmap_name);

  /* Additional "taint key"
   * An array of PDF name objects can be supplied optionally.
   * Dictionary entries specified by this option will be added to the list
   * of dictionary keys to be treated as the target of "ToUnicode" conversion.
   */
  skip_white(&args->curptr, args->endptr);
  if (args->curptr < args->endptr) {
    taint_keys = parse_pdf_object(&args->curptr, args->endptr, NULL);
    if (taint_keys) {
      if (PDF_OBJ_ARRAYTYPE(taint_keys)) {
        int i;
        for (i = 0; i < pdf_array_length(taint_keys); i++) {
          pdf_obj *key;
        
          key = pdf_get_array(taint_keys, i);
          if (PDF_OBJ_NAMETYPE(key))
            pdf_add_array(sd->cd.taintkeys, pdf_link_obj(key));
          else {
            spc_warn(spe, "Invalid argument specified in pdf:tounicode special.");
          }
        }
      } else {
        spc_warn(spe, "Invalid argument specified in pdf:unicode special.");
      }
      pdf_release_obj(taint_keys);
    }
  }

  return 0;
}

static int
spc_handler_pdfm_pageresources (struct spc_env *spe, struct spc_arg *args)
{
  struct spc_pdf_ *sd = &_pdf_stat;
  pdf_obj *dict;

  dict = parse_pdf_object(&args->curptr, args->endptr, NULL);
  if (!dict) {
    spc_warn(spe, "Dictionary object expected but not found.");
    return  -1;
  }

  if (sd->pageresources)
    pdf_release_obj(sd->pageresources);
  sd->pageresources = dict;

  return 0;
}

static struct spc_handler pdfm_handlers[] = {
  {"annotation", spc_handler_pdfm_annot},
  {"annotate",   spc_handler_pdfm_annot},
  {"annot",      spc_handler_pdfm_annot},
  {"ann",        spc_handler_pdfm_annot},

  {"outline",    spc_handler_pdfm_outline},
  {"out",        spc_handler_pdfm_outline},

  {"article",    spc_handler_pdfm_article},
  {"art",        spc_handler_pdfm_article},

  {"bead",       spc_handler_pdfm_bead},
  {"thread",     spc_handler_pdfm_bead},

  {"destination", spc_handler_pdfm_dest}, 
  {"dest",        spc_handler_pdfm_dest},


  {"object",      spc_handler_pdfm_object},
  {"obj",         spc_handler_pdfm_object},


  {"docinfo",     spc_handler_pdfm_docinfo},
  {"docview",     spc_handler_pdfm_docview},

  {"content",     spc_handler_pdfm_content},
  {"put",         spc_handler_pdfm_put},
  {"close",       spc_handler_pdfm_close},
  {"bop",         spc_handler_pdfm_bop},
  {"eop",         spc_handler_pdfm_eop},

  {"image",       spc_handler_pdfm_image},
  {"img",         spc_handler_pdfm_image},
  {"epdf",        spc_handler_pdfm_image},

  {"link",        spc_handler_pdfm_link},
  {"nolink",      spc_handler_pdfm_nolink},

  {"begincolor",  spc_handler_pdfm_bcolor},
  {"bcolor",      spc_handler_pdfm_bcolor},
  {"bc",          spc_handler_pdfm_bcolor},

  {"setcolor",    spc_handler_pdfm_scolor},
  {"scolor",      spc_handler_pdfm_scolor},
  {"sc",          spc_handler_pdfm_scolor},

  {"endcolor",    spc_handler_pdfm_ecolor},
  {"ecolor",      spc_handler_pdfm_ecolor},
  {"ec",          spc_handler_pdfm_ecolor},

  {"begingray",   spc_handler_pdfm_bcolor},
  {"bgray",       spc_handler_pdfm_bcolor},
  {"bg",          spc_handler_pdfm_bcolor},

  {"endgray",     spc_handler_pdfm_ecolor},
  {"egray",       spc_handler_pdfm_ecolor},
  {"eg",          spc_handler_pdfm_ecolor},

  {"bgcolor",     spc_handler_pdfm_bgcolor},
  {"bgc",         spc_handler_pdfm_bgcolor},
  {"bbc",         spc_handler_pdfm_bgcolor},
  {"bbg",         spc_handler_pdfm_bgcolor},

  {"pagesize",    spc_handler_pdfm_pagesize},

  {"bannot",      spc_handler_pdfm_bann},
  {"beginann",    spc_handler_pdfm_bann},
  {"bann",        spc_handler_pdfm_bann},

  {"eannot",      spc_handler_pdfm_eann},
  {"endann",      spc_handler_pdfm_eann},
  {"eann",        spc_handler_pdfm_eann},

  {"btrans",         spc_handler_pdfm_btrans},
  {"begintransform", spc_handler_pdfm_btrans},
  {"begintrans",     spc_handler_pdfm_btrans},
  {"bt",             spc_handler_pdfm_btrans},

  {"etrans",         spc_handler_pdfm_etrans},
  {"endtransform",   spc_handler_pdfm_etrans},
  {"endtrans",       spc_handler_pdfm_etrans},
  {"et",             spc_handler_pdfm_etrans},

  {"bform",          spc_handler_pdfm_bform},
  {"beginxobj",      spc_handler_pdfm_bform},
  {"bxobj",          spc_handler_pdfm_bform},

  {"eform",          spc_handler_pdfm_eform},
  {"endxobj",        spc_handler_pdfm_eform},
  {"exobj",          spc_handler_pdfm_eform},

  {"usexobj",        spc_handler_pdfm_uxobj},
  {"uxobj",          spc_handler_pdfm_uxobj},

  {"tounicode",  spc_handler_pdfm_tounicode},
  {"literal",    spc_handler_pdfm_literal},
  {"stream",     spc_handler_pdfm_stream},
  {"fstream",    spc_handler_pdfm_fstream},
  {"names",      spc_handler_pdfm_names},
  {"mapline",    spc_handler_pdfm_mapline},
  {"mapfile",    spc_handler_pdfm_mapfile},

  {"bcontent",   spc_handler_pdfm_bcontent},
  {"econtent",   spc_handler_pdfm_econtent},
  {"code",       spc_handler_pdfm_code},

  {"minorversion", spc_handler_pdfm_do_nothing},
  {"majorversion", spc_handler_pdfm_do_nothing},
  {"encrypt",      spc_handler_pdfm_do_nothing},

  {"pageresources", spc_handler_pdfm_pageresources},
  {"trailerid", spc_handler_pdfm_do_nothing},
};

int
spc_pdfm_check_special (const char *buf, int len)
{
  int    r = 0;
  const char *p, *endptr;

  p      = buf;
  endptr = p + len;

  skip_white(&p, endptr);
  if (p + strlen("pdf:") <= endptr &&
      !memcmp(p, "pdf:", strlen("pdf:"))) {
    r = 1;
  }

  return  r;
}

int
spc_pdfm_setup_handler (struct spc_handler *sph,
                        struct spc_env *spe, struct spc_arg *ap)
{
  int    error = -1, i;
  char  *q;

  ASSERT(sph && spe && ap);

  skip_white(&ap->curptr, ap->endptr);
  if (ap->curptr + strlen("pdf:") >= ap->endptr ||
      memcmp(ap->curptr, "pdf:", strlen("pdf:"))) {
    spc_warn(spe, "Not pdf: special???");
    return  -1;
  }
  ap->curptr += strlen("pdf:");

  skip_white(&ap->curptr, ap->endptr);
  q = parse_c_ident(&ap->curptr, ap->endptr);
  if (q) {
    for (i = 0;
         i < sizeof(pdfm_handlers) / sizeof(struct spc_handler); i++) {
      if (!strcmp(q, pdfm_handlers[i].key)) {
        ap->command = pdfm_handlers[i].key;
        sph->key   = "pdf:";
        sph->exec  = pdfm_handlers[i].exec;
        skip_white(&ap->curptr, ap->endptr);
        error = 0;
        break;
      }
    }
    RELEASE(q);
  }

  return  error;
}