summaryrefslogtreecommitdiff
path: root/Build/source/texk/dvipsk/output.c
blob: 0fc3d7ad69170e8ba11fb7f0814ceb85b9e34118 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
/*
 *   These routines do most of the communicating with the printer.
 *
 *   LINELENGTH tells the maximum line length to send out.  It's been
 *   reduced to 72 because sometimes PostScript files are included in
 *   mail messages and many mailers mutilate longer lines.
 */
#define LINELENGTH (72)
#include "dvips.h" /* The copyright notice in that file is included too! */
#include <ctype.h>
#include <stdlib.h>

#ifdef OS2
#ifdef _MSC_VER
#define popen(pcmd, pmode)  _popen(pcmd, pmode)
#define pclose(pstream) _pclose(pstream)
#endif
#endif
#if defined(WIN32) && defined(KPATHSEA)
#undef fopen
#undef popen
#undef pclose
#define fopen(file, fmode)  fsyscp_fopen(file, fmode)
#define popen(pcmd, pmode)  fsyscp_popen(pcmd, pmode)
#define pclose(pstream) _pclose(pstream)
#endif

#ifdef __DJGPP__
#include <unistd.h>	/* for `isatty' */
#endif

/* UCS -> UTF-8 */
#define UCStoUTF8B1(x)  (0xc0 + (((x) >>  6) & 0x1f))
#define UCStoUTF8B2(x)  (0x80 + (((x)      ) & 0x3f))

#define UCStoUTF8C1(x)  (0xe0 + (((x) >> 12) & 0x0f))
#define UCStoUTF8C2(x)  (0x80 + (((x) >>  6) & 0x3f))
#define UCStoUTF8C3(x)  (0x80 + (((x)      ) & 0x3f))

#define UCStoUTF8D1(x)  (0xf0 + (((x) >> 18) & 0x07))
#define UCStoUTF8D2(x)  (0x80 + (((x) >> 12) & 0x3f))
#define UCStoUTF8D3(x)  (0x80 + (((x) >>  6) & 0x3f))
#define UCStoUTF8D4(x)  (0x80 + (((x)      ) & 0x3f))

/* UTF-32 over U+FFFF -> UTF-16 surrogate pair */
#define UTF32toUTF16HS(x)  (0xd800 + (((x-0x10000) >> 10) & 0x3ff))
#define UTF32toUTF16LS(x)  (0xdc00 + (  x                 & 0x3ff))

/*
 *   The external declarations:
 */
#include "protos.h"

char preamblecomment[256]; /* usually "TeX output ..." */
integer rdir = 0, fdir = 0;
/*
 *   We need a few statics to take care of things.
 */
static void chrcmd(char c);
static void tell_needed_fonts(void);
static void print_composefont(void);
static void setdir(int d);
static int JIStoSJIS(int c);

static Boolean any_dir = 0; /* did we output any direction commands? */
static Boolean jflag = 0;
static integer rhh, rvv;
static int instring;
static Boolean lastspecial = 1;
static shalfword d;
static Boolean popened = 0;
static int lastfont;
static char strbuffer[LINELENGTH + 20], *strbp = strbuffer;
static struct papsiz *finpapsiz;
static struct papsiz defpapsiz = {
   0, 40258437L, 52099154L, "letter", ""
};
#ifdef CREATIONDATE
#if (!defined(VMS) && !defined(MSDOS) && !(defined(OS2) && defined(_MSC_VER)) && !defined(ATARIST))
 /* VAXC/MSDOS don't like/need this !! */
#include <sys/types.h>
#ifndef WIN32
#include <sys/time.h> /* time(), at least on BSD Unix */
#endif
#endif
#include <time.h> /* asctime() and localtime(), at least on BSD Unix */
static time_t jobtime;
#endif
/*
 *   This routine copies a file down the pipe.  Search path uses the
 *   header path.
 *
 *   We add code to handle the case of MS-DOS font files.
 *
 *   Format:  80 {01,02} four byte length in littleendian order data
 *   repeated possibly multiple times.
 */
static const char *hxdata = "0123456789ABCDEF";
static int infigure;
static char possibleDSCLine[81],
       *dscLinePointer = possibleDSCLine, *dscLineEnd = possibleDSCLine + 80;
void
copyfile_general(const char *s, struct header_list *cur_header)
{
   FILE *f = NULL;
   int c, prevc = '\n';
   long len;
   /* begin DOS EPS code */
   int doseps = 0;
   unsigned long dosepsbegin, dosepsend = 0;
   int removingBytes = 0;
   const char *scanForEnd = 0;
   int scanningFont = 0;

   /* end DOS EPS code */
#if defined(VMCMS) || defined (MVSXA)
   register char *lastdirsep;
   register char *trunc_s;
   trunc_s = s;
#endif
   dscLinePointer = possibleDSCLine;

   switch (infigure) {
   case 1:
/*
 *   Look in headerpath too, just in case.  This allows common header
 *   or figure files to be installed in the .../ps directory.
 */
      f = search(figpath, s, READBIN);
      if (f == 0)
         f = search(headerpath, s, READBIN);
#if defined(VMCMS) || defined (MVSXA)
      lastdirsep = strrchr(s, '/');
      if ( NULL != lastdirsep ) trunc_s = lastdirsep + 1;
#ifdef VMCMS
      sprintf(errbuf,
   "Couldn't find figure file %s with CMS name %s; continuing.", s, trunc_s);
      if (secure == 2) {
         strcat(errbuf, "\nNote that an absolute path or a relative path with .. are denied in -R2 mode.");
      }
#else /* VMCMS */
      sprintf(errbuf,
    "Couldn't find figure file %s with MVS name %s; continuing.", s, trunc_s);
      if (secure == 2) {
         strcat(errbuf, "\nNote that an absolute path or a relative path with .. are denied in -R2 mode.");
      }
#endif /* VMCMS */
#else /* VMCMS || MVSXA */
      sprintf(errbuf, "Could not find figure file %s; continuing.", s);
      if (secure == 2) {
         strcat(errbuf, "\nNote that an absolute path or a relative path with .. are denied in -R2 mode.");
      }
#endif /* VMCMS || MVSXA */
      break;
#ifndef VMCMS
#ifndef MVSXA
#ifndef VMS
#if !defined(MSDOS) || defined(__DJGPP__)
#ifndef ATARIST
#ifndef __THINK__
   case 2:
#ifdef SECURE
      sprintf(errbuf, "<%s>: Tick filename execution disabled", s);
#else
#ifdef OS2
      if (_osmode == OS2_MODE) {
#endif
      if (secure == 0) {
         sprintf(errbuf, "Execution of  <%s> failed ", s);
         f = popen(s, "r");
         if (f != 0)
            SET_BINARY(fileno(f));
	}
	else {
      sprintf(errbuf,"Secure mode is %d so execute <%s> will not run", secure,s);
	}
#ifdef OS2
      }
#endif
#endif
      break;
#endif
#endif
#endif
#endif
#endif
#endif
   default:
      f = search(headerpath, s, READBIN);
      if(cur_header && (cur_header->precode || cur_header->postcode)) {
	 if(f==NULL)
	    f = search(figpath, s, READBIN);
      }
      sprintf(errbuf, "! Could not find header file %s.", s);
      if (secure == 2) {
         strcat(errbuf, "\nNote that an absolute path or a relative path with .. are denied in -R2 mode.");
      }
      break;
   }
   if (f==NULL)
      error(errbuf);
   else {
      if (! quiet) {
#if defined(VMCMS) || defined (MVSXA)
         if (strlen(s) + prettycolumn > STDOUTSIZE) {
#else
         if (strlen(realnameoffile) + prettycolumn > STDOUTSIZE) {
#endif
            fprintf(stderr, "\n");
            prettycolumn = 0;
         }
#if defined(VMCMS) || defined (MVSXA)
         fprintf(stderr, "<%s>", trunc_s);
#else
         fprintf(stderr, "<%s>", realnameoffile);
#endif
         fflush(stderr);
#if defined(VMCMS) || defined (MVSXA)
         prettycolumn += 2 + strlen(s);
#else
         prettycolumn += 2 + strlen(realnameoffile);
#endif
      }
      if (linepos != 0)
         putc('\n', bitfile);
/*
 *   Suggested by Andrew Trevorrow; don't ever BeginFont a file ending in .enc
 */
      if (infont && strstr(s,".enc"))
         infont = 0;
      if (! disablecomments) {
         if (infigure)
            fprintf(bitfile, "%%%%BeginDocument: %s\n", s);
         else if (infont)
            fprintf(bitfile, "%%%%BeginFont: %s\n", infont);
#ifdef HPS
         else if (noprocset) {}
#endif
         else
            fprintf(bitfile, "%%%%BeginProcSet: %s 0 0\n", s);
      }
      if (cur_header && cur_header->precode) {
         fprintf(bitfile, "%s\n", cur_header->precode);
         free(cur_header->precode);
      }
      c = getc(f);
      if (c == 0x80) {
         while (1) {
            c = getc(f);
            switch(c) {
case 1:
case 2:
               len = getc(f);
               len += getc(f) * 256L;
               len += getc(f) * 65536L;
               len += getc(f) * 256L * 65536;
               if (c == 1) {
                  while (len > 0) {
                     c = getc(f);
                     if (c == EOF) {
                        error("premature EOF in MS-DOS font file");
                        len = 0;
                     } else {
		        if (c == '\r') { /* Mac- or DOS-style text file */
                           putc('\n', bitfile);
			   if ((c = getc(f)) == '\n') /* DOS-style text */
			      len--; /* consume, but don't generate NL */
			   else
			      ungetc(c, f);
			}
                        else
                           putc(c, bitfile);
                        len--;
                     }
                  }
               } else {
                  putc('\n', bitfile);
                  prevc = 0;
                  while (len > 0) {
                     c = getc(f);
                     if (c == EOF) {
                        error("premature EOF in MS-DOS font file");
                        len = 0;
                     } else {
                        putc(hxdata[c >> 4], bitfile);
                        putc(hxdata[c & 15], bitfile);
                        len--;
                        prevc += 2;
                        if (prevc >= 76) {
                           putc('\n', bitfile);
                           prevc = 0;
                        }
                     }
                  }
               }
               break;
case 3:
               goto msdosdone;
default:
               error("saw type other than 1, 2, or 3 in MS-DOS font file");
               break;
            }
            c = getc(f);
            if (c == EOF)
               break;
            if (c != 0x80) {
               error("saw non-MSDOS header in MSDOS font file");
               break;
            }
         }
msdosdone:
         prevc = 0;
      } else {
/* begin DOS EPS code */
         if (c == 'E'+0x80) {
            if ((getc(f)=='P'+0x80) && (getc(f)=='S'+0x80)
	                            && (getc(f)=='F'+0x80)) {
               doseps = 1;
               dosepsbegin = getc(f);
               dosepsbegin += getc(f) * 256L;
               dosepsbegin += getc(f) * 65536L;
               dosepsbegin += getc(f) * 256L * 65536;
               dosepsend = getc(f);
               dosepsend += getc(f) * 256L;
               dosepsend += getc(f) * 65536L;
               dosepsend += getc(f) * 256L * 65536;
               fseek(f, dosepsbegin, 0);
               c = getc(f);
               dosepsend--;
            }
            else {
               rewind(f);
               c = getc(f);
            }
         }
/* end DOS EPS code */
         if (c != EOF) {
            while (1) {
               if (c == '\n') { /* end or beginning of line; check DSC */
                  *dscLinePointer = 0; /* make sure we terminate!
                                         * might be a new empty line! */
                  if (strncmp(possibleDSCLine, "%%BeginBinary:", 14) == 0 ||
                      strncmp(possibleDSCLine, "%%BeginData:", 12) == 0 ||
                      strncmp(possibleDSCLine, "%%BeginFont:", 12) == 0) {
                     integer size = 0;
                     char *p = possibleDSCLine;
                     *dscLinePointer = 0;
                     *dscLineEnd = 0;
                     if (scanForEnd == 0 && removecomments) {
                        fputs(possibleDSCLine, bitfile);
                        putc('\n', bitfile);
                     }

                     if (strncmp(possibleDSCLine, "%%BeginFont:", 12) == 0) {

                       /* Theoretically, we could wait until we see
                          the "currentfile eexec" and possibly even
                          check that the following data really looks
                          like binary before we begin verbatim
                          copying, but that would complicate the code
                          beyond our present needs.  If we were going
                          to do that much work, this entire chunk of
                          code should probably be
                          rewritten. [dmj@ams.org, 2007/08/20] */

                       scanForEnd = "%%EndFont";
                       scanningFont = 1;
                     } else {
                       scanningFont = 0;

                     scanForEnd = 0;
                     while (*p != ':')
                        p++;
                     p++;
                     while (*p && *p <= ' ')
                        p++;
                     if ('0' > *p || *p > '9') {
                        /*
                         *   No byte count!  We need to scan for end binary
                         *   or end data, and hope we get it right.  Really
                         *   the file is malformed.
                         */
                        scanForEnd = "Yes";
                     }
                     while ('0' <= *p && *p <= '9') {
                        size = size * 10 + *p - '0';
                        p++;
                     }
                     while (*p && *p <= ' ')
                        p++;
                     if (*p == 'h' || *p == 'H')
                        /*
                         *   Illustrator 8 and 9 have bogus byte counts
                         *   for hex data.  But if it is hex, we assume
                         *   that it is safe to use ASCII scanning, so
                         *   we do so.
                         */
                        scanForEnd = "Yes";
                     while (*p > ' ') /* ignore Hex/Binary/ASCII */
                        p++;
                     while (*p && *p <= ' ')
                        p++;
                     putc(c, bitfile);
                     if (c == '\r') { /* maybe we have a DOS-style text file */
                        c = getc(f);
                        if (c == '\n') {
                           putc(c, bitfile);
                           dosepsend--;
                        } else
                           ungetc(c, f);
                     }
                     if (scanForEnd != 0) {
                        if (strncmp(possibleDSCLine, "%%BeginBinary", 13) == 0)
                           scanForEnd = "%%EndBinary";
                        else
                           scanForEnd = "%%EndData";
                     }
                     }
                     if (scanForEnd == 0) {
                        if (strncmp(p, "lines", 5) != 0 &&
                            strncmp(p, "Lines", 5) != 0) {
                           for (; size>0; size--) {
                              c = getc(f);
                              dosepsend--;
                              if (c == EOF)
                                 error(
                                 "! premature end of file in binary section");
                              putc(c, bitfile);
                           }
                        } else {
                           /*
                            *  Count both newlines and returns, and when either
                            *  goes over the count, we are done.
                            */
                           int newlines=0, returns=0;
                           while (newlines < size && returns < size) {
                              c = getc(f);
                              dosepsend--;
                              if (c == EOF)
                                 error(
                                    "! premature end of file in binary section");
                              putc(c, bitfile);
                              if (c == '\n')
                                 newlines++;
                              else if (c == '\r')
                                 returns++;
                           }
                           /*
                            *   If we've seen precisely one too few newlines,
                            *   and the next char is a newline, include it too.
                            */
                           if (returns == newlines + 1) {
                              if ((c = getc(f)) == '\n') {
                                 putc(c, bitfile);
                                 dosepsend--;
                              } else {
                                 ungetc(c, f);
                              }
                           }
                        }
                        c = getc(f);
                        dosepsend--;
                        if (c == '\n' || c == '\r') {
                           putc(c, bitfile);
			   if (c == '\r') { /* DOS-style text file? */
			      c = getc(f);
                              dosepsend--;
			      if (c == '\n') {
			         putc(c, bitfile);
			         c = getc(f);
                                 dosepsend--;
			      }
			   } else {
			      c = getc(f);
                              dosepsend--;
                           }
                        }
                        if (c != '%') {
                           /*   try to find %%EndBinary or %%EndData anywhere
                                in the rest of the file, and pretend it
                                worked; this works around various Illustrator
                                bugs.   -tgr, 14 June 2003                  */
                           const char *m1 = "%%EndData";
                           const char *m2 = "%%EndBinary";
                           const char *p1 = m1;
                           const char *p2 = m2;
                           error(
               " expected to see %%EndBinary at end of data; struggling on");
                           while (1) {
                              putc(c, bitfile);
                              if (c == '\r' || c == '\n') {
			         if (c == '\r') { /* DOS-style text file? */
			            c = getc(f);
			            if (c != '\n')
				       ungetc(c, f);
                                    else
                                       dosepsend--;
			         }
                                 break;
			      }
                              c = getc(f);
                              dosepsend--;
                              if (c == EOF)
                                 error(
                                 "! premature end of file in binary section");
 /*
  *   By the way, this code can be fooled by things like %%%EndBinary
  *   or even %%EndBi%%EndBinary, but this isn't valid DSC anyway.
  *   This comment is mainly here to prevent anyone else from emulating
  *   this code when doing stream-based substring matching.
  */
                              if (c == *p1) {
                                 p1++;
                                 if (*p1 == 0)
                                    break;
                              } else {
                                 p1 = m1;
                              }
                              if (c == *p2) {
                                 p2++;
                                 if (*p2 == 0)
                                    break;
                              } else {
                                 p2 = m2;
                              }
                           }
                        }
                        while (1) {
                           putc(c, bitfile);
                           if (c == '\r' || c == '\n') {
			      if (c == '\r') { /* DOS-style text file? */
			         c = getc(f);
			         if (c != '\n')
				    ungetc(c, f);
                                 else {
                                    putc(c, bitfile);
                                    dosepsend--;
                                 }
			      }
                              break;
			   }
                           c = getc(f);
                           removingBytes = 0;
                           dosepsend--;
                           if (c == EOF)
                              error(
                                 "! premature end of file in binary section");
                        }
                        c = getc(f);
                        dosepsend--;
                     }
                  } else if (scanForEnd && strncmp(possibleDSCLine, scanForEnd,
                                                   strlen(scanForEnd))==0) {
                     scanForEnd = 0;
                     scanningFont = 0;
                  }
                  dscLinePointer = possibleDSCLine;
               } else if (dscLinePointer < dscLineEnd) {
                  *dscLinePointer++ = c;
                  if (removecomments && scanForEnd == 0 &&
                      c == '%' && dscLinePointer == possibleDSCLine + 1) {
                     /* % is first char */
                     c = getc(f);
                     if (c == '%' || c == '!')
                        removingBytes = 1;
                     if (c != EOF)
                        ungetc(c, f);
                     c = '%';
                  }
               }
#if defined(VMCMS) || defined (MVSXA)
               if (c != 0x37  || scanningFont) {
#else
               if (c != 4 || scanningFont) {
#endif
                  if (!removingBytes)
                     putc(c, bitfile);
               }
               prevc = c;
/* begin DOS EPS code */
               if (doseps && (dosepsend <= 0))
                  break;      /* stop at end of DOS EPS PostScript section */
/* end DOS EPS code */
               c = getc(f);
               dosepsend--;
               if (c == EOF)
                  break;
               else if (c == '\r' && ! scanningFont) {
		  c = getc(f);
		  if (c == '\n') { /* DOS-style text file? */
		     if (!removingBytes) putc('\r', bitfile);
                     dosepsend--;
		  } else
		     ungetc(c, f);
                  c = '\n';
	       }
               if (prevc == '\n')
                  removingBytes = 0;
            }
         }
      }
      if (prevc != '\n')
         putc('\n', bitfile);
      linepos = 0;
#ifndef VMCMS
#ifndef MVSXA
#ifndef VMS
#if !defined(MSDOS) || defined(__DJGPP__)
#ifndef ATARIST
#ifndef __THINK__
      if (infigure == 2)
#ifdef OS2
         {
            if (_osmode == OS2_MODE)
               pclose(f);
         }
#else
         pclose(f);
#endif
      else
#endif
#endif
#endif
#endif
#endif
#endif
         fclose(f);
      if (cur_header && cur_header->postcode) {
         fprintf(bitfile, "\n%s", cur_header->postcode);
         free(cur_header->postcode);
      }
      if (!disablecomments) {
         if (infigure)
            fprintf(bitfile, "\n%%%%EndDocument\n");
         else if (infont)
            fprintf(bitfile, "\n%%%%EndFont\n");
#ifdef HPS
         else if (noprocset) {}
#endif
         else
            fprintf(bitfile, "\n%%%%EndProcSet\n");
      }
   }
}

void
copyfile(const char *s)
{
   copyfile_general(s, NULL);
}

/*
 *   For included PostScript graphics, we use the above routine, but
 *   with no fatal error message.
 */
void
figcopyfile(char *s, int systemtype)
{
   infigure = systemtype ? 2 : 1;
   copyfile(s);
   infigure = 0;
}
/*
 *   This next routine writes out a `special' character.  In this case,
 *   we simply put it out, since any special character terminates the
 *   preceding token.
 */
void
specialout(char c)
{
   if (linepos >= LINELENGTH) {
      putc('\n', bitfile);
      linepos = 0;
   }
   putc(c, bitfile);
   linepos++;
   lastspecial = 1;
}

void
stringend(void)
{
   if (linepos + instring >= LINELENGTH - 2) {
      putc('\n', bitfile);
      linepos = 0;
   }
   putc('(', bitfile);
   *strbp = 0;
   fputs(strbuffer, bitfile);
   putc(')', bitfile);
   linepos += instring + 2;
   lastspecial = 1;
   instring = 0;
   strbp = strbuffer;
}

#ifdef SHIFTLOWCHARS
/*
 *   moving chars 0-32 and 127 to higher positions
 *   is desirable when using some fonts
 */
int
T1Char(int c)
{
  int tmpchr = c;
  if (shiftlowchars && curfnt->resfont) {
    if ((tmpchr <= 0x20)&&(tmpchr>=0)) {
      if (tmpchr < 0x0A) {
        tmpchr += 0xA1;
      }
      else {
        tmpchr += 0xA3;
      }
    }
    else if (tmpchr == 0x7F) {
      tmpchr = 0xC4;
    }
  }
  if (curfnt->chardesc[tmpchr].flags2 & EXISTS)
    tmpchr = c;
  return tmpchr;
}
#endif

void
scout(unsigned char c)   /* string character out */
{
/*
 *   Is there room in the buffer?  LINELENGTH-6 is used because we
 *   need room for (, ), and a possible four-byte string \000, for
 *   instance.  If it is too long, we send out the string.
 */
   jflag = 0;
   if (instring > LINELENGTH-6) {
      stringend();
      chrcmd('p');
   }
#ifdef SHIFTLOWCHARS
   c=T1Char(c);
#endif
/*  changed next line to hex representation for VMCMS port
   if (c<' ' || c > 126 || c=='%' ) {
*/
   if ( c<0x20 || c>= 0x7F || c==0x25 ) {
      *strbp++ = '\\';
      *strbp++ = '0' + ((c >> 6) & 3);
      *strbp++ = '0' + ((c >> 3) & 7);
      *strbp++ = '0' + (c & 7);
      instring += 4;
   } else {
#if defined(VMCMS) || defined (MVSXA)
     c = ascii2ebcdic[c];
#endif
     if (c == '(' || c == ')' || c == '\\') {
       *strbp++ = '\\';
       *strbp++ = c;
       instring += 2;
     } else {
       *strbp++ = c;
       instring++;
     }
   }
}

static void
scout2(int c)
{
   char s[64];

   sprintf(s, "<%04x>p", c);
   cmdout(s);
}

static void
jscout(int c, char *fs)   /* string character out */
{
   char s[64];

   if (!dir) {
      numout(hh);
      numout(vv);
   } else {
      numout(vv);
      numout(-hh);
   }
   if (strstr(fs,"-UTF32-")!=NULL) {
      snprintf(s, sizeof(s), "a<%08x>p", c);
   } else if (strstr(fs,"-UTF8-")!=NULL) {
      if (c<0x80) {
         snprintf(s, sizeof(s), "a<%02x>p", c);
      } else if (c<0x800) {
	 snprintf(s, sizeof(s), "a<%02x%02x>p", UCStoUTF8B1(c), UCStoUTF8B2(c));
      } else if (c<0x10000) {
	 snprintf(s, sizeof(s), "a<%02x%02x%02x>p", UCStoUTF8C1(c),
                 UCStoUTF8C2(c), UCStoUTF8C3(c));
      } else if (c<0x110000) {
	 snprintf(s, sizeof(s), "a<%02x%02x%02x%02x>p", UCStoUTF8D1(c),
		 UCStoUTF8D2(c), UCStoUTF8D3(c), UCStoUTF8D4(c));
      } else {
         error("warning: Illegal code value.");
      }
   } else if (c>0xffff && strstr(fs,"-UTF16-")!=NULL) {
      snprintf(s, sizeof(s), "a<%04x%04x>p",
	       UTF32toUTF16HS(c), UTF32toUTF16LS(c));
   } else {
      if ((strstr(fs,"-RKSJ-")!=NULL)) c = JIStoSJIS(c);
      snprintf(s, sizeof(s), "a<%04x>p", c);
   }
   cmdout(s);
   instring = 0;
   jflag = 1;
   strbuffer[0] = '\0';
}

void
cmdout(const char *s)
{
   int l;

   /* hack added by dorab */
   if (instring && !jflag) {
        stringend();
        chrcmd('p');
   }
   l = strlen(s);
   if ((! lastspecial && linepos >= LINELENGTH - 20) ||
           linepos + l >= LINELENGTH) {
      putc('\n', bitfile);
      linepos = 0;
   } else if (! lastspecial) {
      putc(' ', bitfile);
      linepos++;
   }
   fputs(s, bitfile);
   linepos += l;
   lastspecial = 0;
}


static void
chrcmd(char c)
{
   if ((! lastspecial && linepos >= LINELENGTH - 20) ||
       linepos + 2 > LINELENGTH) {
      putc('\n', bitfile);
      linepos = 0;
   } else if (! lastspecial) {
      putc(' ', bitfile);
      linepos++;
   }
   putc(c, bitfile);
   linepos++;
   lastspecial = 0;
}

void
floatout(float n)
{
   char buf[50];

   snprintf(buf, sizeof(buf), "%.2f", n);
   cmdout(buf);
}

void
doubleout(double n)
{
   char buf[50];

   snprintf(buf, sizeof(buf), "%g", n);
   cmdout(buf);
}

void
numout(integer n)
{
   char buf[50];

#ifdef SHORTINT
   snprintf(buf, sizeof(buf), "%ld", n);
#else
   snprintf(buf, sizeof(buf), "%d", n);
#endif
   cmdout(buf);
}

void
mhexout(register unsigned char *p,
        register long len)
{
   register const char *hexchar = hxdata;
   register int n, k;

   while (len > 0) {
      if (linepos > LINELENGTH - 2) {
         putc('\n', bitfile);
         linepos = 0;
      }
      k = (LINELENGTH - linepos) >> 1;
      if (k > len)
         k = len;
      len -= k;
      linepos += (k << 1);
      while (k--) {
         n = *p++;
         putc(hexchar[n >> 4], bitfile);
         putc(hexchar[n & 15], bitfile);
      }
   }
}

static void
fontout(halfword n)
{
   char buf[6];

   if (instring && !jflag) {
      stringend();
      chrcmd('p');
   }
   makepsname(buf, n);
   cmdout(buf);

   lastfont = curfnt->psname;
}

void
hvpos(void)
{
   if (!dir) {
      if (rvv != vv || jflag) {
         if (instring) {
            stringend();
            numout(hh);
            numout(vv);
            chrcmd('y');
         } else if (rhh != hh || jflag) {
            numout(hh);
            numout(vv);
            chrcmd('a') ;
         } else { /* hard to get this case, but it's there when you need it! */
            numout(vv - rvv);
            chrcmd('x');
         }
         rvv = vv;
      } else if (rhh != hh || jflag) {
         if (instring) {
            stringend();
            if (hh - rhh < 5 && rhh - hh < 5) {
#if defined(VMCMS) || defined (MVSXA) /*  should replace 'p' in non-VMCMS, non-MVSXA line as well */
               chrcmd(ascii2ebcdic[(char)(112 + hh - rhh)]);
#else
               chrcmd((char)('p' + hh - rhh));
#endif
            } else if (hh - rhh < d + 5 && rhh - hh < 5 - d) {
#if defined(VMCMS) || defined (MVSXA) /* should replace 'g' in non-VMCMS, non-MVSXA line as well  */
               chrcmd(ascii2ebcdic[(char)(103 + hh - rhh - d)]);
#else
               chrcmd((char)('g' + hh - rhh - d));
#endif
               d = hh - rhh;
            } else {
               numout(hh - rhh);
               chrcmd('b');
               d = hh - rhh;
            }
         } else {
            numout(hh - rhh);
            chrcmd('w');
         }
      }
      rhh = hh;
   } else {
      if (rhh != hh || jflag) {
         if (instring) {
            stringend();
            numout(vv);
            numout(-hh);
            chrcmd('y');
         } else if (rvv != vv || jflag) {
            numout(vv);
            numout(-hh);
            chrcmd('a');
         } else { /* hard to get this case, but it's there when you need it! */
            numout(rhh - hh);
            chrcmd('x');
         }
         rhh = hh;
      } else if (rvv != vv || jflag) {
         if (instring) {
            stringend();
            if (vv - rvv < 5 && rvv - vv < 5) {
#if defined(VMCMS) || defined (MVSXA) /*  should replace 'p' in non-VMCMS, non-MVSXA line as well */
               chrcmd(ascii2ebcdic[(char)(112 + vv - rvv)]);
#else
               chrcmd((char)('p' + vv - rvv));
#endif
            } else if (vv - rvv < d + 5 && rvv - vv < 5 - d) {
#if defined(VMCMS) || defined (MVSXA) /* should replace 'g' in non-VMCMS, non-MVSXA line as well  */
               chrcmd(ascii2ebcdic[(char)(103 + vv - rvv - d)]);
#else
               chrcmd((char)('g' + vv - rvv - d));
#endif
               d = vv - rvv;
            } else {
               numout(vv - rvv);
               chrcmd('b');
               d = vv - rvv;
            }
         } else {
            numout(vv - rvv);
            chrcmd('w');
         }
      }
      rvv = vv;
   }
}

/*
 *   initprinter opens the bitfile and writes the initialization sequence
 *   to it.
 */
void
newline(void)
{
   if (linepos != 0) {
      fprintf(bitfile, "\n");
      linepos = 0;
   }
   lastspecial = 1;
}

void
nlcmdout(const char *s)
{
   newline();
   cmdout(s);
   newline();
}
/*
 *   Is the dimension close enough for a match?  We use 5bp
 *   as a match; this is 65536*72.27*5/72 or 328909 scaled points.
 */
static int
indelta(integer i)
{
   if (i < 0)
      i = -i;
   return (i <= 328909);
}
/*
 *   A case-irrelevant string compare.
 */
static int
mlower(int c)
{
   if ('A' <= c && c <= 'Z')
      return c - 'A' + 'a';
   else
      return c;
}
static int
ncstrcmp(const char *a, const char *b)
{
   while (*a && (*a == *b ||
                       mlower(*a) == mlower(*b)))
      a++, b++;
   if (*a == 0 && *b == 0)
      return 0;
   else
      return 1;
}
/*
 *   Find the paper size.
 */
static void
findpapersize(void) {
   if (finpapsiz == 0) {
      struct papsiz *ps;
      struct papsiz *fps = 0;
      int    ih, iv, it;
      int    mindiff = 0x7fffffff;

      if (tryepsf && !landscape) {
         finpapsiz = &defpapsiz;
         hpapersize = defpapsiz.xsize;
         vpapersize = defpapsiz.ysize;
         return;
      }
      if (cropmarks) {
/*
 *   If user wanted crop marks, we increase the size of the page by
 *   a half inch all around.
 */
         if (hpapersize == 0 || vpapersize == 0) {
            error(
 "warning: -k crop marks wanted, but no paper size specified; using default");
            if (landscape) {
               hpapersize = defpapsiz.ysize;
               vpapersize = defpapsiz.xsize;
            } else {
               hpapersize = defpapsiz.xsize;
               vpapersize = defpapsiz.ysize;
            }
         }
         hpapersize += 2368143L;
         vpapersize += 2368143L;
         add_header(CROPHEADER);
      }
      if (paperfmt && *paperfmt) {
         for (ps = papsizes; ps; ps = ps->next)
            if (ncstrcmp(paperfmt, ps->name)==0)
               finpapsiz = ps;
         if (finpapsiz == 0)
            error("no match for papersize");
      }
      if (finpapsiz == 0 && hpapersize > 0 && vpapersize > 0) {
         for (ps=papsizes; ps; ps = ps->next) {
            ih = ps->xsize-hpapersize;
            iv = ps->ysize-vpapersize;
            if (ih < 0) ih = -ih;
            if (iv < 0) iv = -iv;
            it = ih;
            if (it < iv) it = iv;
            if (it < mindiff) {
               mindiff = it;
               fps = ps;
            }
         }
         if (indelta(mindiff))
            landscape = 0;
         else
            fps = 0;
         mindiff = 0x7fffffff;
         if (fps == 0) {
            for (ps=papsizes; ps; ps = ps->next) {
               iv = ps->ysize-hpapersize;
               ih = ps->xsize-vpapersize;
               if (ih < 0) ih = -ih;
               if (iv < 0) iv = -iv;
               it = ih;
               if (it < iv) it = iv;
               if (it < mindiff) {
                  mindiff = it;
                  fps = ps;
               }
            }
            if (indelta(mindiff))
               landscape = 1;
            else
               fps = 0;
            if (fps == 0) {
               for (ps=papsizes; ps; ps = ps->next) {
                  if (ps->ysize == 0 && ps->xsize == 0) {
                     fps = ps;
                     break;
                  }
               }
               if (fps == 0) {
                  landscape = (hpapersize > vpapersize);
                  error(
                    "no match for special paper size found; using default");
               }
            }
         }
         finpapsiz = fps;
      }
      if (finpapsiz == 0) {
         if (papsizes)
            finpapsiz = papsizes;
         else
            finpapsiz = &defpapsiz;
/*
 *   But change xsize/ysize to match so bounding box works.
 */
         if (hpapersize && vpapersize) {
            if (landscape) {
               finpapsiz->ysize = hpapersize;
               finpapsiz->xsize = vpapersize;
            } else {
               finpapsiz->xsize = hpapersize;
               finpapsiz->ysize = vpapersize;
            }
         }
      }
/*
 *   Here, there was no papersize special.  We set the paper size from
 *   the selected paper format.  If the selected paper format has no
 *   sizes, we use the defaults.
 */
      if (hpapersize == 0 || vpapersize == 0) {
         if (finpapsiz->xsize == 0 || finpapsiz->ysize == 0) {
            finpapsiz->xsize = defpapsiz.xsize;
            finpapsiz->ysize = defpapsiz.ysize;
         }
         if (landscape) {
            vpapersize = finpapsiz->xsize;
            hpapersize = finpapsiz->ysize;
         } else {
            hpapersize = finpapsiz->xsize;
            vpapersize = finpapsiz->ysize;
         }
/*
 *   Here, there was a papersize special, but the selected paper
 *   format has 0 0 for sizes.  We set the sizes here so that the
 *   bounding box works.
 */
      } else if (finpapsiz->xsize == 0 || finpapsiz->ysize == 0) {
         finpapsiz->xsize = hpapersize;
         finpapsiz->ysize = vpapersize;
/*
 *   Here, the user specified a size with -t, and there was a
 *   papersize special, and its sizes were greater than zero.
 *   We make sure the sizes are okay.  Note that the user must have
 *   specified landscape if this is desired.
 */
      } else if (paperfmt && *paperfmt) {
         if (landscape) {
            if (!indelta(vpapersize - finpapsiz->xsize) ||
                !indelta(hpapersize - finpapsiz->ysize)) {
               if (vpapersize > finpapsiz->xsize ||
                   hpapersize > finpapsiz->ysize)
                  error("warning: -t selected paper may be too small");
               else
                  error("note: -t selected paper may be too large");
            }
         } else {
            if (!indelta(hpapersize - finpapsiz->xsize) ||
                !indelta(vpapersize - finpapsiz->ysize)) {
               if (hpapersize > finpapsiz->xsize ||
                   vpapersize > finpapsiz->ysize)
                  error("warning: -t selected paper may be too small");
               else
                  error("note: -t selected paper may be too large");
            }
         }
      }
   }
}
/*
 *   Convert scaled points to PostScript points.  This is the same
 *   as return (i * 72 / (65536 * 72.27)), which is the same as
 *   dividing by 65781.76, but we want to round up.
 */
static int
topoints(integer i)
{
   i += 65780L;
   return (i / 6578176L)*100 + (i % 6578176) * 100 / 6578176;
}
/*
 *   Send out the special paper stuff.  If `hed' is non-zero, only
 *   send out lines starting with `!' else send all other lines out.
 */
static void
paperspec(const char *s, int hed)
{
   int sendit;

   while (*s) {
      s++;
      if (*s == '\0')
         return;
      if (*s == '!') {
         s++;
         while (*s == ' ') s++;
         sendit = hed;
      } else
         sendit = ! hed;
      if (sendit) {
         while (*s && *s != '\n')
            putc(*s++, bitfile);
         putc('\n', bitfile);
      } else {
         while (*s && *s != '\n')
            s++;
      }
   }
}
static char *
epsftest(integer bop)
{
   if (tryepsf && paperfmt == 0 && *iname) {
      findbb(bop+44);
      return nextstring;
   }
   return 0;
}
static char *isepsf = 0;
static int endprologsent;
void
open_output(void) {
   FILE * pf = NULL;
   if (*oname != 0) {
/*
 *   We check to see if the first character is a exclamation
 *   point, and popen if so.
 */
      if (*oname == '!' || *oname == '|') {
#if defined(MSDOS) && !defined(__DJGPP__) || defined(VMS) || defined(VMCMS) || defined(MVSXA) || defined(__THINK__) || defined(ATARIST)
            error("! can't open output pipe");
#else
#ifdef OS2
         if (_osmode != OS2_MODE) {
            error("! can't open output pipe");
         } else {
#endif
#ifdef __DJGPP__
        /* Feature: if they pipe to "lpr" and there's no executable by
           that name anywhere in sight, write to local printer instead.

           We do this up front, before even trying to popen, because on
           MS-DOS popen always succeeds for writing (it only opens a
           temporary file), and by the time we get to actually run the
           (possibly nonexistent) program in pclose, it's too late to
           fall back.

           We don't use kpathsea functions here because they don't
           know about DOS-specific executable extensions, while we
           want to be able to find "lpr.exe", "lpr.com", "lpr.bat" etc.  */
        extern char *__dosexec_find_on_path(const char *,
                                            char **, char *);
        extern char **environ;
        char *p = oname + 1;
        char found[FILENAME_MAX];

        while (ISSPACE(*p))
          p++;
        if (strncmp(p, "lpr", 3) == 0 && (ISSPACE(p[3]) || p[3] == '\0')
            && !__dosexec_find_on_path(oname+1, (char **)0, found)
            && !__dosexec_find_on_path(oname+1, environ, found))
           pf = fopen("PRN", "w");
#endif
	 if (pf == NULL && (pf = popen(oname+1, "w")) != NULL) {
	    popened = 1;
	    SET_BINARY(fileno(pf));
	 }
         if (pf == NULL)
            error("! couldn't open output pipe");
	 bitfile = pf;
#ifdef OS2
         }
#endif
#endif /* MSDOS && !__DJGPP__ || VMS || ... */
      } else {
         if ((bitfile=fopen(oname,"w"))==NULL)
            error("! couldn't open PostScript file");
         SET_BINARY(fileno(bitfile));
      }
   } else {
      bitfile = stdout;
   }

   /* Even PostScript output may include binary characters, so switch
      bitfile to binary mode.  */
   if (O_BINARY && !isatty(fileno(bitfile)))
      SET_BINARY(fileno(bitfile));
}
void
initprinter(sectiontype *sect)
{
   int n = sect->numpages * pagecopies * collatedcopies;
#ifdef HPS
   if (!HPS_FLAG)
#endif
      open_output();

   findpapersize();
   if (disablecomments) {
      fprintf(bitfile,
             "%%!PS (but not EPSF; comments have been disabled)\n");
      fprintf(stderr, "Warning:  no %%%%Page comments generated.\n");
   } else {
      if (multiplesects) {
         fprintf(bitfile,
             "%%!PS (but not EPSF because of memory limits)\n");
         fprintf(stderr, "Warning:  no %%%%Page comments generated.\n");
      } else {
         isepsf = epsftest(sect->bos);
         if (isepsf)
            fprintf(bitfile, "%%!PS-Adobe-2.0 EPSF-2.0\n");
         else
            fprintf(bitfile, "%%!PS-Adobe-2.0\n");
      }
      if (tryepsf && isepsf == 0)
         error("We tried, but couldn't make it EPSF.");
      fprintf(bitfile, "%%%%Creator: %s\n", banner + 8);
      if (*iname)
         fprintf(bitfile, "%%%%Title: %s\n", iname);
#ifdef CREATIONDATE
      jobtime=time(0);
      fprintf(bitfile, "%%%%CreationDate: %s",
                                 asctime(localtime(&jobtime)));
#endif
      if (! isepsf) {
/*
 *   Normally, we wouldn't want to add that second field
 *   indicating that the page order is reversed, as per page
 *   644 of the Red book.  But we have to, for many existing
 *   spoolers.
 */
        fprintf(bitfile, "%%%%Pages: %d%s\n", (sepfiles ? n : totalpages),
                                                    (reverse?" -1":""));
        fprintf(bitfile, "%%%%PageOrder: %sscend\n", reverse?"De":"A");
      }
      if (landscape) {
         fprintf(bitfile, "%%%%Orientation: Landscape\n");
         fprintf(bitfile, "%%%%BoundingBox: 0 0 %d %d\n",
              topoints(finpapsiz->xsize), topoints(finpapsiz->ysize));
      } else if (isepsf)
         fprintf(bitfile, "%%%%BoundingBox: %s\n", isepsf);
      else
         fprintf(bitfile, "%%%%BoundingBox: 0 0 %d %d\n",
              topoints(finpapsiz->xsize), topoints(finpapsiz->ysize));
      tell_needed_fonts();
      paperspec(finpapsiz->specdat, 1);
      fprintf(bitfile, "%%%%EndComments\n");
   }
   {
      int i, len;
      char *p;

/*
 *   Here, too, we have to be careful not to exceed the line length
 *   limitation, if possible.
 */
      fprintf(bitfile, "%%DVIPSWebPage: %s\n", banner2);
      fprintf(bitfile, "%%DVIPSCommandLine:");
      len = 18;
      for (i=0; i<gargc; i++) {
         p = gargv[i];
         while (*p > ' ')
            p++;
         if (*p)
            len += 2;
         len += strlen(gargv[i]) + 1;
         if (len > LINELENGTH) {
            fprintf(bitfile, "\n%%+");
            len = strlen(gargv[i]) + 3;
            if (*p)
               len += 2;
         }
         fprintf(bitfile, (*p ? " \"%s\"" : " %s"), gargv[i]);
      }
      fprintf(bitfile, "\n%%DVIPSParameters: dpi=%d", actualdpi);
      if (actualdpi != vactualdpi)
         fprintf(bitfile, "x%d", vactualdpi);
      if (compressed)
         fprintf(bitfile, ", compressed");
      if (removecomments)
         fprintf(bitfile, ", comments removed");
      fputc('\n', bitfile);
   }
#if defined(VMCMS) || defined (MVSXA)  /* convert preamblecomment to ebcdic so we can read it */
   {
      int i;
      for ( i=0; preamblecomment[i]; i++ )
          preamblecomment[i] = ascii2ebcdic[preamblecomment[i]];
   }
#endif
   fprintf(bitfile, "%%DVIPSSource: %s\n", preamblecomment);
   linepos = 0;
   endprologsent = 0;
   if (safetyenclose)
      fprintf(bitfile, "/SafetyEnclosure save def\n");
   print_composefont();
   if (! headers_off)
      send_headers();
}
void
setup(void) {
   newline();
   if (endprologsent == 0 && !disablecomments) {
      fprintf(bitfile, "%%%%EndProlog\n");
      fprintf(bitfile, "%%%%BeginSetup\n");
      if (vactualdpi == actualdpi)
         fprintf(bitfile, "%%%%Feature: *Resolution %ddpi\n",
                                           actualdpi);
      else
         fprintf(bitfile, "%%%%Feature: *Resolution %dx%ddpi\n",
                                           actualdpi, vactualdpi);
      if (multiplesects && *(finpapsiz->specdat)) {
         fprintf(bitfile, "TeXDict begin\n");
         paperspec(finpapsiz->specdat, 0);
         fprintf(bitfile, "end\n");
      }
      if (manualfeed)
         fprintf(bitfile, "%%%%Feature: *ManualFeed True\n");
#ifdef HPS
      if (!HPS_FLAG)
#endif
      if (multiplesects)
         fprintf(bitfile, "%%%%EndSetup\n");
   }
   if (multiplesects && ! disablecomments)
      fprintf(bitfile, "%%DVIPSBeginSection\n");
   cmdout("TeXDict");
   cmdout("begin");
   if (endprologsent || disablecomments || multiplesects == 0) {
      fprintf(bitfile, "\n");
      paperspec(finpapsiz->specdat, 0);
   }
   if (manualfeed) cmdout("@manualfeed");
   if (landscape) cmdout("@landscape");
   if (numcopies != 1) {
      numout((integer)numcopies);
      cmdout("@copies");
   }
   cmdout("end");
   if (endprologsent == 0 && !disablecomments) {
      newline();
      endprologsent = 1;
#ifdef HPS
      if (!HPS_FLAG)
#endif
         if (! multiplesects)
            fprintf(bitfile, "%%%%EndSetup\n");
   }
#ifdef HPS
  if (HPS_FLAG) {
    fclose(bitfile);
    set_bitfile("body.tmp",0);
  }
#endif
}
/*
 *   cleanprinter is the antithesis of the above routine.
 */
void
cleanprinter(void)
{
   fprintf(bitfile, "\n");
   fprintf(bitfile, "userdict /end-hook known{end-hook}if\n");
   if (safetyenclose)
      fprintf(bitfile, "SafetyEnclosure restore\n");
   if (!disablecomments)
      fprintf(bitfile, "%%%%EOF\n");
   if (sendcontrolD)
      putc(4, bitfile);
   if (ferror(bitfile))
      error("Problems with file writing; probably disk full.");
#if !defined(MSDOS) || defined(__DJGPP__)
#ifndef VMS
#ifndef MVSXA
#ifndef VMCMS
#ifndef __THINK__
#ifndef ATARIST
#ifdef OS2
   if (_osmode == OS2_MODE)
#endif
      if (popened)
         pclose(bitfile);
#endif
#endif
#endif
#endif
#endif
#endif
   if (popened == 0)
      fclose(bitfile);
   bitfile = NULL;
}

/* this tells dvips that it has no clue where it is. */
static int thispage = 0;
static integer rulex, ruley;
void
psflush(void) {
   rulex = ruley = rhh = rvv = -314159265;
   lastfont = -1;
}
/*
 *   pageinit initializes the output variables.
 */
void
pageinit(void)
{
   psflush();
   newline();
   thispage++;
   if (!disablecomments) {
      if (multiplesects)
#ifdef SHORTINT
         fprintf(bitfile, "%%DVIPSSectionPage: %ld\n", pagenum);
      else if (! isepsf)
         fprintf(bitfile, "%%%%Page: %ld %d\n", pagenum, thispage);
#else
         fprintf(bitfile, "%%DVIPSSectionPage: %d\n", pagenum);
      else if (! isepsf)
         fprintf(bitfile, "%%%%Page: %d %d\n", pagenum, thispage);
#endif
   }
   linepos = 0;
   cmdout("TeXDict");
   cmdout("begin");
#ifdef HPS
   if (HPS_FLAG) {
      cmdout("HPSdict");
      cmdout("begin");
   }
#endif
   if (landscape) cmdout("@landscape");
   numout((integer)pagenum);
   numout((integer)thispage-1);
   cmdout("bop");
   d = 0;
}



/*
 *   This routine ends a page.
 */
void
pageend(void)
{
   if (instring) {
      stringend();
      chrcmd('p');
   }
   if (dir)
      cmdout("-90 rotate");
   if (any_dir)
      cmdout("dyy");
   cmdout("eop");
   cmdout("end");
#ifdef HPS
   if (HPS_FLAG)
      cmdout("end");
#endif
}

/*
 *   drawrule draws a rule at the specified position.
 *   It does nothing to save/restore the current position,
 *   or even draw the current string.  (Rules are normally
 *   set below the baseline anyway, so this saves us on
 *   output size almost always.)
 */
void
drawrule(integer rw, integer rh)
{
   if (!dir) {
     numout((integer)hh);
     numout((integer)vv);
   } else {
     numout((integer)vv);
     numout((integer)-hh);
   }
   if (rw == rulex && rh == ruley)
      chrcmd('V');
   else {
      numout((integer)rw);
      numout((integer)rh);
      chrcmd('v');
      rulex = rw;
      ruley = rh;
   }
}

/*
 *   drawchar draws a character at the specified position.
 */
void
drawchar(chardesctype *c, int cc)
{
   if (rdir != dir || fdir != curfnt->dir) {
      if (curfnt->dir == 9)
         setdir(dir+2);
      else
         setdir(dir);
      rdir = dir;
      fdir = curfnt->dir;
   }

   if (curfnt->iswide == 0 && curfnt->codewidth == 2) {
      Boolean savejflag = jflag;
      jflag = 1;
      hvpos();
      jflag = savejflag;
      if (lastfont != curfnt->psname)
         fontout(curfnt->psname);
      scout2(cc);
   }
   else if (curfnt->iswide) {
      if (lastfont != curfnt->psname)
         fontout(curfnt->psname);
      jscout(cc, curfnt->resfont->PSname);
   }
   else {
      if (jflag) {
         if (!dir){
            numout(hh);
            numout(vv);
         }
         else {
            numout(vv);
            numout(-hh);
         }
         chrcmd('a');
         rhh = hh;
         rvv = vv;
      }
      else hvpos();
      if (lastfont != curfnt->psname)
         fontout(curfnt->psname);
      scout((unsigned char)cc);
   }
   if (!dir)
      rhh = hh + c->pixelwidth; /* rvv = rv */
   else
      rvv = vv + c->pixelwidth; /* rhh = rh */
}
/*
 *   This routine sends out the document fonts comment.
 */
static void
tell_needed_fonts(void) {
   struct header_list *hl = ps_fonts_used;
   char *q;
   int roomleft = -1;

   if (hl == 0)
      return;
   while (0 != (q=get_name(&hl))) {
      if ((int)strlen(q) >= roomleft) {
         if (roomleft != -1) {
            fprintf(bitfile, "\n%%%%+");
            roomleft = LINELENGTH - 3;
         } else {
            fprintf(bitfile, "%%%%DocumentFonts:");
            roomleft = LINELENGTH - 16;
         }
      }
      fprintf(bitfile, " %s", q);
      roomleft -= strlen(q) + 1;
   }
   fprintf(bitfile, "\n");
}

static void print_composefont(void)
{
   struct header_list *hl = ps_fonts_used;
   int  len;
   char *q, *p;

   if (hl == 0)
      return;
   while (0 != (q=get_name(&hl))) {
     len = strlen(q);
     if(len > 11 && (!strncmp(q+len-10, "Identity-H", 10) ||
             !strncmp(q+len-10, "Identity-V", 10))) {
       fprintf(bitfile, "%%%%BeginFont: %s\n", q);
       fprintf(bitfile, "/%s ", q);
       fprintf(bitfile, "/%s ", q+len-10);
       fprintf(bitfile, "[/");
       for(p=q; p <= q+len-12; p++)
          fprintf(bitfile, "%c", *p);
       fprintf(bitfile, "] composefont pop\n");
       fprintf(bitfile, "%%%%EndFont\n");
     }
   }
}

static void setdir(int d)
{
   if (instring) {
      stringend();
      chrcmd('p');
   }
   switch(d) {
   case 1 :
      cmdout("dyt");
      break;
   case 2 :
      cmdout("dty");
      break;
   case 3 :
      cmdout("dtt");
      break;
   default :
      cmdout("dyy");
      break;
   }
   linepos += 4;
   any_dir = 1;
}

void cmddir(void)
{
   if (dir != rdir) {
      if (dir)
         cmdout("90 rotate");
      else
         cmdout("-90 rotate");
      rdir = dir;
   }
}

static int JIStoSJIS(int c)
{
    int high, low;
    int nh,nl;

    high = (c>>8) & 0xff;
    low = c & 0xff;
    nh = ((high-0x21)>>1) + 0x81;
    if (nh>0x9f)
    nh += 0x40;
    if (high & 1) {
        nl = low + 0x1f;
        if (low>0x5f)
        nl++;
    }
    else
        nl = low + 0x7e;
    if (((nh >= 0x81 && nh <= 0x9f) || (nh >= 0xe0 && nh <= 0xfc)) &&
        (nl >= 0x40 && nl <= 0xfc && nl != 0x7f))
        return((nh<<8) | nl);
    else
        return(0x813f);
}