summaryrefslogtreecommitdiff
path: root/Xprint/ps/psout.c
blob: 66764401c965bd67eb5bb86084a81a226233723f (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
/* $Xorg: psout.c,v 1.9 2001/03/26 15:25:12 coskrey Exp $ */
/*

Copyright 1996, 1998  The Open Group

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

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

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

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

*/
/*
 * (c) Copyright 1996 Hewlett-Packard Company
 * (c) Copyright 1996 International Business Machines Corp.
 * (c) Copyright 1996, 2000 Sun Microsystems, Inc.  All Rights Reserved.
 * (c) Copyright 1996 Novell, Inc.
 * (c) Copyright 1996 Digital Equipment Corp.
 * (c) Copyright 1996 Fujitsu Limited
 * (c) Copyright 1996 Hitachi, Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject
 * to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Except as contained in this notice, the names of the copyright holders
 * shall not be used in advertising or otherwise to promote the sale, use
 * or other dealings in this Software without prior written authorization
 * from said copyright holders.
 */

/*******************************************************************
**
**    *********************************************************
**    *
**    *  File:          psout.c
**    *
**    *  Contents:      Code to output PostScript to file
**    *
**    *  Created By:    Roger Helmendach (Liberty Systems)
**    *
**    *  Copyright:     Copyright 1996 The Open Group, Inc.
**    *
**    *********************************************************
**
********************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <X11/os.h>
#define USE_PSOUT_PRIVATE 1
#include "psout.h"
#ifdef XP_USE_FREETYPE
#include <ft2build.h>
#include FT_FREETYPE_H
#endif /* XP_USE_FREETYPE */
/* For VENDOR_STRING and VENDOR_RELEASE */
#include "site.h"

extern PsElmPtr PsCloneFillElementList(int nElms, PsElmPtr elms);
extern void PsDestroyFillElementList(int nElms, PsElmPtr elms);

/*
 *  Standard definitions
 */

static char *S_StandardDefs = "\
/d{def}bind def\
/b{bind}bind d\
/bd{b d}b d\
/x{exch}bd\
/xd{x d}bd\
/dp{dup}bd\
/t{true}bd\
/f{false}bd\
/p{pop}bd\
/r{roll}bd\
/c{copy}bd\
/i{index}bd\
/rp{repeat}bd\
/n{newpath}bd\
/w{setlinewidth}bd\
/lc{setlinecap}bd\
/lj{setlinejoin}bd\
/sml{setmiterlimit}bd\
/ds{setdash}bd\
/ie{ifelse}bd\
/len{length}bd\
/m{moveto}bd\
/rm{rmoveto}bd\
/l{lineto}bd\
/rl{rlineto}bd\
/a{arc}bd\
/an{arcn}bd\
/st{stroke}bd\
/fl{fill}bd\
/ef{eofill}bd\
/sp{showpage}bd\
/cp{closepath}bd\
/clp{clippath}bd\
/cl{clip}bd\
/pb{pathbbox}bd\
/tr{translate}bd\
/rt{rotate}bd\
/dv{div}bd\
/ml{mul}bd\
/ad{add}bd\
/ng{neg}bd\
/scl{scale}bd\
/sc{setrgbcolor}bd\
/g{setgray}bd\
/gs{gsave}bd\
/gr{grestore}bd\
/sv{save}bd\
/rs{restore}bd\
/mx{matrix}bd\
/cm{currentmatrix}bd\
/sm{setmatrix}bd\
/ccm{concatmatrix}bd\
/cc{concat}bd\
/ff{findfont}bd\
/mf{makefont}bd\
/sf{setfont}bd\
/cft{currentfont}bd\
/fd{FontDirectory}bd\
/sh{show}bd\
/stw{stringwidth}bd\
/ci{colorimage}bd\
/ig{image}bd\
/im{imagemask}bd\
/cf{currentfile}bd\
/rh{readhexstring}bd\
/str{string}bd\
/al{aload}bd\
/wh{where}bd\
/kn{known}bd\
/stp{stopped}bd\
/bg{begin}bd\
/ed{end}bd\
/fa{forall}bd\
/pi{putinterval}bd\
/mk{mark}bd\
/ctm{cleartomark}bd\
/df{definefont}bd\
/cd{currentdict}bd\
/db{20 dict dp bg}bd\
/de{ed}bd\
/languagelevel wh{p languagelevel}{1}ie\
 1 eq{/makepattern{p}bd/setpattern{p}bd/setpagedevice{p}bd}if\
/mp{makepattern}bd\
/spt{setpattern}bd\
/spd{setpagedevice}bd\
"
#ifdef XP_USE_FREETYPE
"/trmoveto{currentfont /FontMatrix get transform rm}d"
#endif /* XP_USE_FREETYPE */
;

/*
 *  Composite definitions
 *
 *
 *    XYr  -  Return X/Y dpi for device
 *
 *      XYr <xdpi> <ydpi>
 *
 *    Cs  -  Coordinate setup (for origin upper left)
 *
 *      <orient(0,1,2,3)> Cs
 *
 *    P  -  Draw a point
 *
 *      <x> <y> P
 *
 *    R  -  Add rectangle to path
 *
 *      <x> <y> <w> <h> R
 *
 *    Ac  -  Add arc to path
 *
 *      <x> <y> <w> <h> <ang1> <ang2> Ac
 *
 *    An  -  Add arc to path (counterclockwise)
 *
 *      <x> <y> <w> <h> <ang1> <ang2> An
 *
 *    Tf  -  Set font
 *
 *      <font_name> <size> <iso> Tf
 *
 *    Tfm  -  Set font with matrix
 *
 *      <font_name> <matrix> <iso> Tfm
 *
 *    T  -  Draw text
 *
 *      <text> <x> <y> T
 *
 *    Tb  -  Draw text with background color
 *
 *      <text> <x> <y> <bg_red> <bg_green> <bg_blue> Tb
 *
 *    Im1  -  Image 1 bit monochrome imagemask
 *
 *      <x> <y> <w> <h> <sw> <sh> Im1
 *
 *    Im24  -  Image 24 bit RGB color
 *
 *      <x> <y> <w> <h> <sw> <sh> Im24
 *
 *    Im1t  -  Image 1 bit monochrome imagemask (in tile)
 *
 *      <data> <x> <y> <w> <h> <sw> <sh> Im1t
 *
 *    Im24t  -  Image 24 bit RGB color (in tile)
 *
 *      <data> <x> <y> <w> <h> <sw> <sh> Im24t
 */

static char *S_CompositeDefs = "\
/XYr{/currentpagedevice wh\
  {p currentpagedevice dp /HWResolution kn\
    {/HWResolution get al p}{p 300 300}ie}{300 300}ie}bd\
/Cs{dp 0 eq{0 pHt tr XYr -1 x dv 72 ml x 1 x dv 72 ml x scl}if\
  dp 1 eq{90 rt XYr -1 x dv 72 ml x 1 x dv 72 ml x scl}if\
  dp 2 eq{pWd 0 tr XYr 1 x dv 72 ml x -1 x dv 72 ml x scl}if\
  3 eq{pHt pWd tr 90 rt XYr 1 x dv 72 ml x -1 x dv 72 ml x scl}if}bd\
/P{gs 1 w [] 0 ds 2 c m .1 ad x .1 ad x l st gr}bd\
/R{4 2 r m 1 i 0 rl 0 x rl ng 0 rl cp}bd\
/Ac{mx_ cm p 6 -2 r tr 4 2 r ng scl 0 0 .5 5 3 r a mx_ sm}bd\
/An{mx_ cm p 6 -2 r tr 4 2 r ng scl 0 0 .5 5 3 r an mx_ sm}bd\
/ISO{dp len dict bg{1 i/FID ne{d}{p p}ie}fa\
  /Encoding ISOLatin1Encoding d cd ed df}bd\
/iN{dp len str cvs dp len x 1 i 3 ad str 2 c c p x p dp 3 -1 r(ISO)pi}bd\
/Tp{{x dp iN dp fd x kn{x p dp/f_ x d ff}{dp/f_ x d x ff ISO}ie x}\
  {x dp/f_ x d ff x}ie}bd\
/Tf{Tp[x 0 0 2 i ng 0 0] dp/fm_ x d mf sf}bd\
/Tfm{Tp 1 -1 tm1_ scl tm2_ ccm dp/fm_ x d mf sf}bd\
/T{m sh}bd\
/Tb{gs sc f_ ff sf cft/FontMatrix get 3 get\
  cft/FontBBox get dp 1 get x 3 get 2 i ml 3 1 r ml\
  0 0 m 4 i stw p 4 i 4 i m fm_ cc\
  0 2 i rl dp 0 rl 0 2 i ng rl 0 3 i rl ng 0 rl cp fl p p\
  gr T}bd\
/Im1{6 4 r tr scl t [3 i 0 0 5 i 0 0]{cf str1 rh p} im}bd\
/Im1rev{6 4 r tr scl f [3 i 0 0 5 i 0 0]{cf str1 rh p} im}bd\
/Im24{gs 6 4 r tr scl 8 [3 i 0 0 5 i 0 0]{cf str3 rh p} f 3 ci}bd\
/Im1t{6 4 r tr scl t [3 i 0 0 5 i 0 0]{} im}bd\
/Im24t{gs 6 4 r tr scl 8 [3 i 0 0 5 i 0 0]{} f 3 ci}bd\
/ck2{/currentpagedevice wh \
{p dp currentpagedevice dp 3 -1 r kn \
{x get al p 3 -1 r eq 3 1 r eq and } \
{p p p p t}ie} \
{p p p t}ie}bd \
/ck1{/currentpagedevice wh \
{p dp currentpagedevice dp 3 -1 r kn \
{x get eq} {p p p t}ie} \
{p p t}ie}bd \
/mtx{scl t [3 i 0 0 5 i 0 0]}bd \
";

char *pg_orient[] = {"Portrait","Landscape","Reverse Portrait","Reverse Landscape"};
/*
 *  Setup definitions
 */

static char *S_SetupDefs = "\
 /mx_ mx d\
 /im_ mx d\
 /tm1_ mx d\
 /tm2_ mx d\
 /str3 3 str d\
 /str1 1 str d\
";

/*******************************************************************
 *                       PRIVATE FUNCTIONS                         *
 *******************************************************************/

void
S_Flush(PsOutPtr self)
{
  int len;
  
  if( self->Buf[0] == '\0' )
    return;
  
  len = strlen(self->Buf);

  /* Append a newline char ('\n') if there isn't one there already */
  if( self->Buf[len-1] != '\n' )
  {
    self->Buf[len++] = '\n';
    self->Buf[len]   = '\0';
  }

  (void)fwrite(self->Buf, len, 1, self->Fp);

  self->Buf[0] = '\0';
}

static void
S_Comment(PsOutPtr self, char *comment)
{
  S_Flush(self);
  strcpy(self->Buf, comment);
  S_Flush(self);
}

static void
S_OutDefs(PsOutPtr self, char *defs)
{
  int  i, k=0;
  S_Flush(self);
  memset(self->Buf, 0, sizeof(self->Buf));
  for( i=0 ; defs[i]!='\0' ;)
  {
    if( k>70 && (i==0 || (i && defs[i-1]!='/')) &&
        (defs[i]==' ' || defs[i]=='/' || defs[i]=='{') )
    {
      S_Flush(self);
      k = 0;
      memset(self->Buf, 0, sizeof(self->Buf));
    }
    if( k && self->Buf[k-1]==' ' && defs[i]==' ' ) { i++; continue; }
    self->Buf[k] = defs[i];
    k++; i++;
  }
  S_Flush(self);
}

void
S_OutNum(PsOutPtr self, float num)
{
  int  i;
  char buf[64];
  int  len;

  sprintf(buf, "%.3f", num);

  /* Remove any zeros at the end */
  for( i=strlen(buf)-1 ; buf[i]=='0' ; i-- ); buf[i+1] = '\0';
  /* Remove '.' if it is the last character */
  i = strlen(buf)-1; if( buf[i]=='.' ) buf[i] = '\0';

  len = strlen(self->Buf);
  if( len > 0 )
  {
    self->Buf[len++] = ' ';
    self->Buf[len]   = '\0';
  } 
  strcpy(&self->Buf[len], buf);
  if( (len+i)>70 ) S_Flush(self);
}

static void
S_OutStr(PsOutPtr self, char *txt, int txtl)
{
  int  i, k;
  char buf[1024];
  for( i=0,k=0 ; i<txtl ; i++ )
  {
    if( (txt[i]>=' ' && txt[i]<='~') &&
        txt[i]!='(' && txt[i]!=')' && txt[i]!='\\' )
      { buf[k] = txt[i]; k++; continue; }
    buf[k] = '\\'; k++;
    sprintf(&buf[k], "%03o", txt[i]&0xFF);
    /* Skip to the end of the buffer */
    while( buf[k] != '\0' )
      k++;
  }
  strcat(self->Buf, "(");
  i = strlen(self->Buf);
  memcpy(&self->Buf[i], buf, k);
  self->Buf[i+k] = '\0';
  strcat(self->Buf, ")");
  if( strlen(self->Buf)>70 ) S_Flush(self);
}

/* Same as S_OutStr() but takes |short *| instead of |char *| */
static void
S_OutStr16(PsOutPtr self, unsigned short *txt, int txtl)
{
  int  i, k;
  char buf[2048];
  for( i=0,k=0 ; i<txtl ; i++ )
  {
    if( (txt[i]>=' ' && txt[i]<='~') &&
        txt[i]!='(' && txt[i]!=')' && txt[i]!='\\' )
      { buf[k] = txt[i]; k++; continue; }
    buf[k] = '\\'; k++;
    sprintf(&buf[k], "%03o", txt[i]&0xFFFF);
    /* Skip to the end of the buffer */
    while( buf[k] != '\0' )
      k++;
  }
  strcat(self->Buf, "(");
  i = strlen(self->Buf);
  memcpy(&self->Buf[i], buf, k);
  self->Buf[i+k] = '\0';
  strcat(self->Buf, ")");
  if( strlen(self->Buf)>70 ) S_Flush(self);
}

void
S_OutTok(PsOutPtr self, char *tok, int cr)
{
  int len = strlen(self->Buf);
  if( len > 0 )
  {
    self->Buf[len++] = ' ';
    self->Buf[len]   = '\0';
  } 
  strcpy(&self->Buf[len], tok);
  if( cr ) S_Flush(self);
}

static void
S_Color(PsOutPtr self, PsOutColor clr)
{
  int   ir, ig, ib;
  ir = PSOUTCOLOR_TO_REDBITS(clr);
  ig = PSOUTCOLOR_TO_GREENBITS(clr);
  ib = PSOUTCOLOR_TO_BLUEBITS(clr);
  if( ir==ig && ig==ib )
    { S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ir)); S_OutTok(self, "g", 1); }
  else
  {
    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ir));
    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ig));
    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ib));
    S_OutTok(self, "sc", 1);
  }
}

static void
S_SetPageDevice(PsOutPtr self, int orient, int count, int plex, int res,
                int wd, int ht, int isPage)
{
    float fwd = ((float)wd/(float)res)*72.;
    float fht = ((float)ht/(float)res)*72.;

#define USE_WORKAROUND_COPY_COUNT_BUG 1

#ifdef USE_WORKAROUND_COPY_COUNT_BUG
    /* Workaround (see http://xprint.mozdev.org/bugs/show_bug.cgi?id=1861 -
     * 'Need workaround for bug 1378 ...') to avoid that we print n^2 copies
     * instead of n copies.
     * The problem is that we use both /NumCopies here but pass the
     * %copy-count% to the spooler, too.
     * But we only have to use _one_ way...
     *
     * The final fix for bug 1378 (http://xprint.mozdev.org/bugs/show_bug.cgi?id=1378 -
     * "PS DDX creates n^2 copies of a job instead of n copies") will back this
     * workaround out and replace it with a better solution.
     * (see mozilla.org bug 140030
     * (http://bugzilla.mozilla.org/show_bug.cgi?id=140030 - "Setting number
     * of copies causes too many copies to print") for the initial report for
     * this issue...)
     */
    count = 1;
#endif /* USE_WORKAROUND_COPY_COUNT_BUG */

    S_OutTok(self, "/pWd", 0);
    S_OutNum(self, fwd);
    S_OutTok(self, "d /pHt", 0);
    S_OutNum(self, fht);
    S_OutTok(self, "d", 1);

  /*
   * if these are page attributes, have PostScript check to see if they
   * have changed.  If not, don't do setpagedevice, since it will cause
   * a page flush and screw up duplex printing.  Having PostScript check
   * means we don't have to keep track ourselves.
   */
    if(isPage) {
      S_OutNum(self, (float) orient);
      S_OutTok(self, "/Orientation ck1", 0);
      S_OutTok(self, "pWd pHt /PageSize ck2 and not {", 1);
    }
    S_OutTok(self, "{db", 0);

    S_OutTok(self, "/Orientation", 0);
    S_OutNum(self, (float) orient);
    S_OutTok(self, " d ", 0);
    S_OutTok(self, "/PageSize [pWd pHt] d", 0);

    S_OutTok(self, " de spd", 0);
    /*
   * save a flag to show if we failed to set orientation... determined
   * by both/either Orientation and/or PageSize, use this
   * later to set/not set orientation using Cs command.
   */
    S_OutTok(self,"}stp /orientationFailed x d", 1);
    /*
   * if these are page attributes, have PostScript check to see if they
   * have changed.  If not, don't do setpagedevice, since it will cause
   * a page flush and screw up duplex printing.  Having PostScript check
   * means we don't have to keep track ourselves.
   */
    if(isPage)
    {
      S_OutTok(self,"}if",1);

      S_OutTok(self, (plex==0)?"f":"t", 0);
      S_OutTok(self, "/Duplex ck1 ", 0);

      S_OutTok(self, (plex==2)?"t":"f", 0);
      S_OutTok(self, "/Tumble ck1 and ", 0);


      S_OutNum(self, (float)res);
      S_OutNum(self, (float)res);
      S_OutTok(self, " /HWResolution ck2 and", 0);
      
      if( count>1 )
      {
          S_OutNum(self, (float)count);
          S_OutTok(self, " /NumCopies", 0);
          S_OutTok(self, " ck1 and ", 0);
      }
      S_OutTok(self," not {",1);
    }
    S_OutTok(self, "{db", 0);

    S_OutTok(self, "/Duplex ", 0);
    S_OutTok(self, (plex==0)?"f":"t", 0);
    S_OutTok(self, " d ", 0);

    S_OutTok(self, "/Tumble ", 0);
    S_OutTok(self, (plex==2)?"t":"f", 0);
    S_OutTok(self, " d ", 0);
  
    S_OutTok(self, " /HWResolution [", 0);
    S_OutNum(self, (float)res);
    S_OutNum(self, (float)res);
    S_OutTok(self, "] d ", 0);

    if( count>1 )
    {
      S_OutTok(self, " /NumCopies", 0);
      S_OutNum(self, (float)count);
      S_OutTok(self, " d ", 0);
    }
    S_OutTok(self, " de spd}stp p", 1);

    if(isPage)
    {
      S_OutTok(self, "}if", 1);
    }
}

/*******************************************************************
 *                        PUBLIC FUNCTIONS                         *
 *******************************************************************/

FILE *
PsOut_ChangeFile(PsOutPtr self, FILE *fp)
{
  FILE *nfp;

  nfp = self->Fp;

  self->Fp = fp;

  return nfp;
}

PsOutPtr
PsOut_BeginFile(FILE *fp, char *title, int orient, int count, int plex, int res,
                int wd, int ht, Bool raw)
{
  int  i;
  char buffer[256+32]; /* enougth space for a title with 256 chars... */
/*
 *  Get ready to output PostScript header
 */
  PsOutPtr psout;
  psout = (PsOutPtr)xalloc(sizeof(PsOutRec));
  memset(psout, 0, sizeof(PsOutRec));
  psout->Fp = fp;
  psout->isRaw = raw;
  psout->pagenum = 0;

  if (!raw) {
/*
 *  Output PostScript header
 */
      /* GhostScript will rant about the missing BoundingBox if we use
       * "%!PS-Adobe-3.0 EPSF-3.0" here... */
      S_Comment(psout, "%!PS-Adobe-3.0");
#ifdef XP_USE_FREETYPE
      {
        FT_Int ftmajor = 0,
               ftminor = 0,
               ftpatch = 0; 
        extern FT_Library ftypeLibrary; /* defined in xc/lib/font/FreeType/ftfuncs.c */

        FT_Library_Version(ftypeLibrary, &ftmajor, &ftminor, &ftpatch);
        sprintf(buffer, 
                "%%%%Creator: The X Print Server's PostScript DDX "
                "(%s, release %d, FreeType version %d.%d.%d)",
                VENDOR_STRING, VENDOR_RELEASE,
                (int)ftmajor, (int)ftminor, (int)ftpatch);
      }
#else
      sprintf(buffer, 
              "%%%%Creator: The X Print Server's PostScript DDX (%s, release %d)",
              VENDOR_STRING, VENDOR_RELEASE);
#endif /* XP_USE_FREETYPE */
      S_Comment(psout, buffer);

      if (title)
      {
        sprintf(buffer, "%%%%Title: %.256s", title);
        S_Comment(psout, buffer);
      }
      S_Comment(psout, "%%EndComments");
      S_Comment(psout, "%%BeginProlog");
      S_Comment(psout, "%%BeginProcSet: XServer_PS_Functions");
      S_OutDefs(psout, S_StandardDefs);
      S_OutDefs(psout, S_CompositeDefs);
      S_Comment(psout, "%%EndProcSet");
      S_Comment(psout, "%%EndProlog");
      S_Comment(psout, "%%BeginSetup");
      /* set document level page attributes */
      S_SetPageDevice(psout, orient, count, plex, res, wd, ht, 0);
      S_Comment(psout, "%%Pages: atend");
      S_OutDefs(psout, S_SetupDefs);
      S_Comment(psout, "%%EndSetup");
  }
/*
 *  Initialize the structure
 */
  psout->CurColor    = PSOUTCOLOR_NOCOLOR;
  psout->LineWidth   = 1;
  psout->LineCap     = PsCButt;
  psout->LineJoin    = PsJMiter;
  psout->NDashes     = 0;
  psout->Dashes      = (int *)0;
  psout->FontName    = (char *)0;
  psout->FontSize    = 0;
  psout->start_image = 0;
  for( i=0 ; i<4 ; i++ ) psout->FontMtx[i] = 0.;
  psout->ImageFormat = 0;
  return(psout);
}

void
PsOut_EndFile(PsOutPtr self, int closeFile)
{
  char coms[50];
  int  i;
  
  if (!self)
    return;

  if (!self->isRaw) {
      S_Comment(self,"%%Trailer");
      sprintf(coms,"%%%%Pages: %d", self->pagenum);
      S_Comment(self, coms);
      S_Comment(self, "%%EOF");
  }
  if( self->NDashes && self->Dashes ) xfree(self->Dashes);
  if( self->FontName ) xfree(self->FontName);
  if( self->Patterns ) xfree(self->Patterns);
  if( self->Clip.rects ) xfree(self->Clip.rects);
  if( closeFile ) fclose(self->Fp);
  xfree(self);
}

void
PsOut_BeginPage(PsOutPtr self, int orient, int count, int plex, int res,
                int wd, int ht)
{
  char coms[50];

/*** comment for pagenumbers *****/

  S_Comment(self,"%%PageHeader");
  self->pagenum++;
  sprintf(coms,"%%%%Page: %d %d", self->pagenum, self->pagenum);
  S_Comment(self, coms);
  sprintf(coms,"%%%%PageOrientation: %s",pg_orient[orient]);
  S_Comment(self, coms);

/*** end comment *****************/

  /* set page level page attributes */
  S_SetPageDevice(self, orient, count, plex, res, wd, ht, 1);
  
  S_OutTok(self, "gs ", 0);
  /*
   * check to see if we set orientation already; if it wasn't set,
   * use Cs to set orientation here.
   */
  S_OutNum(self, (float)orient);
  S_OutTok(self, "orientationFailed { ", 0);
  S_OutNum(self, (float)orient);
  S_OutTok(self, " } { 0 }ie Cs 100 sml gs", 1);
}

void
PsOut_EndPage(PsOutPtr self)
{
  S_OutTok(self, "gr gr sp", 1);

  /* did grestore: mark attributes 'dirty' so they will be re-sent */
  PsOut_DirtyAttributes(self);

/*** comment for pagenumbers *****/

  S_Comment(self,"%%PageTrailer");

/*** end comment *****************/
}

void
PsOut_DirtyAttributes(PsOutPtr self)
{
  int  i;
  self->CurColor    = PSOUTCOLOR_NOCOLOR;
  self->LineWidth   = -1;
  self->LineCap     = (PsCapEnum)-1;
  self->LineJoin    = (PsJoinEnum)-1;
  self->NDashes     = -1;
  self->FontSize    = -1;
  for( i=0 ; i<4 ; i++ ) self->FontMtx[i] = -1.;
  if( self->Dashes   ) { xfree(self->Dashes);   self->Dashes   = (int *)0;  }
  if( self->FontName ) { xfree(self->FontName); self->FontName = (char *)0; }
}

void
PsOut_Comment(PsOutPtr self, char *comment)
{
  S_Comment(self, comment);
}

void
PsOut_Offset(PsOutPtr self, int x, int y)
{
  self->XOff = x;
  self->YOff = y;
}

void
PsOut_Clip(PsOutPtr self, int clpTyp, PsClipPtr clpinf)
{
  int  i, k;
  int  changed = 0;
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InTile ) return;
  if( self->InFrame ) xo = yo = 0;
  if( clpTyp!=self->ClipType ) changed = 1;
  else
  {
    if( clpinf->nRects!=self->Clip.nRects ) changed = 1;
    else
    {
      if( clpinf->nOutterClips!=self->Clip.nOutterClips ) changed = 1;
      else
      {
        for( i=0 ; i<clpinf->nOutterClips ; i++ )
        {
          if( memcmp(&clpinf->outterClips[i], &self->Clip.outterClips[i],
                     sizeof(PsRectRec))!=0 ) break;
        }
        if( i<clpinf->nOutterClips ) changed = 1;
        else
        {
          for( i=0 ; i<clpinf->nRects ; i++ )
          {
            if( memcmp(&clpinf->rects[i], &self->Clip.rects[i],
                       sizeof(PsRectRec))!=0 ) { changed = 1; break; }
          }
        }
      }
    }
    if( clpinf->nElms!=self->Clip.nElms ) changed = 1;
    else
    {
      for( i=0 ; i<clpinf->nElms ; i++ )
      {
        if( clpinf->elms[i].type!=PSOUT_POINTS )
        {
          if( memcmp(&clpinf->elms[i], &self->Clip.elms[i],
                     sizeof(PsElmRec))!=0 ) { changed = 1; break; }
        }
        else
        {
          if( clpinf->elms[i].type!=self->Clip.elms[i].type ||
              clpinf->elms[i].nPoints!=self->Clip.elms[i].nPoints )
            { changed = 1; break; }
          else
          {
            for( k=0 ; k<clpinf->elms[i].nPoints ; k++ )
            {
              if( memcmp(&clpinf->elms[i].c.points[k],
                         &self->Clip.elms[i].c.points[k], sizeof(PsPointRec)) )
                { changed = 1; break; }
            }
            if( changed ) break;
          }
        }
      }
    }
  }

  if( self->Clip.rects )       xfree(self->Clip.rects);
  if( self->Clip.outterClips ) xfree(self->Clip.outterClips);
  if( self->Clip.elms )
    PsDestroyFillElementList(self->Clip.nElms, self->Clip.elms);
  self->ClipType          = clpTyp;
  self->Clip.nRects       = clpinf->nRects;
  self->Clip.nElms        = clpinf->nElms;
  self->Clip.nOutterClips = clpinf->nOutterClips;
  if( clpinf->nRects )
  {
    self->Clip.rects = (PsRectPtr)xalloc(clpinf->nRects*sizeof(PsRectRec));
    memcpy(self->Clip.rects, clpinf->rects, clpinf->nRects*sizeof(PsRectRec));
  }
  else self->Clip.rects = 0;
  if( clpinf->nOutterClips )
  {
    self->Clip.outterClips = (PsRectPtr)xalloc(clpinf->nOutterClips*
					       sizeof(PsRectRec));
    memcpy(self->Clip.outterClips, clpinf->outterClips,
           clpinf->nOutterClips*sizeof(PsRectRec));
  }
  else self->Clip.outterClips = 0;
  if( clpinf->nElms )
    self->Clip.elms = PsCloneFillElementList(clpinf->nElms, clpinf->elms);
  else self->Clip.elms = 0;

  PsOut_DirtyAttributes(self);
  S_OutTok(self, "gr gs", 1);
  if( self->Clip.nOutterClips )
  {
    for( i=0 ; i<self->Clip.nOutterClips ; i++ )
    {
      S_OutNum(self, (float)(self->Clip.outterClips[i].x));
      S_OutNum(self, (float)(self->Clip.outterClips[i].y));
      S_OutNum(self, (float)self->Clip.outterClips[i].w);
      S_OutNum(self, (float)self->Clip.outterClips[i].h);
      S_OutTok(self, "R", 1);
    }
    S_OutTok(self, "cl n", 1);
  }
  if( self->Clip.nRects )
  {
    for( i=0 ; i<self->Clip.nRects ; i++ )
    {
      S_OutNum(self, (float)(self->Clip.rects[i].x+xo));
      S_OutNum(self, (float)(self->Clip.rects[i].y+yo));
      S_OutNum(self, (float)self->Clip.rects[i].w);
      S_OutNum(self, (float)self->Clip.rects[i].h);
      S_OutTok(self, "R", 1);
    }
    S_OutTok(self, "cl n", 1);
  }
  if( self->Clip.nElms )
  {
    PsElmPtr elm = self->Clip.elms;
    for( i=0 ; i<self->Clip.nElms ; i++,elm++ )
    {
      switch(elm->type)
      {
        case PSOUT_POINTS:
          for( k=0 ; k<elm->nPoints ; k++ )
          {
            S_OutNum(self, (float)elm->c.points[k].x+xo);
            S_OutNum(self, (float)elm->c.points[k].y+yo);
            if( k==0 ) S_OutTok(self, "m", 0);
            else       S_OutTok(self, "l", 0);
          }
          S_OutTok(self, "cp", 1);
          break;
        case PSOUT_RECT:
          S_OutNum(self, (float)elm->c.rect.x+xo);
          S_OutNum(self, (float)elm->c.rect.y+yo);
          S_OutNum(self, (float)elm->c.rect.w);
          S_OutNum(self, (float)elm->c.rect.h);
          S_OutTok(self, "R", 1);
          break;
        case PSOUT_ARC:
          if( elm->c.arc.style==PsPieSlice )
          {
            S_OutNum(self, (float)elm->c.arc.x+xo+(float)elm->c.arc.w/2.);
            S_OutNum(self, (float)elm->c.arc.y+yo+(float)elm->c.arc.h/2.);
            S_OutTok(self, "m", 0);
          }
          S_OutNum(self, (float)elm->c.arc.x+xo+(float)elm->c.arc.w/2.);
          S_OutNum(self, (float)elm->c.arc.y+yo+(float)elm->c.arc.h/2.);
          S_OutNum(self, (float)elm->c.arc.w);
          S_OutNum(self, (float)elm->c.arc.h);
          S_OutNum(self, (float)elm->c.arc.a1/64.);
          S_OutNum(self, (float)elm->c.arc.a1/64.+(float)elm->c.arc.a2/64.);
          if( elm->c.arc.a2<0 ) S_OutTok(self, "An cp", 1);
          else                  S_OutTok(self, "Ac cp", 1);
          break;
      }
    }
    S_OutTok(self, "cl n", 1);
  }
}

void
PsOut_Color(PsOutPtr self, PsOutColor clr)
{
  if( clr==self->CurColor || self->InTile>=PsStip ) return;
  self->CurColor = clr;
  S_Color(self, clr);
}

void
PsOut_FillRule(PsOutPtr self, PsRuleEnum rule)
{
  self->FillRule = rule;
}

void
PsOut_LineAttrs(PsOutPtr self, int wd, PsCapEnum cap, PsJoinEnum join,
                int nDsh, int *dsh, int dshOff, PsOutColor bclr)
{
  int         i;
  int         same = 1;

  if( wd!=self->LineWidth && wd>=0 )
  {
    if( wd==0 ) wd = 1;
    self->LineWidth = wd;
    S_OutNum(self, (float)wd); S_OutTok(self, "w", 1);
  }
  if( cap!=self->LineCap )
  {
    self->LineCap = cap;
    S_OutNum(self, (float)cap); S_OutTok(self, "lc", 1);
  }
  if( join!=self->LineJoin )
  {
    self->LineJoin = join;
    S_OutNum(self, (float)join); S_OutTok(self, "lj", 1);
  }
  if( nDsh!=self->NDashes ) same = 0;
  else if( dshOff!=self->DashOffset ) same = 0;
  else if( nDsh )
  {
    for( i=0 ; i<nDsh ; i++ )
      { if( dsh[i]!=self->Dashes[i] ) break; }
    if( i<nDsh ) same = 0;
  }
  if( !same )
  {
    if( self->NDashes && self->Dashes )
      { xfree(self->Dashes); self->Dashes = (int *)0; }
    self->NDashes    = nDsh;
    self->DashOffset = dshOff;
    if( nDsh ) self->Dashes = (int *)xalloc(sizeof(int)*nDsh);
    S_OutTok(self, "[", 0);
    for( i=0 ; i<nDsh ; i++ )
    {
      self->Dashes[i] = dsh[i];
      S_OutNum(self, (float)dsh[i]);
    }
    S_OutTok(self, "]", 0);
    S_OutNum(self, (float)dshOff);
    S_OutTok(self, "ds", 1);
  }

  if( nDsh )
    self->LineBClr = bclr;
  else
    bclr = PSOUTCOLOR_NOCOLOR;
}

void
PsOut_TextAttrs(PsOutPtr self, char *fnam, int siz, int iso)
{
  int       i;
  char      buf[256];
  if( self->FontName && strcmp(fnam, self->FontName)==0 &&
      siz==self->FontSize ) return;
  if( self->FontName ) xfree(self->FontName);
  self->FontName = (char *)xalloc(strlen(fnam)+1);
  strcpy(self->FontName, fnam);
  self->FontSize = siz;
  for( i=0 ; i<4 ; i++ ) self->FontMtx[i] = -1.;
  strcpy(buf, "/"); strcat(buf, fnam);
  S_OutTok(self, buf, 0);
  S_OutNum(self, (float)siz);
  if( iso ) S_OutTok(self, "t", 0);
  else      S_OutTok(self, "f", 0);
  S_OutTok(self, "Tf", 1);
}

void
PsOut_TextAttrsMtx(PsOutPtr self, char *fnam, float *mtx, int iso)
{
  int       i;
  char      buf[256];
  if( self->FontName && strcmp(fnam, self->FontName)==0 &&
      mtx[0]==self->FontMtx[0] && mtx[1]==self->FontMtx[1] &&
      mtx[2]==self->FontMtx[2] && mtx[3]==self->FontMtx[3] ) return;
  if( self->FontName ) xfree(self->FontName);
  self->FontName = (char *)xalloc(strlen(fnam)+1);
  strcpy(self->FontName, fnam);
  for( i=0 ; i<4 ; i++ ) self->FontMtx[i] = mtx[i];
  self->FontSize = -1;
  strcpy(buf, "/"); strcat(buf, fnam); strcat(buf, " [");
  S_OutTok(self, buf, 0);
  for( i=0 ; i<4 ; i++ ) S_OutNum(self, mtx[i]);
  S_OutTok(self, "0 0]", 0);
  if( iso ) S_OutTok(self, "t", 0);
  else      S_OutTok(self, "f", 0);
  S_OutTok(self, "Tfm", 1);
}

void
PsOut_Polygon(PsOutPtr self, int nPts, PsPointPtr pts)
{
  int  i;
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  if( nPts<=2 ) return;
  for( i=0 ; i<nPts ; i++ )
  {
    S_OutNum(self, (float)(pts[i].x+xo));
    S_OutNum(self, (float)(pts[i].y+yo));
    if( i==0 ) S_OutTok(self, "m", 0);
    else       S_OutTok(self, "l", 0);
  }
  if( self->FillRule==PsEvenOdd ) S_OutTok(self, "cp ef", 1);
  else                            S_OutTok(self, "cp fl", 1);
}

void
PsOut_FillRect(PsOutPtr self, int x, int y, int w, int h)
{
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  S_OutNum(self, (float)x);
  S_OutNum(self, (float)y);
  S_OutNum(self, (float)w);
  S_OutNum(self, (float)h);
  S_OutTok(self, "R fl", 1);
}

void
PsOut_FillArc(PsOutPtr self, int x, int y, int w, int h,
	      float ang1, float ang2, PsArcEnum style)
{
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  if( style==PsPieSlice )
  {
    S_OutNum(self, (float)x+(float)w/2.);
    S_OutNum(self, (float)y+(float)h/2.);
    S_OutTok(self, "m", 0);
  }
  S_OutNum(self, (float)x+(float)w/2.);
  S_OutNum(self, (float)y+(float)h/2.);
  S_OutNum(self, (float)w);
  S_OutNum(self, (float)h);
  S_OutNum(self, ang1);
  S_OutNum(self, ang1+ang2);
  if( ang2<0 ) S_OutTok(self, "An cp fl", 1);
  else         S_OutTok(self, "Ac cp fl", 1);
}

void
PsOut_Lines(PsOutPtr self, int nPts, PsPointPtr pts)
{
  int  i;
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  if( nPts<1 ) return;
  for( i=0 ; i<nPts ; i++ )
  {
    S_OutNum(self, (float)(pts[i].x+xo));
    S_OutNum(self, (float)(pts[i].y+yo));
    if( i==0 ) S_OutTok(self, "m", 0);
    else       S_OutTok(self, "l", 0);
  }
  if( self->LineBClr != PSOUTCOLOR_NOCOLOR )
  {
    S_OutTok(self, "gs", 0);
    S_Color(self, self->LineBClr);
    S_OutTok(self, "[] 0 ds st gr", 0);
  }
  S_OutTok(self, "st", 1);
}

void
PsOut_Points(PsOutPtr self, int nPts, PsPointPtr pts)
{
  int  i;
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  if( nPts<1 ) return;
  for( i=0 ; i<nPts ; i++ )
  {
    S_OutNum(self, (float)(pts[i].x+xo));
    S_OutNum(self, (float)(pts[i].y+yo));
    S_OutTok(self, "P", 1);
  }
}

void
PsOut_DrawRect(PsOutPtr self, int x, int y, int w, int h)
{
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  S_OutNum(self, (float)x);
  S_OutNum(self, (float)y);
  S_OutNum(self, (float)w);
  S_OutNum(self, (float)h);
  S_OutTok(self, "R", 0);
  if( self->LineBClr != PSOUTCOLOR_NOCOLOR )
  {
    S_OutTok(self, "gs", 0);
    S_Color(self, self->LineBClr);
    S_OutTok(self, "[] 0 ds st gr", 0);
  }
  S_OutTok(self, "st", 1);
}

void
PsOut_DrawArc(PsOutPtr self, int x, int y, int w, int h, 
	      float ang1, float ang2)
{
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  S_OutNum(self, (float)x+(float)w/2.);
  S_OutNum(self, (float)y+(float)h/2.);
  S_OutNum(self, (float)w);
  S_OutNum(self, (float)h);
  S_OutNum(self, ang1);
  S_OutNum(self, ang1+ang2);
  if( ang2<0 ) S_OutTok(self, "An", 0);
  else         S_OutTok(self, "Ac", 0);
  if( self->LineBClr != PSOUTCOLOR_NOCOLOR )
  {
    S_OutTok(self, "gs", 0);
    S_Color(self, self->LineBClr);
    S_OutTok(self, "[] 0 ds st gr", 0);
  }
  S_OutTok(self, "st", 1);
}

void
PsOut_Text(PsOutPtr self, int x, int y, char *text, int textl, PsOutColor bclr)
{
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  S_OutStr(self, text, textl);
  S_OutNum(self, (float)x);
  S_OutNum(self, (float)y);
  if( bclr == PSOUTCOLOR_NOCOLOR )
    S_OutTok(self, "T", 1);
  else
  {
    int ir = PSOUTCOLOR_TO_REDBITS(bclr);
    int ig = PSOUTCOLOR_TO_GREENBITS(bclr);
    int ib = PSOUTCOLOR_TO_BLUEBITS(bclr);

    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ir));
    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ig));
    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ib));
    S_OutTok(self, "Tb", 1);
  }
}

void
PsOut_Text16(PsOutPtr self, int x, int y, unsigned short *text, int textl, PsOutColor bclr)
{
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  S_OutStr16(self, text, textl);
  S_OutNum(self, (float)x);
  S_OutNum(self, (float)y);
  if( bclr == PSOUTCOLOR_NOCOLOR )
    S_OutTok(self, "T", 1);
  else
  {
    int ir = PSOUTCOLOR_TO_REDBITS(bclr);
    int ig = PSOUTCOLOR_TO_GREENBITS(bclr);
    int ib = PSOUTCOLOR_TO_BLUEBITS(bclr);
    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ir));
    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ig));
    S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ib));
    S_OutTok(self, "Tb", 1);
  }
}

#ifdef BM_CACHE
void  /* new */
PsOut_ImageCache(PsOutPtr self, int x, int y, long cache_id, PsOutColor bclr, PsOutColor fclr)
{
  char cacheID[10];
  int xo = self->XOff;
  int yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  sprintf(cacheID, "c%di", cache_id);

  S_OutNum(self, (float)x);
  S_OutNum(self, (float)y);

  if( fclr==PSOUTCOLOR_WHITE )
  {
    int ir = PSOUTCOLOR_TO_REDBITS(bclr);
    int ig = PSOUTCOLOR_TO_GREENBITS(bclr);
    int ib = PSOUTCOLOR_TO_BLUEBITS(bclr);

    if( ir==ig && ig==ib )
      S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ir));
    else
      S_OutNum(self, (float)0);
      self->RevImage = 1;
    }
  else
  {
    int ir = PSOUTCOLOR_TO_REDBITS(fclr);
    int ig = PSOUTCOLOR_TO_GREENBITS(fclr);
    int ib = PSOUTCOLOR_TO_BLUEBITS(fclr);

    if( ir==ig && ig==ib )
      S_OutNum(self, PSOUTCOLOR_BITS_TO_PSFLOAT(ir));
    else
      S_OutNum(self, (float)0);
  }

  S_OutTok(self, cacheID, 1);
}     /* new */

void  /* new */
PsOut_BeginImageCache(PsOutPtr self, long cache_id)
{
  char cacheID[10];

  sprintf(cacheID, "/c%di {", cache_id);

  S_OutTok(self, cacheID, 0);
}     /* new */

void  /* new */
PsOut_EndImageCache(PsOutPtr self)
{
  S_OutTok(self, "}bd", 1);
}     /* new */
#endif

void
PsOut_BeginImage(PsOutPtr self, PsOutColor bclr, PsOutColor fclr, int x, int y,
                 int w, int h, int sw, int sh, int format)
{
  PsOutColor savClr = self->CurColor;
  int xo = self->XOff;
  int yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  if( self->InTile )
  {
    if( self->InTile>=PsStip && format!=1 ) { self->ImgSkip = 1; return; }
    self->ImgBClr = bclr; self->ImgFClr = fclr;
    self->ImgX    = x;    self->ImgY    = y;
    self->ImgW    = w;    self->ImgH    = h;
    self->SclW    = sw;   self->SclH    = sh;
    S_OutTok(self, "<", 0);
    self->ImageFormat = format;
    self->RevImage = 0;
    if( self->InTile==PsTile && format==1 && fclr==PSOUTCOLOR_WHITE )
      self->RevImage = 1;
    return;
  }

  self->RevImage = 0;
  if( format==1 )
  {
    S_OutTok(self, "gs", 0);
    if( fclr==PSOUTCOLOR_WHITE )
    {
      PsOut_Color(self, fclr);
      PsOut_FillRect(self, x, y, sw, sh);
      PsOut_Color(self, bclr);
      self->RevImage = 1;
    }
    else
    {
      PsOut_Color(self, bclr);
      PsOut_FillRect(self, x, y, sw, sh);
      PsOut_Color(self, fclr);
    }
  }
  S_OutNum(self, (float)x);
  S_OutNum(self, (float)y);
  S_OutNum(self, (float)w);
  S_OutNum(self, (float)h);
  S_OutNum(self, (float)sw);
  S_OutNum(self, (float)sh);
  if( format==1 ) {
	if(self->RevImage) 
	    S_OutTok(self, "Im1rev", 1);
	else
	    S_OutTok(self, "Im1", 1);
  }
  else            S_OutTok(self, "Im24", 1);
  self->ImageFormat = format;
  self->CurColor    = savClr;
}

void
PsOut_BeginImageIM(PsOutPtr self, PsOutColor bclr, PsOutColor fclr, int x, int y,
                 int w, int h, int sw, int sh, int format)
{
  PsOutColor savClr = self->CurColor;
  int xo = self->XOff;
  int yo = self->YOff;

  if( self->InFrame || self->InTile ) xo = yo = 0;
  x += xo; y += yo;
  if( self->InTile )
  {
    if( self->InTile>=PsStip && format!=1 ) { self->ImgSkip = 1; return; }
    self->ImgBClr = bclr; self->ImgFClr = fclr;
    self->ImgX    = x;    self->ImgY    = y;
    self->ImgW    = w;    self->ImgH    = h;
    self->SclW    = sw;   self->SclH    = sh;
    S_OutTok(self, "<", 0);
    self->ImageFormat = format;
    self->RevImage = 0;
    if( self->InTile==PsTile && format==1 && fclr==PSOUTCOLOR_WHITE )
      self->RevImage = 1;
    return;
  }

  self->RevImage = 0;
  if( format==1 )
  {
    S_OutTok(self, "gs", 0);
#ifdef BM_CACHE
    S_OutTok(self, "g", 1);
#else
    if( fclr==PSOUTCOLOR_WHITE )
    {
      PsOut_Color(self, bclr);
      self->RevImage = 1;
    }
    else
    {
      PsOut_Color(self, fclr);
    }
#endif
  }

#ifdef BM_CACHE
  S_OutTok(self, "tr", 0);    /* new */
#else
  S_OutNum(self, (float)x);
  S_OutNum(self, (float)y);
#endif
  S_OutNum(self, (float)w);
  S_OutNum(self, (float)h);
  S_OutNum(self, (float)sw);
  S_OutNum(self, (float)sh);
#ifdef BM_CACHE
  S_OutTok(self, "mtx", 1);   /* new */
  S_OutTok(self, "<", 0);     /* new */
  self->start_image = 1;
#else
  if( format==1 ){
        if(self->RevImage)
            S_OutTok(self, "Im1rev", 1);
        else
            S_OutTok(self, "Im1", 1);
  }
  else      S_OutTok(self, "Im24", 1);
#endif
  self->ImageFormat = format;
  self->CurColor    = savClr;
}

void
PsOut_EndImage(PsOutPtr  self)
{
  if( self->ImgSkip ) { self->ImgSkip = 0; return; }
  if( self->InTile )
  {
    S_OutTok(self, ">", 1);
    if( self->ImageFormat==1 && self->InTile==PsTile )
    {
      if( self->ImgFClr==PSOUTCOLOR_WHITE )
      {
        PsOut_Color(self, self->ImgFClr);
        PsOut_FillRect(self, self->ImgX, self->ImgY, self->SclW, self->SclH);
        PsOut_Color(self, self->ImgBClr);
      }
      else
      {
        PsOut_Color(self, self->ImgBClr);
        PsOut_FillRect(self, self->ImgX, self->ImgY, self->SclW, self->SclH);
        PsOut_Color(self, self->ImgFClr);
      }
    }
    S_OutNum(self, (float)self->ImgX);
    S_OutNum(self, (float)self->ImgY);
    S_OutNum(self, (float)self->ImgW);
    S_OutNum(self, (float)self->ImgH);
    S_OutNum(self, (float)self->SclW);
    S_OutNum(self, (float)self->SclH);
    if( self->ImageFormat==1 ) S_OutTok(self, "Im1t", 1);
    else                       S_OutTok(self, "Im24t", 1);
    self->ImageFormat = 0;
    self->RevImage    = 0;
    return;
  }
  /*
   * Bug 4639307: Move flush before "> im" to get all of bitmap into ps file.
   */
  S_Flush(self);
#ifdef BM_CACHE
  if(self->start_image)
    S_OutTok(self, "> im", 1);       /* new */
#endif
  self->ImageFormat = 0;
  self->RevImage    = 0;
#ifdef BM_CACHE
  if(self->start_image)
  {
    self->start_image = 0;
    S_OutTok(self, "gr", 0);
  }
  else
    S_OutTok(self, "gr", 1);
#else
  S_OutTok(self, "gr", 1);
#endif
}

void
PsOut_OutImageBytes(PsOutPtr self, int nBytes, char *bytes)
{
  int   i;
  int   b;
  int   len;
  const char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7',
                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

  if( (!self->ImageFormat) || self->ImgSkip ) return;

  len = strlen(self->Buf);

  for( i=0 ; i<nBytes ; i++ )
  {
    if( self->RevImage ) b = (int)((bytes[i]^0xFF)&0xFF);
    else                 b = (int)(bytes[i]&0xFF);
    
    self->Buf[len++] = hex[(b&0xF0) >> 4];
    self->Buf[len++] = hex[(b&0x0F)];
    self->Buf[len] = '\0';

    if( len>70 ) 
    {
      S_Flush(self);
      len = 0;
    }
  }
}

void
PsOut_BeginFrame(PsOutPtr self, int xoff, int yoff, int x, int y,
                 int w, int h)
{
  int  xo = self->XOff;
  int  yo = self->YOff;

  if( self->InFrame ) xo = yo = 0;
  S_OutTok(self, "gs", 0);
  S_OutNum(self, (float)(x+xo));
  S_OutNum(self, (float)(y+yo));
  S_OutNum(self, (float)w);
  S_OutNum(self, (float)h);
  S_OutTok(self, "R cl n", 0);
  xoff += xo; yoff += yo;
  if( xoff || yoff )
  {
    S_OutNum(self, (float)xoff);
    S_OutNum(self, (float)yoff);
    S_OutTok(self, "tr", 0);
  }
  S_OutTok(self, "gs", 1);
  self->InFrame += 1;
}

void
PsOut_EndFrame(PsOutPtr self)
{
  self->InFrame -= 1;
  if( self->InFrame<0 ) self->InFrame = 0;
  S_OutTok(self, "gr gr", 1);
  PsOut_DirtyAttributes(self);
}

int
PsOut_BeginPattern(PsOutPtr self, void *tag, int w, int h, PsFillEnum type,
                   PsOutColor bclr, PsOutColor fclr)
{
  int   i;
  char  key[64];

  for( i=0 ; i<self->NPatterns ; i++ )
    { if( self->Patterns[i].tag==tag && self->Patterns[i].type==type ) break; }
  if( i<self->NPatterns ) return(1);
  if( (self->NPatterns+1)>self->MxPatterns )
  {
    if( self->Patterns )
    {
      self->MxPatterns *= 2;
      self->Patterns =
        (PsPatPtr)xrealloc(self->Patterns, sizeof(PsPatRec)*self->MxPatterns);
    }
    else
    {
      self->MxPatterns = 64;
      self->Patterns = (PsPatPtr)xalloc(sizeof(PsPatRec)*self->MxPatterns);
    }
  }
  self->Patterns[self->NPatterns].tag  = tag;
  self->Patterns[self->NPatterns].type = type;
  sprintf(key, "/ %d", (int)tag);
  switch(type) {
    case PsTile:   key[1] = 't'; break;
    case PsStip:   key[1] = 's'; break;
    case PsOpStip: key[1] = 'o'; break; }
  S_OutTok(self, key, 0);
  S_OutTok(self, "db/PatternType 1 d/PaintType 1 d", 0);
  S_OutTok(self, "/TilingType 1 d/BBox[0 0", 0);
  S_OutNum(self, (float)w);
  S_OutNum(self, (float)h);
  S_OutTok(self, "]d/XStep", 0);
  S_OutNum(self, (float)w);
  S_OutTok(self, "d/YStep", 0);
  S_OutNum(self, (float)h);
  S_OutTok(self, "d/PaintProc{bg sv", 1);
  if( type==PsOpStip )
  {
    S_Color(self, bclr);
    S_OutTok(self, "0 0", 0);
    S_OutNum(self, (float)w);
    S_OutNum(self, (float)h);
    S_OutTok(self, "R fl", 1);
  }
  if( type!=PsTile ) S_Color(self, fclr);
  self->NPatterns += 1;
  self->InTile = type;
  return(0);
}

void
PsOut_EndPattern(PsOutPtr self)
{
  self->InTile = PsSolid;
  S_OutTok(self, "rs ed}d de im_ mp d", 1);
}

void
PsOut_SetPattern(PsOutPtr self, void *tag, PsFillEnum type)
{
  int   i;
  char  key[64];

  for( i=0 ; i<self->NPatterns ; i++ )
    { if( tag==self->Patterns[i].tag && type==self->Patterns[i].type ) break; }
  if( i>=self->NPatterns ) return;
  sprintf(key, " %d", (int)tag);
  switch(type) {
    case PsTile:   key[0] = 't'; break;
    case PsStip:   key[0] = 's'; break;
    case PsOpStip: key[0] = 'o'; break; }
  S_OutTok(self, key, 0);
  S_OutTok(self, "spt", 1);
  self->CurColor = PSOUTCOLOR_NOCOLOR;
}

void
PsOut_RawData(PsOutPtr self, char *data, int len)
{
    S_Flush(self);
    if (!ferror(self->Fp)) {
	(void) fwrite(data, 1, len, self->Fp);
    }
}

typedef enum PsDownfontFontType_  
{ 
  PsDFT_Type1PFA=0,
  PsDFT_Type1PFB,
  PsDFT_TrueType /* not implemented yet */
} PsDownfontFontType;

/* Download a PS Type1 font */
int
PsOut_DownloadType1(PsOutPtr self, const char *auditmsg, const char *name, const char *fname)
{
  int     i;
  int     stt;
  char    buf[256];
  FILE   *fp;
  PsDownfontFontType type;

  fp = fopen(fname, "r");
  if( !fp )
    return 0;

#ifdef DEBUG_gisburn
  /* This should be log-able! */
  fprintf(stderr, "PsOut_DownloadType1: %s: Downloading '%s' from '%s'\n", auditmsg, name, fname);
#endif /* DEBUG_gisburn */

  fread(buf, 32, 1, fp);
  fseek(fp, (long)0, 0);

  /* Is this a Adobe PostScript Type 1 binary font (PFB) ? */
  if( (buf[0]&0xFF)==0x80 && (buf[1]&0xFF)==0x01 )
  {
    type = PsDFT_Type1PFB;
  }  
  /* Is this a Adobe PostScript ASCII font (PFA) ? */
  else if (!strncmp(buf, "%!PS-AdobeFont", 14))
  {
    type = PsDFT_Type1PFA;
  }
  else
  {
    /* This should be log-able! */
    fprintf(stderr, "PsOut_DownloadType1: Unknown font type for '%s'\n", fname);
    return 0;
  }      

  S_Flush(self);
  sprintf(buf, "%%%%BeginFont: %s", name);
  S_Comment(self, buf);

  if( type == PsDFT_Type1PFB )
  {
    char *buf, 
         *pt;
    int   len, 
          ch,
          stype;

    ch = fgetc(fp);  
    /* Strip out the binary headers and de-binary it */
    while( (ch&0xFF) == 0x80 ) 
    {
      stype = fgetc(fp);
      if( stype==3 ) /* eof mark */
        break;
      len = fgetc(fp);
      len |= fgetc(fp)<<8;
      len |= fgetc(fp)<<16;
      len |= fgetc(fp)<<24;
      buf = (char *)xalloc(len+1);
      if( stype==1 ) 
      {
        /* Process ASCII section */
        len = fread(buf, 1, len, fp);
        /* convert any lone CRs (ie Mac eol) to LFs */
        for( pt = buf ; (pt = memchr(pt, '\r', len-(pt-buf))) != NULL ; pt++ ) 
        {
          if ( pt[1]!='\n' ) 
            *pt = '\n';
        }
        fwrite(buf, 1, len, self->Fp);
      } 
      else if( stype==2 ) 
      {
        int i;
        
        /* Process binary section */
        len = fread(buf, 1, len, fp);
        for( i=0 ; i<len ; i++ ) 
        {
          ch = buf[i];
          if( ((ch>>4)&0xf) <= 9 )
            fputc('0'+((ch>>4)&0xf), self->Fp);
          else
            fputc('A'-10+((ch>>4)&0xf), self->Fp);
          
          if( (ch&0xf) <= 9 )
            fputc('0'+(ch&0xf), self->Fp);
          else
            fputc('A'-10+(ch&0xf), self->Fp);
          
          if( (i&0x1f)==0x1f )
              fputc('\n', self->Fp);
        }
      }
      xfree(buf);
      
      /* Next block... */
      ch = fgetc(fp);
    }
  }
  /* Is this a Adobe PostScript ASCII font (PFA) ? */
  else if (type == PsDFT_Type1PFA)
  {
    for(;;)
    {
      stt = fread(buf, 1, 256, fp);
      if( stt<=0 ) break;
      if (!ferror(self->Fp)) {
        (void) fwrite(buf, 1, stt, self->Fp);
      }
      if( stt<256 )
        break;
    }
  }
  fclose(fp);
  S_Flush(self);
  S_Comment(self, "%%EndFont");
  
  /* Success... */
  return 1;
}