File: pdfgraphics.ml

package info (click to toggle)
camlpdf 0.5-1
  • links: PTS, VCS
  • area: non-free
  • in suites: squeeze, wheezy
  • size: 1,516 kB
  • ctags: 2,689
  • sloc: ml: 18,229; ansic: 139; makefile: 139
file content (1717 lines) | stat: -rw-r--r-- 62,830 bytes parent folder | download
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
(* \chaptertitle{Pdfgraphics}{Structured Graphics} *)
open Utility
open Pdf
open Pdfread
open Pdfpages

type fpoint = float * float

type winding_rule = EvenOdd | NonZero

type segment =
  | Straight of fpoint * fpoint
  | Bezier of fpoint * fpoint * fpoint * fpoint

(* Each segment list may be marked as a hole or not. *)
type hole = Hole | Not_hole

(* A [subpath] is either closed or open. *)
type closure = Closed | Open

(* A [subpath] is the pair of a hole and a list of segments. *)
type subpath = hole * closure * segment list

(* A path is made from a number of subpaths. *)
type path = winding_rule * subpath list

type tiling = Tiling

type function_shading =
  {funshading_domain : float * float * float * float;
   funshading_matrix : Transform.transform_matrix;
   funshading_function : Pdffun.pdf_fun}

type radial_shading =
  {radialshading_coords : float * float * float * float * float * float;
   radialshading_domain : float * float;
   radialshading_function : Pdffun.pdf_fun list;
   radialshading_extend : bool * bool}

type axial_shading =
  {axialshading_coords : float * float * float * float;
   axialshading_domain : float * float;
   axialshading_function : Pdffun.pdf_fun list;
   axialshading_extend : bool * bool}

type shading_kind =
 | FunctionShading of function_shading
 | AxialShading of axial_shading
 | RadialShading of radial_shading
 | FreeFormGouraudShading
 | LatticeFormGouraudShading
 | CoonsPatchMesh
 | TensorProductPatchMesh

type shading =
 {shading_colourspace : Pdf.pdfobject;
  shading_background : Pdf.pdfobject option;
  shading_bbox : Pdf.pdfobject option;
  shading_antialias : bool;
  shading_matrix : Transform.transform_matrix;
  shading_extgstate : Pdf.pdfobject;
  shading : shading_kind}

type pattern =
  | ColouredTilingPattern of tiling
  | UncolouredTilingPattern of tiling
  | ShadingPattern of shading

type colvals =
  | Floats of float list
  | Named of (string * float list)
  | Pattern of pattern

let rec string_of_colvals = function
  | Floats fs ->
      "Floats " ^ fold_left ( ^ ) "" (map (function x -> string_of_float x ^ " ") fs)
  | Named (n, fs) ->
      "Named " ^ n ^ " " ^ string_of_colvals (Floats fs)
  | Pattern p ->
      "Pattern"

type objectclass =
  | PathObject
  | TextObject
  | ClippingPathObject
  | PageDescriptionLevel
  | ShadingObject
  | InlineImageObject
  | ExternalObject

let string_of_objectclass = function
  | PathObject -> "PathObject"
  | TextObject -> "TextObject"
  | ClippingPathObject -> "ClippingPathObject"
  | PageDescriptionLevel -> "PageDescriptionLevel"
  | ShadingObject -> "ShadingObject"
  | InlineImageObject -> "InlineImageObject"
  | ExternalObject -> "ExternalObject"

type transparency_attributes =
  {fill_transparency : float;
   line_transparency : float}

type path_attributes =
  {path_transform : Transform.transform_matrix;
   path_fill : (Pdf.pdfobject * colvals) option;
   path_line : (Pdf.pdfobject * colvals) option;
   path_linewidth : float;
   path_joinstyle : int;
   path_capstyle : int;
   path_dash : float list * float;
   path_mitrelimit : float;
   path_transparency : transparency_attributes;
   path_intent : string}

type text_attributes =
  {textmode : int}

type textblock_attributes =
  {textblock_transform : Transform.transform_matrix}

type textblock =
  text_attributes * Pdfpages.operator

type softmask_subtype =
  Alpha | Luminosity

type transparency_group =
  {tr_group_colourspace : Pdf.pdfobject option;
   isolated : bool;
   knockout : bool;
   tr_graphic : graphic}

and softmask =
  {softmask_subtype : softmask_subtype;
   transparency_group : transparency_group;
   softmask_bbox : float * float * float * float;
   backdrop : float list option;
   softmask_transfer : Pdffun.pdf_fun option}

and image_attributes =
  {image_transform : Transform.transform_matrix;
   image_transparency : float; (* The /ca value *)
   image_softmask : softmask option}

and fontname = string * Pdf.pdfobject (*r Name, font *)

(* The main type for a graphic. It must be kept paired with the PDF it comes
from, since it will reference objects (fonts, images etc) in that PDF. *)
and graphic_elt =
  | Path of (path * path_attributes)
  | Text of textblock list * textblock_attributes
  | MCPoint of string
  | MCPointProperties of string * Pdf.pdfobject 
  | MCSection of string * graphic_elt list
  | MCSectionProperties of string * Pdf.pdfobject * graphic_elt list
  | Image of image_attributes * int (* object number *)
  | GraphicInlineImage of Pdf.pdfobject * bytestream * Transform.transform_matrix
  | Clip of path * graphic_elt list
  | Shading of path option * shading * Transform.transform_matrix

and graphic =
  {elements : graphic_elt list; (* Page content *)
   fonts : fontname list; (* Fonts *)
   resources : Pdf.pdfobject} (* Anything else in /Resources *)

(* Calculate the bounding box (xmin, xmax, ymin, ymax) of a graphic. *)
let bbox_of_segment = function
  | Straight ((x1, y1), (x2, y2)) ->
      fmin x1 x2, fmax x1 x2, fmin y1 y2, fmax y1 y2
  | Bezier ((x1, y1), (x2, y2), (x3, y3), (x4, y4)) ->
      fmin (fmin x1 x2) (fmin x3 x4), fmax (fmax x1 x2) (fmax x3 x4),
      fmin (fmin y1 y2) (fmin y3 y4), fmax (fmax y1 y2) (fmax y3 y4)

let bbox_of_path (_, subpaths) =
  let segments =
    flatten (map (function (_, _, l) -> l) subpaths)
  in
    fold_left
      box_union_float
      (max_float, min_float, max_float, min_float)
      (map bbox_of_segment segments)

let rec bbox_of_graphic_inner (xmin, xmax, ymin, ymax) = function
  | [] -> xmin, xmax, ymin, ymax
  | (Path (p, _) | Clip (p, _))::t ->
      bbox_of_graphic_inner
        (box_union_float (xmin, xmax, ymin, ymax) (bbox_of_path p)) t
  | h::t -> bbox_of_graphic_inner (xmin, xmax, ymin, ymax) t

let bbox_of_graphic graphic =
  bbox_of_graphic_inner
    (max_float, min_float, max_float, min_float)
    graphic.elements

(* For debug purposes, build a string of a graphic. *)
let string_of_segment = function
  | Straight ((ax, ay), (bx, by)) ->
      Printf.sprintf "Straight line: (%f, %f) --> (%f, %f)\n" ax ay bx by
  | Bezier ((ax, ay), (bx, by), (cx, cy), (dx, dy)) ->
      Printf.sprintf
        "Bezier curve: (%f, %f) --> (%f, %f) --> (%f, %f) --> (%f, %f)\n"
        ax ay bx by cx cy dx dy

let string_of_subpath (h, o ,segments) =
  Printf.sprintf "Hole: %b, Open: %b, segments:%s\n"
    (h = Hole) (o = Open) (fold_left ( ^ ) "" (map string_of_segment segments))

let string_of_path (windingrule, subpaths) =
  Printf.sprintf "%s %s"
    (match windingrule with
    | EvenOdd -> "Even-odd\n"
    | NonZero -> "Non-zero\n")
    (fold_left ( ^ ) "" (map string_of_subpath subpaths))

let string_of_textblock (st, op) =
  "TEXTPIECE: " ^ Pdfpages.string_of_op op ^ "\n"

let string_of_font (f, i) = f ^ " " ^ Pdfwrite.string_of_pdf i ^ "\n"

let rec string_of_graphic_elt = function
  | MCSection (n, g) ->
      Printf.sprintf "Marked content section %s...\n" n ^ "BEGIN\n" ^
      (fold_left ( ^ ) "" (map string_of_graphic_elt g))
      ^ "\nEND Marked content section\n"
  | MCSectionProperties (n, d, g) ->
      Printf.sprintf "Marked content section %s with properties %s...\n" n
      (Pdfwrite.string_of_pdf d) 
      ^ "BEGIN\n" ^
      (fold_left ( ^ ) "" (map string_of_graphic_elt g))
      ^ "\nEND Marked content section\n"
  | MCPoint n ->
      Printf.sprintf "Marked content point %s...\n" n
  | MCPointProperties (n, d) ->
      Printf.sprintf "Marked content point %s with properties %s...\n" n (Pdfwrite.string_of_pdf d)
  | Path (p, _) -> Printf.sprintf "Path: %s\n" (string_of_path p)
  | Text (ts, attr) ->
      "-----BEGIN TEXT - fonts:\n" ^
      fold_left ( ^ ) "" (map string_of_textblock ts) ^
      "-----END TEXT"
  | Image (tr, x) ->
      "Image " ^ string_of_int x ^ "\n"
  | GraphicInlineImage _ ->
      "Inline image\n"
  | Clip (p, g) ->
      "Clipview: path = " ^ string_of_path p ^ "\ngraphic is " ^
      fold_left ( ^ ) "" (map string_of_graphic_elt g)
  | Shading (clip, shading, tr) ->
      "Shading"

and string_of_graphic g =
  "Elements:\n" ^
  fold_left ( ^ ) "" (map string_of_graphic_elt g.elements) ^ 
  "Fonts:\n" ^
  fold_left ( ^ ) ""
    (map
      (fun (name, obj) -> name ^ " "  ^ Pdfwrite.string_of_pdf obj)
       g.fonts) ^
  "Resources:\n" ^
  Pdfwrite.string_of_pdf g.resources

type state =
  {mutable objectclass : objectclass; (*r Not strictly part of the state, but fits here. *)
   mutable clip : path option; (*r Ditto - stores a clipping path which is to be invoked on the next path operation. *)
   mutable intent : string;
   mutable fill : colvals;
   mutable linewidth : float;
   mutable line : colvals;
   mutable mitrelimit : float;
   mutable joinstyle : int;
   mutable capstyle : int;
   mutable colourspace_stroke : Pdf.pdfobject;
   mutable colourspace_nonstroke : Pdf.pdfobject;
   mutable dash : float list * float;
   mutable flatness : int;
   mutable transform : Transform.transform_matrix;
   mutable extra_transform : Transform.transform_matrix;
   mutable text_transform : Transform.transform_matrix;
   mutable text_line_transform : Transform.transform_matrix;
   mutable opacity_stroke : float;
   mutable opacity_nonstroke : float;
   mutable character_spacing : float;
   mutable word_spacing : float;
   mutable scale : float;
   mutable leading : float;
   mutable font_and_size : (string * float) option;
   mutable font_render : int;
   mutable font_rise : float;
   mutable blendmode : int;
   mutable softmask : softmask option;
   mutable in_xobject : int;
   mutable opdo_matrix : Transform.transform_matrix}

let default_state () =
  {objectclass = PageDescriptionLevel;
   clip = None;
   intent = "/RelativeColorimetric";
   fill = Floats [1.];
   linewidth = 1.;
   line = Floats [1.];
   mitrelimit = 10.;
   joinstyle = 0;
   capstyle = 0;
   colourspace_stroke = Name "/DeviceGray";
   colourspace_nonstroke = Name "/DeviceGray";
   dash = [], 0.;
   flatness = 0;
   transform = Transform.i_matrix;
   extra_transform = Transform.i_matrix;
   text_transform = Transform.i_matrix;
   text_line_transform = Transform.i_matrix;
   opacity_stroke = 1.;
   opacity_nonstroke = 1.;
   character_spacing = 0.;
   word_spacing = 0.;
   scale = 100.;
   leading = 0.;
   font_and_size = None; (*r No initial value. *)
   font_render = 0;
   font_rise = 0.;
   blendmode = 1;
   softmask = None;
   in_xobject = 0;
   opdo_matrix = Transform.i_matrix}

let state = ref (default_state ())

let string_of_state s =
  (*i "Object class: " ^ string_of_objectclass s.objectclass ^ "\n" ^ i*)
  "Stroke Colourspace: " ^ Pdfwrite.string_of_pdf s.colourspace_stroke ^ "\n" ^
  "Nonstroke Colourspace: " ^ Pdfwrite.string_of_pdf s.colourspace_nonstroke ^ "\n" ^
  "Stroke colours: " ^ string_of_colvals s.line ^ "\n" ^ 
  "NonStroke colours: " ^ string_of_colvals s.fill ^ "\n"

let path_attributes_fill_and_stroke () =
  {path_transform = (!state).transform;
   path_fill = Some ((!state).colourspace_nonstroke, (!state).fill);
   path_line = Some ((!state).colourspace_stroke, (!state).line);
   path_linewidth = (!state).linewidth;
   path_joinstyle = (!state).joinstyle;
   path_capstyle = (!state).capstyle;
   path_dash = (!state).dash;
   path_mitrelimit = (!state).mitrelimit;
   path_transparency =
     {fill_transparency = (!state).opacity_nonstroke;
      line_transparency = (!state).opacity_stroke};
   path_intent = (!state).intent}

let path_attributes_fill () =
  {path_transform = (!state).transform;
   path_fill = Some ((!state).colourspace_nonstroke, (!state).fill);
   path_line = None;
   path_linewidth = (!state).linewidth;
   path_joinstyle = (!state).joinstyle;
   path_capstyle = (!state).capstyle;
   path_dash = (!state).dash;
   path_mitrelimit = (!state).mitrelimit;
   path_transparency =
     {fill_transparency = (!state).opacity_nonstroke;
      line_transparency = 1.};
   path_intent = (!state).intent}

let path_attributes_stroke () =
  {path_transform = (!state).transform;
   path_fill = None;
   path_line = Some ((!state).colourspace_stroke, (!state).line);
   path_linewidth = (!state).linewidth;
   path_joinstyle = (!state).joinstyle;
   path_capstyle = (!state).capstyle;
   path_dash = (!state).dash;
   path_mitrelimit = (!state).mitrelimit;
   path_transparency =
     {fill_transparency = 1.;
      line_transparency = (!state).opacity_stroke};
   path_intent = (!state).intent}

let textstate () =
  {textmode = 0}

let nonzero = EvenOdd

let rec initial_colour pdf resources = function
  | Name "/DeviceGray"
  | Array (Name "/CalGray"::_) ->
      Floats [0.]
  | Name "/DeviceRGB"
  | Array (Name "/CalRGB"::_) ->
      Floats [0.; 0.; 0.]
  | Name "/DeviceCMYK" ->
      Floats [0.; 0.; 0.; 1.]
  | Name "/Pattern"
  | Array [Name "/Pattern"] ->
      Floats [0.]
  | Array elts as cs ->
      begin match elts with
        | [Name "/ICCBased"; iccstream] ->
             begin match lookup_direct pdf "/Alternate" iccstream with
             | Some space -> initial_colour pdf resources space
             | None ->
                 begin match lookup_direct pdf "/N" iccstream with
                 | Some (Integer 1) -> Floats [0.]
                 | Some (Integer 3) -> Floats [0.; 0.; 0.]
                 | Some (Integer 4) -> Floats [0.; 0.; 0.; 0.]
                 | _ -> raise (PDFSemanticError "Bad ICCBased Alternate")
                 end
             end
        | Name "/DeviceN"::_::alternate::_ 
        | [Name "/Separation"; _; alternate; _] ->
            initial_colour pdf resources alternate
        | [Name "/Pattern"; alternate] ->
            initial_colour pdf resources alternate
        | _ -> Printf.eprintf "%s\n" (Pdfwrite.string_of_pdf cs); raise (PDFSemanticError "Unknown colourspace A")
      end
  | Indirect _ as indirect ->
      initial_colour pdf resources (direct pdf indirect)
  | _ -> raise (PDFSemanticError "Unknown colourspace B")

(* PartialPath (sp, cp, p, s) is starting point [sp], current point [cp] the
partial segment list [p], subpath [s] and graphic [g]. *)
type partial =
  | NoPartial
  | PartialText of textblock list
  | PartialPath of fpoint * fpoint * segment list * subpath list 

(* g is a [group_transparency] xobject *)
let rec read_transparency_group pdf g =
  let group =
    match Pdf.lookup_direct pdf "/Group" g with
    | Some gr -> gr
    | None -> raise (Pdf.PDFError "Pdfgraphics.read_transparency_group: no /Group found")
  in
    let colourspace =
      Pdf.lookup_direct pdf "/CS" group
    and isolated =
      match Pdf.lookup_direct pdf "/I" group with
      | Some (Pdf.Boolean b) -> b
      | _ -> false
    and knockout =
      match Pdf.lookup_direct pdf "/K" group with
      | Some (Pdf.Boolean b) -> b
      | _ -> false
    and graphic =
      let fakepage =
        let resources =
          match Pdf.lookup_direct pdf "/Resources" g with
          | Some (Pdf.Dictionary d) -> Pdf.Dictionary d
          | _ -> Pdf.Dictionary []
        and contents =
          [g]
        in
          {Pdfdoc.content = contents;
           Pdfdoc.mediabox = Pdf.Null;
           Pdfdoc.resources = resources;
           Pdfdoc.rotate = Pdfdoc.Rotate0;
           Pdfdoc.rest = Pdf.Dictionary []}
      in
        graphic_of_page pdf fakepage
    and a, b, c, d =
      Pdf.parse_rectangle (Pdf.lookup_fail "no bbox" pdf "/BBox" g)
    in
      {tr_group_colourspace = colourspace;
       isolated = isolated;
       knockout = knockout;
       tr_graphic = graphic}, a, b, c, d

and read_soft_mask pdf mask =
  match
    match Pdf.lookup_direct pdf "/S" mask with
    | Some (Pdf.Name "/Alpha") -> Some Alpha
    | Some (Pdf.Name "/Luminosity") -> Some Luminosity
    | _ -> None
  with
  | None -> None
  | Some subtype ->
      let transparency_group, a, b, c, d =
        match Pdf.lookup_direct pdf "/G" mask with
        | Some g -> read_transparency_group pdf g
        | None -> raise (Pdf.PDFError "Pdfgraphics.transparency group not found in soft mask")
      and backdrop =
        match Pdf.lookup_direct pdf "/BC" mask with
        | Some (Pdf.Array nums) -> Some (map getnum nums)
        | _ -> None
      and transfer =
        match Pdf.lookup_direct pdf "/TR" mask with
        | Some (Pdf.Dictionary d) ->
            Some (Pdffun.parse_function pdf (Pdf.Dictionary d))
        | _ -> None
      in
        Some
          {softmask_subtype = subtype;
           transparency_group = transparency_group;
           backdrop =  backdrop;
           softmask_transfer = transfer;
           softmask_bbox = (a, b, c, d)}

and update_graphics_state_from_dict pdf resources gdict =
  begin match lookup_direct pdf "/SMask" gdict with
  | Some softmask -> (!state).softmask <- read_soft_mask pdf softmask
  | None -> ()
  end;
  begin match lookup_direct pdf "/CA" gdict with
  | Some (Real o) -> (!state).opacity_stroke <- o
  | _ -> ()
  end;
  begin match lookup_direct pdf "/ca" gdict with
  | Some (Real o) -> (!state).opacity_nonstroke <- o
  | _ -> ()
  end;
  begin match lookup_direct pdf "/BM" gdict with
  | Some (Name n)
  | Some (Array (Name n::_)) ->
      (!state).blendmode <- 0 (* FIXME: Do properly *)
  | _ -> ()
  end;
  begin match lookup_direct pdf "/LW" gdict with
    | Some (Integer width) ->
        (!state).linewidth <- float width
    | Some (Real width) ->
        (!state).linewidth <- width
    | _ -> ()
  end;
  begin match lookup_direct pdf "/LC" gdict with
    | Some (Integer style) ->
        (!state).capstyle <- style
    | _ -> ()
  end;
  begin match lookup_direct pdf "/LC" gdict with
    | Some (Integer join) ->
        (!state).joinstyle <- join
    | _ -> ()
  end;
  begin match lookup_direct pdf "/ML" gdict with
    | Some (Integer limit) ->
        (!state).mitrelimit <- float limit
    | Some (Real limit) ->
        (!state).mitrelimit <- limit
    | _ -> ()
  end;
  begin match lookup_direct pdf "/D" gdict with
  | Some (Array [Array dashes; phase]) ->
      let dashnums, phase =
        map
          (function
           | (Integer n) -> float n
           | (Real n) -> n
           | _ -> raise (PDFSemanticError "Malformed dash."))
          dashes,
        match phase with
        | Integer phase -> float phase
        | Real phase -> phase
        | _ -> raise (PDFSemanticError "Malformed dash phase.")
      in
        (!state).dash <- dashnums, phase
  | _ -> ()
  end

and statestack : state list ref = ref []

and copystate () =
  {!state with fill = (!state).fill}

and push_statestack () =
  statestack =| copystate ()

and pop_statestack () =
  match !statestack with
  | [] -> raise (PDFSemanticError "Unbalanced q/Q Ops")
  | h::t -> statestack := t; state := h

and read_tiling_pattern _ =
  ColouredTilingPattern Tiling

and read_function_shading pdf shading =
  let domain =
    match Pdf.lookup_direct pdf "/Domain" shading with
    | Some (Pdf.Array [a; b; c; d]) -> getnum a, getnum b, getnum c, getnum d
    | _ -> 0., 1., 0., 1.
  and matrix =
    Pdf.parse_matrix pdf "/Matrix" shading
  and func =
    Pdf.lookup_fail "No function found" pdf "/Function" shading
  in
    FunctionShading
      {funshading_domain = domain;
       funshading_matrix = matrix;
       funshading_function = Pdffun.parse_function pdf func}

and read_radial_shading pdf shading =
  let coords =
    match Pdf.lookup_direct pdf "/Coords" shading with
    | Some (Pdf.Array [a; b; c; d; e; f]) ->
        getnum a, getnum b, getnum c, getnum d, getnum e, getnum f
    | _ -> raise (Pdf.PDFError "Pdfgraphics.read_radial_shading: no coords in radial shading")
  and domain =
    match Pdf.lookup_direct pdf "/Domain" shading with
    | Some (Pdf.Array [a; b]) -> getnum a, getnum b
    | _ -> 0., 1.
  and func =
    match Pdf.lookup_direct pdf "/Function" shading with
    | Some (Pdf.Array fs) -> map (Pdffun.parse_function pdf) fs
    | Some f -> [Pdffun.parse_function pdf f]
    | _ -> raise (Pdf.PDFError "Pdfgraphics.read_radial_shading: no function in radial shading")
  and extend =
    match Pdf.lookup_direct pdf "/Extend" shading with
    | Some (Pdf.Array [Pdf.Boolean a; Pdf.Boolean b]) -> a, b
    | _ -> false, false
  in
    RadialShading
      {radialshading_coords = coords;
       radialshading_domain = domain;
       radialshading_function = func;
       radialshading_extend = extend}

and read_axial_shading pdf shading =
  let coords =
    match Pdf.lookup_direct pdf "/Coords" shading with
    | Some (Pdf.Array [a; b; c; d]) ->
        getnum a, getnum b, getnum c, getnum d
    | _ -> raise (Pdf.PDFError "Pdfgraphics.read_axial_shading: no coords in radial shading")
  and domain =
    match Pdf.lookup_direct pdf "/Domain" shading with
    | Some (Pdf.Array [a; b]) -> getnum a, getnum b
    | _ -> 0., 1.
  and func =
    match Pdf.lookup_direct pdf "/Function" shading with
    | Some (Pdf.Array fs) -> map (Pdffun.parse_function pdf) fs
    | Some f -> [Pdffun.parse_function pdf f]
    | _ -> raise (Pdf.PDFError "Pdfgraphics.read_axial_shading: no function in radial shading")
  and extend =
    match Pdf.lookup_direct pdf "/Extend" shading with
    | Some (Pdf.Array [Pdf.Boolean a; Pdf.Boolean b]) -> a, b
    | _ -> false, false
  in
    AxialShading
      {axialshading_coords = coords;
       axialshading_domain = domain;
       axialshading_function = func;
       axialshading_extend = extend}

(* Read a shading pattern *)
and read_shading pdf matrix extgstate shading =
  let colourspace =
    Pdf.lookup_fail "No colourspace in shading" pdf "/ColorSpace" shading
  and background =
    Pdf.lookup_direct pdf "/Background" shading
  and bbox =
    Pdf.lookup_direct pdf "/BBox" shading
  and antialias =
    match Pdf.lookup_direct pdf "/BBox" shading with
    | Some (Pdf.Boolean true) -> true
    | _ -> false
  in
    let shading =
      match Pdf.lookup_fail "no /ShadingType" pdf "/ShadingType" shading with
      | Pdf.Integer 1 -> read_function_shading pdf shading
      | Pdf.Integer 3 -> read_radial_shading pdf shading
      | Pdf.Integer 2 -> read_axial_shading pdf shading
      | Pdf.Integer 4 -> FreeFormGouraudShading
      | Pdf.Integer 5 -> LatticeFormGouraudShading
      | Pdf.Integer 6 -> CoonsPatchMesh
      | Pdf.Integer 7 -> TensorProductPatchMesh
      | _ -> raise (Pdf.PDFError "Pdfgraphics.unknown shadingtype")
    in
      {shading_colourspace = colourspace;
       shading_background = background;
       shading_bbox = bbox;
       shading_antialias = antialias;
       shading_matrix = matrix;
       shading_extgstate = extgstate;
       shading = shading}

and read_shading_pattern pdf p =
  let matrix = Pdf.parse_matrix pdf "/Matrix" p
  and extgstate =
    match Pdf.lookup_direct pdf "/ExtGState" p with
    | Some (Pdf.Dictionary _ as d) -> d
    | _ -> Pdf.Dictionary []
  in
    match Pdf.lookup_direct pdf "/Shading" p with
    | Some shading ->
        ShadingPattern (read_shading pdf matrix extgstate shading)
    | _ ->
        raise (Pdf.PDFError "No shading dictionary")

and read_pattern pdf page name =
  match lookup_direct pdf "/Pattern" page.Pdfdoc.resources with
  | None -> raise (Pdf.PDFError "No pattern dictionary")
  | Some patterndict ->
      match lookup_direct pdf name patterndict with
      | None -> raise (Pdf.PDFError "Pattern not found")
      | Some pattern ->
          match lookup_direct pdf "/PatternType" pattern with
          | Some (Pdf.Integer 1) ->
               read_tiling_pattern pattern
          | Some (Pdf.Integer 2) ->
               read_shading_pattern pdf pattern
          | _ -> raise (Pdf.PDFError "unknown pattern")

and process_op pdf page (partial, graphic) op =
  let ret = (partial, graphic) in
  (*i flprint (string_of_state !state); *)
  (*i flprint (Pdfpages.string_of_op op ^ "\n"); i*)
  match op with
  | Op_W ->
      (* Move the current partial path into Clip, and return *)
      begin match partial with
      | PartialPath (_, _, segments, subpaths) ->
          if segments = [] && subpaths = [] then ret else
            let path =
              if segments <> []
                then (Not_hole, Closed, rev segments)::subpaths
                else subpaths
            in
              (!state).clip <- Some (NonZero, path); ret
      | _ -> ret
      end
      (* FIXME: In NextClip needs to support possibly several clips, since we can do W n W n W n f, for instance? *)
  | Op_W' ->
      begin match partial with
      | PartialPath (_, _, segments, subpaths) ->
          if segments = [] && subpaths = [] then ret else
            let path =
              if segments <> []
                then (Not_hole, Closed, rev segments)::subpaths
                else subpaths
            in
              (!state).clip <- Some (EvenOdd, path); ret
      | _ -> ret
      end
  | InlineImage (dict, data) ->
      (NoPartial, GraphicInlineImage (dict, data, (!state).transform)::graphic)
  | Op_MP name ->
      begin match (!state).objectclass with
      | PageDescriptionLevel -> (NoPartial, MCPoint name::graphic)
      | TextObject -> ret (* FIXME -- Add it to the text partial. *)
      | _ -> ret (* Invalid, silently drop *)
      end
  | Op_DP (name, properties) ->
      begin match (!state).objectclass with
      | PageDescriptionLevel ->
          (NoPartial, MCPointProperties (name, properties)::graphic)
      | TextObject -> ret (* FIXME -- Add it to the text partial. *)
      | _ -> ret (* Invalid, silently drop *)
      end
  | Op_BX | Op_EX -> ret    
  | Op_ri n -> (!state).intent <- n; ret
  | Op_j j -> (!state).joinstyle <- j; ret
  | Op_J c -> (!state).capstyle <- c; ret
  | Op_w w -> (!state).linewidth <- w; ret
  | Op_M m -> (!state).mitrelimit <- m; ret
  | Op_q ->
      push_statestack ();
      ret
  | Op_Q ->
      pop_statestack ();
      ret
  | Op_SC vals | Op_SCN vals ->
      (!state).line <- Floats vals;
      ret
  | Op_sc vals | Op_scn vals ->
      (!state).fill <- Floats vals;
      ret
  | Op_scnName (name, vals) when (!state).colourspace_nonstroke = Name "/Pattern" ->
      begin try
        (!state).fill <- Pattern (read_pattern pdf page name);
        ret
      with
        _ -> ret
      end
  | Op_scnName (name, vals) ->
      (!state).fill <- Named (name, vals);
      ret
  | Op_SCNName (name, vals) when (!state).colourspace_stroke = Name "/Pattern" ->
      begin try
        (!state).line <- Pattern (read_pattern pdf page name);
        ret
      with
        _ -> ret
      end
  | Op_SCNName (name, vals) ->
      (!state).line <- Named (name, vals);
      ret
  | Op_CS (("/DeviceGray" | "/DeviceRGB" | "/DeviceCMYK" | "/Pattern") as name) ->
      (!state).colourspace_nonstroke <- Name name;
      (!state).line <- initial_colour pdf page.Pdfdoc.resources (Name name);
      ret
  | Op_CS other ->
      (* Look up in colourspace directory *)
      let space =
        match lookup_direct pdf "/ColorSpace" page.Pdfdoc.resources with
        | None ->
            raise (PDFSemanticError ("Pdfpages: Colourspace not found: " ^ other)) 
        | Some csdict ->
            match lookup_direct pdf other csdict with
            | Some space -> space
            | None -> raise (PDFSemanticError "Pdfpages: colourspace not found")
      in
        (!state).colourspace_nonstroke <- space;
        (!state).line <- initial_colour pdf page.Pdfdoc.resources space;
        ret
  | Op_cs (("/DeviceGray" | "/DeviceRGB" | "/DeviceCMYK" | "/Pattern") as name) ->
      (!state).colourspace_nonstroke <- Name name;
      (!state).fill <- initial_colour pdf page.Pdfdoc.resources (Name name);
      ret
  | Op_cs other ->
      (* Look up in colourspace directory *)
      let space =
        match lookup_direct pdf "/ColorSpace" page.Pdfdoc.resources with
        | None ->
            raise (PDFSemanticError ("Pdfpages: Colourspace not found: " ^ other)) 
        | Some csdict ->
            match lookup_direct pdf other csdict with
            | Some space -> space
            | None -> raise (PDFSemanticError "Pdfpages: colourspace not found")
      in
        (!state).colourspace_nonstroke <- space;
        (!state).fill <- initial_colour pdf page.Pdfdoc.resources space;
        ret
  | Op_G gv ->
      (!state).colourspace_stroke <- Name "/DeviceGray";
      (!state).line <- Floats [gv];
      ret
  | Op_g gv ->
      (!state).colourspace_nonstroke <- Name "/DeviceGray";
      (!state).fill <- Floats [gv];
      ret
  | Op_RG (rv, gv, bv) ->
      (!state).colourspace_stroke <- Name "/DeviceRGB";
      (!state).line <- Floats [rv; gv; bv];
      ret
  | Op_rg (rv, gv, bv) ->
      (!state).colourspace_nonstroke <- Name "/DeviceRGB";
      (!state).fill <- Floats [rv; gv; bv];
      ret
  | Op_K (c, m, y, k) ->
      (!state).colourspace_stroke <- Name "/DeviceCMYK";
      (!state).line <- Floats [c; y; m; k];
      ret
  | Op_k (c, m, y, k) ->
      (!state).colourspace_nonstroke <- Name "/DeviceCMYK";
      (!state).fill <- Floats [c; y; m; k];
      ret
  | Op_gs name ->
      let ext_state_dict = lookup_fail "Bad Op_gs" pdf "/ExtGState" page.Pdfdoc.resources in
        let gdict = lookup_fail "Bad Op_gs" pdf name ext_state_dict in
          update_graphics_state_from_dict pdf page.Pdfdoc.resources gdict;
          ret
  | Op_m (x, y) ->
      (* Begin a new subpath. Get into path mode if not already there. If the last op was an
      [Op_m], it should have no effect. *)
      (!state).objectclass <- PathObject;
      begin match partial with
      | PartialPath (sp, cp, segs, subpaths) ->
          if segs = []
            then PartialPath ((x, y), (x, y), [], subpaths), graphic
            else PartialPath ((x, y), (x, y), [], (Not_hole, Open, rev segs)::subpaths), graphic
      | _ ->
          PartialPath ((x, y), (x, y), [], []), graphic
      end
  | Op_l (x, y) ->
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_l");
      begin match partial with 
      | PartialPath (sp, cp, segs, subpaths) ->
          PartialPath (sp, (x, y), Straight (cp, (x, y))::segs, subpaths), graphic
      | _ ->
          raise (Pdf.PDFError "Pdfgraphics: Op_l")
      end
  | Op_c (a, b, c, d, e, f) ->
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_c");
      begin match partial with 
      | PartialPath (sp, cp, segs, subpaths) ->
          let ep = (e, f) in
            let curve = Bezier (cp, (a, b), (c, d), ep) in
              PartialPath (sp, ep, curve::segs, subpaths), graphic
      | _ ->
          raise (Pdf.PDFError "Pdfgraphics: Op_c")
      end
  | Op_v (a, b, c, d) ->
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_v");
      begin match partial with 
      | PartialPath (sp, cp, segs, subpaths) ->
          let ep = (c, d) in
            let curve = Bezier (cp, cp, (a, b), ep) in
              PartialPath (sp, ep, curve::segs, subpaths), graphic
      | _ ->
          raise (Pdf.PDFError "Pdfgraphics: Op_v")
      end
  | Op_y (a, b, c, d) ->
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_y");
      begin match partial with 
      | PartialPath (sp, cp, segs, subpaths) ->
          let ep = (c, d) in
            let curve = Bezier (cp, (a, b), ep, ep) in
              PartialPath (sp, ep, curve::segs, subpaths), graphic
      | _ ->
          raise (Pdf.PDFError "Pdfgraphics: Op_y")
      end
  | Op_h ->
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_h - not in PathObject");
      begin match partial with 
      | PartialPath (sp, cp, segs, subpaths) ->
          PartialPath (sp, cp, [], (Not_hole, Closed, rev segs)::subpaths), graphic
      | _ ->
          raise (Pdf.PDFError "Pdfgraphics: Op_h - not a partial path")
      end
  | Op_s ->
      (* Close and stroke. Equivalent to h S *)
      process_ops pdf page ret [Op_h; Op_S]
  | Op_b ->
      (* Close, fill, stroke, nonzero. Equivalent to h B *)
      process_ops pdf page ret [Op_h; Op_B]
  | Op_b' ->
      (* Close, fill, stroke, evenodd. Equivalent to h B* *)
      process_ops pdf page ret [Op_h; Op_B']
  | Op_f | Op_F ->
      (* Close and Fill non-zero *)
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_f");
      let partial, graphic = process_op pdf page (partial, graphic) Op_h in
        (!state).objectclass <- PageDescriptionLevel;
        begin match partial with
        | PartialPath (sp, cp, segs, subpaths) ->
            (* segs is empty, due to [Op_h] *)
            PartialPath (sp, cp, [], []),
            Path ((NonZero, rev subpaths), path_attributes_fill ())::graphic
        | _ ->
           raise (Pdf.PDFError "Pdfgraphics: Op_f")
        end
  | Op_S ->
      (* Stroke *)
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_S");
      (!state).objectclass <- PageDescriptionLevel;
      begin match partial with
      | PartialPath (sp, cp, segs, subpaths) ->
          if segs = [] then
            PartialPath (sp, cp, [], []),
            Path ((EvenOdd, rev subpaths), path_attributes_stroke ())::graphic
          else
            PartialPath (sp, cp, [], []),
            Path ((EvenOdd, rev ((Not_hole, Open, rev segs)::subpaths)), path_attributes_stroke ())::graphic
      | _ ->
         raise (Pdf.PDFError "Pdfgraphics: Op_S")
      end
  | Op_B ->
      (* Fill and stroke, non-zero. *)
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_B");
      (!state).objectclass <- PageDescriptionLevel;
      begin match partial with
      | PartialPath (sp, cp, segs, subpaths) ->
          if segs = [] then
            PartialPath (sp, cp, [], []),
            Path ((NonZero, rev subpaths), path_attributes_fill_and_stroke ())::graphic
          else
            PartialPath (sp, cp, [], []),
            Path ((NonZero, rev ((Not_hole, Open, rev segs)::subpaths)), path_attributes_fill_and_stroke ())
            ::graphic
      | _ ->
        raise (Pdf.PDFError "Pdfgraphics: Op_B")
      end
  | Op_B' ->
      (* Fill and stroke, even-odd. *)
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_B*");
      let partial, graphic = process_op pdf page (partial, graphic) Op_h in
        (!state).objectclass <- PageDescriptionLevel;
        begin match partial with
        | PartialPath (sp, cp, segs, subpaths) ->
            if segs = [] then
              PartialPath (sp, cp, [], []),
              Path ((EvenOdd, rev subpaths), path_attributes_fill_and_stroke ())::graphic
            else
              PartialPath (sp, cp, [], []),
              Path ((EvenOdd, rev ((Not_hole, Open, rev segs)::subpaths)), path_attributes_fill_and_stroke ())
              ::graphic
        | _ ->
           raise (Pdf.PDFError "Pdfgraphics: Op_B*")
        end
  | Op_f' ->
      (* Fill, even-odd *)
      if (!state).objectclass <> PathObject then
        raise (Pdf.PDFError "Pdfgraphics: Op_f*");
      (!state).objectclass <- PageDescriptionLevel;
      begin match partial with
      | PartialPath (sp, cp, segs, subpaths) ->
          if segs = [] then
            PartialPath (sp, cp, [], []),
            Path ((EvenOdd, rev subpaths), path_attributes_fill ())::graphic
          else
            PartialPath (sp, cp, [], []),
            Path ((EvenOdd, rev ((Not_hole, Open, rev segs)::subpaths)), path_attributes_fill ())
            ::graphic
      | _ ->
         raise (Pdf.PDFError "Pdfgraphics: Op_f*")
      end
  | Op_n ->
      (* no-op *)
      (!state).objectclass <- PageDescriptionLevel;
      (* for now, until we support clipviews, clean up the polygon *)
      (NoPartial, graphic)
  | Op_re (x, y, w, h) ->
      (* Rectangle. *)
      let ops =
        [Op_m (x, y);
         Op_l (x +. w, y);
         Op_l (x +. w, y +. h);
         Op_l (x, y +. h);
         Op_h]
      in
        process_ops pdf page (partial, graphic) ops
  | Op_Do name ->
      begin match Pdf.lookup_direct pdf "/XObject" page.Pdfdoc.resources with
      | Some d ->
          begin match Pdf.lookup_direct pdf name d with
          | Some xobj ->
              begin match Pdf.lookup_direct pdf "/Subtype" xobj with
              | Some (Pdf.Name "/Image") ->
                  let objnum =
                    match Pdf.find_indirect name d with
                    | None -> raise (Pdf.PDFError "image not found")
                    | Some i -> i
                  in
                    partial,
                    Image
                       ({image_transform = (!state).transform;
                         image_transparency = (!state).opacity_nonstroke;
                         image_softmask = (!state).softmask}
                        , objnum)::graphic
              | Some (Pdf.Name "/Form") ->
                  let elts = read_form_xobject pdf page xobj in
                    partial, rev elts @ graphic
              | _ -> raise (Pdf.PDFError "Unknown kind of xobject")
              end
          | _ -> raise (Pdf.PDFError "Unknown xobject")
          end
      | None -> raise (Pdf.PDFError "xobject not found")
      end
  | Op_cm tr ->
      (!state).transform <- Transform.matrix_compose (!state).transform tr;
      ret
  | (Op_Tc _ | Op_Tw _ | Op_Tz _ | Op_TL _ | Op_Tf _ | Op_Tr _ | Op_Ts _ | Op_Td _ |
     Op_TD _ | Op_Tm _ | Op_T' | Op_Tj _ | Op_TJ _ | Op_' _ | Op_'' _ | Op_d0 _ | Op_d1 _) as op ->
       begin match partial with
       | PartialText t ->
           let st = textstate () in
             PartialText ((st, op)::t), graphic
       | _ ->
         (* If there's no partial text, this is an op affecting the text state but not in a text section. Such ops are allowed. FIXME: Deal with them properly - by ops altering the text state so this can be reflected in the initial state at the start of a text section *)
         ret
       end
  | Op_sh n ->
      let shading =
        let shadingdict = Pdf.lookup_fail "no /Shading" pdf "/Shading" page.Pdfdoc.resources in
          let shading = Pdf.lookup_fail "named shading not found" pdf n shadingdict in
            read_shading pdf Transform.i_matrix Pdf.Null shading
      and currentclip = (!state).clip in
        partial, Shading (currentclip, shading, (!state).transform)::graphic
  | Op_i flatness ->
      if flatness >= 0 && flatness <= 100 then (!state).flatness <- flatness;
      ret
  | Op_d (spec, phase) ->
      (!state).dash <- spec, phase;
      ret
  | Op_Unknown _ -> ret
  | _ -> Printf.eprintf "Operator shouldn't appear at this place"; ret

and getuntil_matching_emc level prev = function
  | (Op_BMC _ | Op_BDC (_, _)) as h::t ->
      getuntil_matching_emc (level + 1) (h::prev) t
  | Op_EMC::t ->
      if level < 0
        then raise (Pdf.PDFError "Too many EMCs\n")
        else if level = 0
          then rev prev, t
          else getuntil_matching_emc (level - 1) (Op_EMC::prev) t
  | h::t -> getuntil_matching_emc level (h::prev) t
  | [] -> raise (Pdf.PDFError "Missing EMC\n")

and getuntil_matching_Q level prev = function
  | Op_q::t -> getuntil_matching_Q (level + 1) (Op_q::prev) t
  | Op_Q::t ->
      if level = 0
        then rev prev, Op_Q::t
        else getuntil_matching_Q (level - 1) (Op_Q::prev) t
  | [] -> rev prev, []
  | h::t -> getuntil_matching_Q level (h::prev) t

and process_ops pdf page (partial, graphic) ops =
  match ops with
  | [] -> partial, rev graphic
  | Op_n::t ->
      (* If there's a NextClip, select all operators within the scope of this
      clip. That is, all operators until an [Op_Q] which puts the stack level
      below the current level or the end of the stream, whichever comes first.*)
      begin match (!state).clip with
      | None ->
          process_ops pdf page (partial, graphic) t
      | Some path ->
          (* We process the operators concerned, putting them inside a Clip,
          and then proceed with the remaining operators (including any [Op_Q]).
          However, to deal with the case of overlapping pairs of marked content
          sections and q/Q pairs (which is allowed). Currently just chuck BDC we don't understand. *)
          let toq, rest = getuntil_matching_Q 0 [] t in
            let _, elts =
              process_ops pdf page (NoPartial, []) toq
            in
              process_ops pdf page (NoPartial, Clip (path, elts)::graphic) rest
      end
  | Op_BMC n::t ->
      (* FIXME: Marked content regions / q/Q pairs overlapping problem *)
      begin try
        let ops, rest = getuntil_matching_emc 0 [] t in
          let partial, graphic' = process_ops pdf page (partial, []) ops in
            process_ops pdf page (partial, MCSection (n, graphic')::graphic) rest
      with
        _ -> process_ops pdf page (partial, graphic) t
      end
  | Op_BDC (n, d)::t ->
      (* FIXME: Marked content regions / q/Q pairs overlapping problem *)
      begin try
        let ops, rest = getuntil_matching_emc 0 [] t in
          let partial, graphic' = process_ops pdf page (partial, []) ops in
            process_ops pdf page (partial, MCSectionProperties (n, d, graphic')::graphic) rest
      with
        _ -> process_ops pdf page (partial, graphic) t
      end
  | Op_BT::t ->
     (* Can't nest text sections, so just get to ET *)
     let textops, rest = cleavewhile (neq Op_ET) t in
       begin match rest with
       | Op_ET::_ | [] ->
          (* We allow blank in case of wrongly nested EMC / ET etc *)
          let more = tail_no_fail rest in
          (* We need to process the ops, and capture the text operations, but state changes inside
          text sections (e.g colour changes) have global effect, so need to keep the state *)
          (!state).objectclass <- TextObject;
          let partial, _ =
            process_ops pdf page (PartialText [], graphic) textops
          in
            begin match partial with
            | PartialText t ->
                let textblock =
                  Text (rev t, {textblock_transform = (!state).transform})
                in
                  process_ops pdf page (partial, textblock::graphic) (Op_ET::more)
            | _ -> raise (Pdf.PDFError "Bad operations in text block")
            end
       | _ ->
         (*i Printf.printf "textops: %s\n\n" (Pdfpages.string_of_ops textops);
         Printf.printf "rest: %s\n\n" (Pdfpages.string_of_ops rest); i*)
         raise (Pdf.PDFError "No Matching Op_ET")
       end
  | Op_ET::t ->
     (!state).objectclass <- PageDescriptionLevel;
     process_ops pdf page (partial, graphic) t
  | h::t -> process_ops pdf page (process_op pdf page (partial, graphic) h) t

(* Load the fonts as (name, pdfobject) pairs *)
and fonts_of_page pdf page =
  match Pdf.lookup_direct pdf "/Font" page.Pdfdoc.resources with
  | Some (Pdf.Dictionary fs) -> fs
  | _ -> []

(* Find the operations of a form xobject. *)
and read_form_xobject pdf page pdfobject =
  let content = [Pdf.direct pdf pdfobject] in
    let pagedict =
      match Pdf.direct pdf page.Pdfdoc.resources with
      | Pdf.Dictionary rs -> rs
      | _ -> []
    and xobjdict =
      match Pdf.direct pdf pdfobject with
      | Pdf.Stream {contents = (dict, _)} ->
          begin match Pdf.lookup_direct pdf "/Resources" dict with
          | Some (Pdf.Dictionary rs) -> rs
          | _ -> []
          end
      | _ -> raise (Pdf.PDFError "bad stream in read_form_xobject")
    in
      let total_resources =
        Pdf.Dictionary (mergedict pagedict xobjdict)
      in
        let fake_page =
          {Pdfdoc.content = [];
           Pdfdoc.mediabox = Pdf.Null;
           Pdfdoc.resources = total_resources;
           Pdfdoc.rotate = Pdfdoc.Rotate0;
           Pdfdoc.rest = Pdf.Dictionary []}
        in
          let _, graphic_elts =
              (process_ops pdf fake_page (NoPartial, [])
              (Pdfpages.parse_operators pdf total_resources content))
          in
            graphic_elts

(* Main function - build a graphic from a page *)
and graphic_of_page pdf page =
  if Pdfcrypt.is_encrypted pdf then
    raise (Pdf.PDFError "Pdfgraphics: File is encrypted")
  else
    begin
      let _, elts =
        let ops =
          Pdfpages.parse_operators pdf page.Pdfdoc.resources page.Pdfdoc.content
        in
          process_ops pdf page (NoPartial, []) ops
      in
        {elements = elts;
         fonts = fonts_of_page pdf page;
         resources = page.Pdfdoc.resources}
    end

let graphic_of_ops ops =
   graphic_of_page
     (Pdf.empty ())
     {(Pdfdoc.blankpage Paper.a4) with
         Pdfdoc.content =
           [Pdf.Stream {contents =
              (Pdf.Dictionary [], Pdf.Got (bytestream_of_string (Pdfpages.string_of_ops ops)))}]}

(* \section{Building a page from a graphic} *)

let int_of_shading_kind = function
  | FunctionShading _ -> 1
  | AxialShading _ -> 2
  | RadialShading _ -> 3
  | FreeFormGouraudShading -> 4
  | LatticeFormGouraudShading -> 5
  | CoonsPatchMesh -> 6
  | TensorProductPatchMesh -> 7

let entries_of_shading pdf s =
  match s.shading with
  | RadialShading r ->
      let coords =
        let a, b, c, d, e, f = r.radialshading_coords in
          Pdf.Array
            [Pdf.Real a; Pdf.Real b; Pdf.Real c; Pdf.Real d; Pdf.Real e; Pdf.Real f]
      and domain =
        let a, b = r.radialshading_domain in
          Pdf.Array
            [Pdf.Real a; Pdf.Real b]
      and funcnum =
        match r.radialshading_function with
        | [f] ->
           Pdf.addobj pdf (Pdffun.pdfobject_of_function pdf f)
        | funs ->
           Pdf.addobj pdf (Pdf.Array (map (Pdffun.pdfobject_of_function pdf) funs))
      and extend =
        Pdf.Array
          [Pdf.Boolean (fst r.radialshading_extend);
           Pdf.Boolean (snd r.radialshading_extend)]
      in
        ["/Coords", coords;
         "/Domain", domain;
         "/Function", Pdf.Indirect funcnum;
         "/Extend", extend]
  | AxialShading a ->
      let coords =
        let a, b, c, d = a.axialshading_coords in
          Pdf.Array
            [Pdf.Real a; Pdf.Real b; Pdf.Real c; Pdf.Real d]
      and domain =
        let a, b = a.axialshading_domain in
          Pdf.Array
            [Pdf.Real a; Pdf.Real b]
      and funcnum =
        match a.axialshading_function with
        | [f] ->
           Pdf.addobj pdf (Pdffun.pdfobject_of_function pdf f)
        | funs ->
           Pdf.addobj pdf (Pdf.Array (map (Pdffun.pdfobject_of_function pdf) funs))
      and extend =
        Pdf.Array
          [Pdf.Boolean (fst a.axialshading_extend);
           Pdf.Boolean (snd a.axialshading_extend)]
      in
        ["/Coords", coords;
         "/Domain", domain;
         "/Function", Pdf.Indirect funcnum;
         "/Extend", extend]
  | _ -> []

let shading_object_of_shading pdf s =
  let background =
    match s.shading_background with
    | None -> []
    | Some b -> ["/Background", b]
  and bbox =
    match s.shading_bbox with
    | None -> []
    | Some b -> ["/BBox", b]
  in
    Pdf.Dictionary
      (["/ShadingType", Pdf.Integer (int_of_shading_kind s.shading);
       "/ColorSpace", s.shading_colourspace;
       "/AntiAlias", Pdf.Boolean s.shading_antialias]
      @ background @ bbox @ entries_of_shading pdf s)

let pattern_object_of_pattern xobject_level opdo_matrix pdf = function
  | ShadingPattern s ->
      begin try
        let shading_matrix =
          if xobject_level > 0 then
            let inverted = Transform.matrix_invert opdo_matrix in
              Transform.matrix_compose inverted s.shading_matrix
          else
            s.shading_matrix
        in
          Pdf.Dictionary
            ["/Type", Pdf.Name "/Pattern";
             "/PatternType", Pdf.Integer 2;
             "/Shading", shading_object_of_shading pdf s;
             "/Matrix", Pdf.make_matrix shading_matrix]
      with
        Transform.NonInvertable -> raise (Pdf.PDFError "Pdfgraphics.Bad pattern")
      end
  | _ ->
      Printf.eprintf "Unknown pattern\n";
      Pdf.Dictionary []

(* Output a move and line/curve ops. *)
let ops_of_segs segs closure =
  let raw_seg_ops =
    map
      (function
       | Straight (_, (x, y)) -> Op_l (x, y)
       | Bezier (_, (bx, by), (cx, cy), (dx, dy)) -> Op_c (bx, by, cx, cy, dx, dy))
      segs
  and get_move = function
    | Straight ((x, y), _) | Bezier ((x, y), _, _, _) -> Op_m (x, y)
  in
    (* Predicate: Do we need to close this subpath? *)
    match segs with
    | [] -> []
    | h::_ -> get_move h::raw_seg_ops @ (if closure = Closed then [Op_h] else [])

let protect ops =
  [Op_q] @ ops @ [Op_Q]

let attribute_ops_of_path (_, a) =
  [Op_w a.path_linewidth;
   Op_J a.path_capstyle;
   Op_j a.path_joinstyle;
   Op_M a.path_mitrelimit;
   Op_ri a.path_intent]

let transform_ops_of_path (_, a) =
  [Op_cm a.path_transform]

let stroke_ops_of_path ((winding, _), a) =
  match winding, a.path_fill, a.path_line with
  | _, None, None -> Op_n
  | EvenOdd, Some _, Some _ -> Op_B'
  | EvenOdd, Some _, None -> Op_f'
  | NonZero, Some _, Some _ -> Op_B
  | NonZero, Some _, None -> Op_f
  | _, None, Some _ -> Op_S

let path_ops_of_path (_, subpaths) =
  flatten (map (fun (_, closure, segs) -> ops_of_segs segs closure) subpaths)

let ops_of_path pdf page (((winding, subpaths), a) as p) =
  (* Add a colourspace returning new resources and a new name, or return the name it's already held under. *)
  let name_of_colourspace cs resources =
    match cs with
    | Pdf.Name (("/DeviceGray" | "/DeviceRGB" | "/DeviceCMYK" | "/Pattern") as str) -> resources, str
    | _ ->
      let existing_colourspacedict =
        match lookup_direct pdf "/ColorSpace" resources with
        | Some ((Dictionary _) as d) -> d
        | _ -> Dictionary []
      in
        (* FIXME: For now, we just always create a new one. Must search to see if it's already there for efficiency. *)
        let name = unique_key "cs" existing_colourspacedict in
          let newcolourspacedict = add_dict_entry existing_colourspacedict name cs in
            add_dict_entry resources "/ColorSpace" newcolourspacedict, name
  in
  let resources = page.Pdfdoc.resources in
  let attribute_ops = attribute_ops_of_path p
  and transform = transform_ops_of_path p
  and stroke_op = stroke_ops_of_path p in
  let colours_stroke, resources =
    match a.path_line with
    | Some (cs, Floats vals) ->
        let resources', name = name_of_colourspace cs resources in
        [Op_CS name; Op_SCN vals], resources
    | Some (cs, Named (n, vals)) ->
        let resources', name = name_of_colourspace cs resources in
          [Op_CS name; Op_SCNName (n, vals)], resources'
    | _ -> [], resources
  in
  let colours_nonstroke, resources =
    match a.path_fill with
    | Some (cs, Floats vals) ->
        let resources', name = name_of_colourspace cs resources in
          [Op_cs name; Op_scn vals], resources'
    | Some (cs, Named (n, vals)) ->
        let resources', name = name_of_colourspace cs resources in
          [Op_cs name; Op_scnName (n, vals)], resources'
    | Some (_, Pattern p) ->
        (* Build /Pattern cs and reference to pattern, having built the
        pattern in the pattern dictionary *)
        let pattern = pattern_object_of_pattern (!state).in_xobject (!state).opdo_matrix pdf p in
         let resources, name =
           let existing_patterndict =
             match lookup_direct pdf "/Pattern" resources with
             | Some ((Dictionary _) as d) -> d
             | _ -> Dictionary []
           in
             let name = unique_key "pt" existing_patterndict in
               let newpatterndict = add_dict_entry existing_patterndict name pattern in
                 add_dict_entry page.Pdfdoc.resources "/Pattern" newpatterndict, name
        in
          [Op_cs "/Pattern"; Op_scnName (name, [])], resources
    | _ -> [], resources
  in
  let gs, resources =
    if a.path_transparency.fill_transparency < 1. || a.path_transparency.line_transparency < 1.
      then
         let resources, name =
           let existing_extgstate =
             match lookup_direct pdf "/ExtGState" resources with
             | Some ((Dictionary _) as d) -> d
             | _ -> Dictionary []
           in
             let name = unique_key "gs" existing_extgstate
             and gsdict =
               Dictionary
                 [("/ca", Real a.path_transparency.fill_transparency);
                  ("/CA", Real a.path_transparency.line_transparency)]
             in
               let new_extgstate = add_dict_entry existing_extgstate name gsdict in
                 add_dict_entry page.Pdfdoc.resources "/ExtGState" new_extgstate, name
         in
            [Op_gs name], resources
      else
        [], resources
  in
   let path_ops = path_ops_of_path (winding, subpaths) in
     protect (gs @ transform @ attribute_ops @ colours_stroke @ colours_nonstroke @ path_ops @ [stroke_op]),
     resources

let ops_of_textstate st = []

let ops_of_textpiece (st, op) =
  ops_of_textstate st @ [op]

(* Upon entry to this, the transformation matrix is identity *)
let ops_of_text tr ops =
  protect ([Op_cm tr; Op_BT] @ (flatten <| map ops_of_textpiece ops) @ [Op_ET])

(* Transform a bounding box by a given matrix *)
let extreme_of_4 f a b c d =
  hd <| sort f [a; b; c; d]

let min_of_4 = extreme_of_4 compare

let max_of_4 = extreme_of_4 (fun a b -> ~-(compare a b))

let transform_bbox tr l b r t =
  let (x0, y0) = Transform.transform_matrix tr (l, t)
  and (x1, y1) = Transform.transform_matrix tr (l, b)
  and (x2, y2) = Transform.transform_matrix tr (r, t)
  and (x3, y3) = Transform.transform_matrix tr (r, b) in
    min_of_4 x0 x1 x2 x3,
    min_of_4 y0 y1 y2 y3,
    max_of_4 x0 x1 x2 x3,
    max_of_4 y0 y1 y2 y3

(* Build a transparency group xobject, add it to the pdf and return its object number *)
let rec pdfobject_of_transparency_group (a, b, c, d) pdf t =
  (!state).in_xobject <- (!state).in_xobject + 1;
  let r =
    let page = page_of_graphic pdf (0., 0., 0., 0.) t.tr_graphic
    and group_attributes =
      let cs =
        match t.tr_group_colourspace with 
        | None -> []
        | Some pdfobject -> ["/CS", pdfobject]
      in
        Pdf.Dictionary
          (["/Type", Pdf.Name "/Group";
            "/S", Pdf.Name "/Transparency";
            "/I", Pdf.Boolean t.isolated;
            "/K", Pdf.Boolean t.knockout] @ cs)
    in
      let extras =
        ["/Type", Pdf.Name "/XObject";
         "/Subtype", Pdf.Name "/Form";
         "/BBox", Pdf.Array [Pdf.Real a; Pdf.Real b; Pdf.Real c; Pdf.Real d];
         "/Resources", page.Pdfdoc.resources;
         "/Group", group_attributes]
      in
        match page.Pdfdoc.content with
        | Pdf.Stream ({contents = Pdf.Dictionary dict, Got data})::_ ->
            Pdf.addobj pdf (Pdf.Stream ({contents = Pdf.Dictionary (extras @ dict), Got data}))
        | _ -> raise (Pdf.PDFError "Pdfgraphics: Bad page content")
  in
    (!state).in_xobject <- (!state).in_xobject - 1;
    r

and pdfobject_of_softmask pdf m =
  let bc =
    match m.backdrop with
    | None -> []
    | Some fs -> ["/BC", Pdf.Array (map (function x -> Pdf.Real x) fs)]
  and tr =
    match m.softmask_transfer with
    | None -> []
    | Some f -> ["/TR", Pdffun.pdfobject_of_function pdf f]
  in
    Pdf.addobj pdf
      (Pdf.Dictionary
        (["/Type", Pdf.Name "/Mask";
         "/S", Pdf.Name (match m.softmask_subtype with Alpha -> "/Alpha" | Luminosity -> "/Luminosity");
         "/G", Pdf.Indirect (pdfobject_of_transparency_group m.softmask_bbox pdf m.transparency_group)]
        @ bc @ tr))

and ops_of_image pdf page (a, i) =
  (!state).opdo_matrix <- a.image_transform;
  let resources = page.Pdfdoc.resources in
    let ops, resources =
      let opgs, resources =
        if a.image_transparency < 1. || a.image_softmask <> None
          then
             let resources, name =
               let existing_extgstate =
                 match lookup_direct pdf "/ExtGState" page.Pdfdoc.resources with
                 | Some ((Dictionary _) as d) -> d
                 | _ -> Dictionary []
               in
                 let name = unique_key "gs" existing_extgstate
                 and gsdict =
                   let softmask =
                     match a.image_softmask with
                     | None -> []
                     | Some m -> ["/SMask", Pdf.Indirect (pdfobject_of_softmask pdf m)]
                   in
                     Dictionary
                       ([("/ca", Real a.image_transparency)] @ softmask)
                 in
                   let new_extgstate = add_dict_entry existing_extgstate name gsdict in
                     add_dict_entry resources "/ExtGState" new_extgstate, name
             in
                [Op_gs name], resources
          else
            [], resources
      in
        [Op_cm a.image_transform] @ opgs @ [Op_Do ("/Im" ^ string_of_int i)], resources
    in
      protect ops, resources

and ops_of_shading pdf page path shading transform =
  let resources', name =
    (* Add new entry to shading dictionary, return its name, new resources *)
    let existing_shadingdict =
      match lookup_direct pdf "/Shading" page.Pdfdoc.resources with
      | Some ((Dictionary _) as d) -> d
      | _ -> Dictionary []
    in
      let name = unique_key "sh" existing_shadingdict
      and objnum = Pdf.addobj pdf (shading_object_of_shading pdf shading) in
        let shadingref = Pdf.Indirect objnum in
          let new_shadingdict = add_dict_entry existing_shadingdict name shadingref in
            let r =
              add_dict_entry page.Pdfdoc.resources "/Shading" new_shadingdict
            in
              r, name
  in
    let ops =
      let pathops, clipops =
       match path with
       | None -> [], []
       | Some p ->
           path_ops_of_path p, [Op_W; Op_n] (* FIXME: Even-odd vs Non-Zero *)
      in
        pathops @ clipops @ [Op_cm transform; Op_sh name]
    in
      protect ops, resources'

and ops_of_graphic_acc pdf page oplists = function
  | [] ->
      flatten (rev oplists), page
  | Path p::t ->
      let ops, resources' = ops_of_path pdf page p in
        let page' = {page with Pdfdoc.resources = resources'} in
          ops_of_graphic_acc pdf page' (ops::oplists) t
  | Image (attr, i)::t ->
      let ops, resources' = ops_of_image pdf page (attr, i) in
        let page' = {page with Pdfdoc.resources = resources'} in
          ops_of_graphic_acc pdf page' (ops::oplists) t
  | Text (ts, {textblock_transform = tr})::t ->
      let ops = ops_of_text tr ts in
        ops_of_graphic_acc pdf page (ops::oplists) t
  | MCSection (n, graphic)::t ->
      let oplist, page' =
        ops_of_graphic_acc pdf page [] graphic
      in
        ops_of_graphic_acc pdf page' (([Op_BMC n] @ oplist @ [Op_EMC])::oplists) t
  | MCSectionProperties (n, d, graphic)::t ->
      let oplist, page' =
        ops_of_graphic_acc pdf page [] graphic
      in
        ops_of_graphic_acc pdf page' (([Op_BDC (n, d)] @ oplist @ [Op_EMC])::oplists) t
  | MCPoint n::t ->
      ops_of_graphic_acc pdf page ([Op_MP n]::oplists) t
  | MCPointProperties (n, d)::t ->
      ops_of_graphic_acc pdf page ([Op_DP (n, d)]::oplists) t
  | GraphicInlineImage (dict, data, tr)::t ->
      ops_of_graphic_acc pdf page (protect [Op_cm tr; InlineImage (dict, data)]::oplists) t
  | Clip ((w, _) as p, elts)::t ->
      let ops, page' =
        let path_ops =
          [Op_cm (!state).transform] @ path_ops_of_path p 
        and clipviewops =
          [if w = NonZero then Op_W else Op_W'; Op_n]
        and insideclipops, page' =
          ops_of_graphic_acc pdf page [] elts
        in
          protect (path_ops @ clipviewops @ insideclipops), page'
      in
        ops_of_graphic_acc pdf page' (ops::oplists) t
   | Shading (path, shading, transform)::t ->
       let ops, resources' = ops_of_shading pdf page path shading transform in
         let oplists'= protect ops::oplists
         and page' = {page with Pdfdoc.resources = resources'} in
           ops_of_graphic_acc pdf page' oplists' t

(* Build a page from a graphic in the same PDF. *)
and image_numbers_of_elts prev = function
  | Image (_, i)::t -> image_numbers_of_elts (i::prev) t
  | MCSection (_, elts)::t
  | MCSectionProperties (_, _, elts)::t
  | Clip (_, elts)::t ->
      let these = image_numbers_of_elts [] elts in
        image_numbers_of_elts (these @ prev) t
  | _::t -> image_numbers_of_elts prev t
  | [] -> prev

and make_xobjects pdf elts =
  let numbers = image_numbers_of_elts [] elts in
    setify <| map (function n -> ("/Im" ^ string_of_int n), Pdf.Indirect n) numbers

and make_resources pdf g page' =
  let resources =
    match g.resources with
    | Pdf.Dictionary rs -> rs
    | _ -> []
  and fontdict =
    Pdf.Dictionary g.fonts
  and xobjdict =
    let objs = make_xobjects pdf g.elements in
      Pdf.Dictionary objs
  and resources_frompage =
    match page'.Pdfdoc.resources with
    | Pdf.Dictionary d -> d
    | _ -> raise (Assert_failure ("", 0, 0))
  in
    let resources = remove "/Shading" resources in
    let resources = remove "/Pattern" resources in
    let resources = remove "/ExtGState" resources in
    let resources = remove "/ColorSpace" resources in
      (* [fold_right] so that entries overwrite *)
      Pdf.Dictionary
        (fold_right
           (fun (k, v) d -> add k v d)
           ["/Font", fontdict; "/XObject", xobjdict]
           (resources_frompage @ resources))

and page_of_graphic pdf (xmin, ymin, xmax, ymax) graphic =
  let page =
    Pdfdoc.custompage (Pdf.Array [Pdf.Real xmin; Pdf.Real ymin; Pdf.Real xmax; Pdf.Real ymax])
  in
    let ops, page' = ops_of_graphic_acc pdf page [] graphic.elements in
      (* We're not including the ExtGState because it's in the page', so need
      to merge with resources *)
      let resources = make_resources pdf graphic page' in
        {page' with
           Pdfdoc.content = [Pdfpages.stream_of_ops ops];
           Pdfdoc.resources = resources}

let ops_of_simple_graphic graphic =
  fst (ops_of_graphic_acc (Pdf.empty ()) (Pdfdoc.blankpage Paper.a4) [] graphic.elements)

(* FIXME Add in here a function to copy a page/graphic from one document to another *)

let streams_of_simple_graphic g =
  (page_of_graphic (Pdf.empty ()) (0., 0., 600., 400.) g).Pdfdoc.content

(* Transforming a graphic *)
let transform_segment tr s =
  let f = Transform.transform_matrix tr in
    match s with
    | Straight (x, y) -> Straight (f x, f y)
    | Bezier (a, b, c, d) -> Bezier (f a, f b, f c, f d)

let transform_subpath tr (h, c, segments) =
  (h, c, map (transform_segment tr) segments)

let transform_path tr (w, subpaths) =
  (w, map (transform_subpath tr) subpaths)

let transform_element tr = function
  | Path (pth, attr) -> Path (transform_path tr pth, attr)
  | x -> x (* FIXME: Add rest of elements. *)

let transform_graphic tr g =
  {g with elements = map (transform_element tr) g.elements}