File: gdevcdj.c

package info (click to toggle)
gs 3.33-7
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 7,436 kB
  • ctags: 15,511
  • sloc: ansic: 92,150; asm: 684; sh: 486; makefile: 91
file content (2297 lines) | stat: -rw-r--r-- 70,494 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
/* Copyright (C) 1991, 1995 Aladdin Enterprises.  All rights reserved.
  
  This file is part of GNU Ghostscript.
  
  GNU Ghostscript is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility to
  anyone for the consequences of using it or for whether it serves any
  particular purpose or works at all, unless he says so in writing.  Refer
  to the GNU Ghostscript General Public License for full details.
  
*/

/* gdevcdj.c */
/* H-P colour printer drivers */
#include "std.h"		/* to stop stdlib.h redefining types */
#include <stdlib.h>		/* for rand() */
#include "gdevprn.h"
#include "gdevpcl.h"
#include "gsparam.h"
#include "gsstate.h"

/***
 *** This file contains multiple drivers.  The main body of code, and all
 *** but the DesignJet driver, were contributed by George Cameron;
 *** please contact g.cameron@biomed.abdn.ac.uk if you have questions.
 *     1 - cdj500:	HP DeskJet 500C
 *     2 - cdj550:	HP DeskJet 550C
 *     3 - pjxl300:	HP PaintJet XL300
 *     4 - pj:		HP PaintJet
 *     5 - pjxl:	HP PaintJet XL
 *     6 - declj250:	DEC LJ250
 *** The DesignJet 650C driver was contributed by Koert Zeilstra;
 *** please contact koert@zen.cais.com if you have questions.
 *     7 - dnj650c      HP DesignJet 650C
 *** The LaserJet 4 driver with dithering was contributed by Eckhard
 *** Rueggeberg; please contact eckhard@ts.go.dlr.de if you have questions.
 *     8 - lj4dith:	HP LaserJet 4 with dithering
 ***/

/*
 * All of these drivers have 8-bit (monochrome), 16-bit and 24-bit
 *     (colour) and for the DJ 550C 32-bit, (colour, cmyk mode)
 *     options in addition to the usual 1-bit and 3-bit modes
 * It is also possible to set various printer-specific parameters
 *     from the gs command line, eg.
 *
 *  gs -sDEVICE=cdj550 -dBitsPerPixel=16 -dDepletion=1 -dShingling=2 tiger.ps
 *
 * Please consult the appropriate section in the devices.doc file for
 * further details on all these drivers.
 */

#define DESKJET_PRINT_LIMIT  0.04	/* 'real' top margin? */
#define PAINTJET_PRINT_LIMIT 0.0	/* This is a guess.. */
#define ESC_P_PRINT_LIMIT    0.335
#define BJC600_PRINT_LIMIT   (2.5/25.4)	/* Experimental result */

/* Margins are left, bottom, right, top. */
#define DESKJET_MARGINS_LETTER   0.25, 0.50, 0.25, 0.167
#define DESKJET_MARGINS_A4       0.125, 0.50, 0.143, 0.167
#define LJET4_MARGINS  		 0.26, 0.0, 0.0, 0.0
/* The PaintJet and DesignJet seem to have the same margins */
/* regardless of paper size. */
#define PAINTJET_MARGINS         0.167, 0.167, 0.167, 0.167
#define DESIGNJET_MARGINS        0.167, 0.167, 0.167, 0.167
#define BJC600_MARGINS_LETTER  (3.2/25.4), (11.0/25.4), (3.2/25.4), (2.5/25.4)
#define BJC600_MARGINS_A4      (3.2/25.4), (11.0/25.4), (3.2/25.4), (2.5/25.4)
/*
 * With ESC/P commands, BJC-600 can print no more than 8 inches width.
 * So it can't use full width of letter size paper.  Since non printable
 * left side area is 0.134 inch, we set up margins as follows.
 */
#define ESC_P_MARGINS_LETTER    0.134, 0.276+0.2, 0.366+0.01, 0.335
#define ESC_P_MARGINS_A4        0.134, 0.276+0.2, 0.166+0.01, 0.335

#define BJ_SIZE_A4 0
#define BJ_SIZE_B5 1
#define BJ_SIZE_PC 2
#define BJ_SIZE_LETTER 3
#define BJ_SIZE_LEGAL 4
  
/* Default page size is US-Letter or A4 (other sizes from command line). */
#ifndef A4
#  define WIDTH_10THS            85
#  define HEIGHT_10THS           110
#else
#  define WIDTH_10THS            83      /* 210mm */
#  define HEIGHT_10THS           117     /* 297mm */
#endif

/* Define bits-per-pixel for generic drivers - default is 24-bit mode */
#ifndef BITSPERPIXEL
#  define BITSPERPIXEL 24
#endif

#define W sizeof(word)
#define I sizeof(int)


#define invert_word(v)\
     ((v) >> 24) + (((v) >> 8) & 0xff00L) +\
	 (((word)(v) << 8) & 0xff0000L) + ((word)(v) << 24)


/* Printer types */
#define DJ500C   0
#define DJ550C   1
#define PJXL300  2
#define PJ180    3
#define PJXL180  4
#define DECLJ250 5
#define DNJ650C  6
#define LJ4DITH  7
#define ESC_P	 8
#define BJC600	 9

/* No. of ink jets (used to minimise head movements) */
#define HEAD_ROWS_MONO 50
#define HEAD_ROWS_COLOUR 16
#define BJ_HEAD_ROWS_MONO 64
#define BJ_HEAD_ROWS_COLOUR 64

/* Colour mapping procedures */
private dev_proc_map_rgb_color (gdev_pcl_map_rgb_color);
private dev_proc_map_color_rgb (gdev_pcl_map_color_rgb);

/* Print-page, parameters and miscellaneous procedures */
private dev_proc_open_device(dj500c_open);
private dev_proc_open_device(dj550c_open);
private dev_proc_open_device(dnj650c_open);
private dev_proc_open_device(lj4dith_open);
private dev_proc_open_device(pj_open);
private dev_proc_open_device(pjxl_open);
private dev_proc_open_device(pjxl300_open);
private dev_proc_open_device(escp_open);
private dev_proc_open_device(bjc600_open);

private dev_proc_print_page(declj250_print_page);
private dev_proc_print_page(dj500c_print_page);
private dev_proc_print_page(dj550c_print_page);
private dev_proc_print_page(dnj650c_print_page);
private dev_proc_print_page(lj4dith_print_page);
private dev_proc_print_page(pj_print_page);
private dev_proc_print_page(pjxl_print_page);
private dev_proc_print_page(pjxl300_print_page);
private dev_proc_print_page(escp_print_page);
private dev_proc_print_page(bjc600_print_page);

private dev_proc_get_params(cdj_get_params);
private dev_proc_get_params(pjxl_get_params);
private dev_proc_get_params(bj_get_params);
#define ep_get_params cdj_get_params

private dev_proc_put_params(cdj_put_params);
private dev_proc_put_params(pj_put_params);
private dev_proc_put_params(pjxl_put_params);
private dev_proc_put_params(bj_put_params);
#define ep_put_params cdj_put_params

/* The device descriptors */
typedef struct gx_device_cdj_s gx_device_cdj;
struct gx_device_cdj_s {
	gx_device_common;
	gx_prn_device_common;
	int correction;           /* Black correction parameter */
	int shingling;		  /* Interlaced, multi-pass printing */
	int depletion;		  /* 'Intelligent' dot-removal */
};

typedef struct gx_device_pjxl_s gx_device_pjxl;
struct gx_device_pjxl_s {
	gx_device_common;
	gx_prn_device_common;
	uint correction;          /* Black correction parameter */
	int printqual;            /* Mechanical print quality */
	int rendertype;           /* Driver or printer dithering control */
};

typedef struct gx_device_hp_s gx_device_hp;
struct gx_device_hp_s {
	gx_device_common;
	gx_prn_device_common;
	uint correction;          /* Black correction parameter
				   * (used only by DJ500C) */
};

typedef struct gx_device_hp_s gx_device_pj;

typedef struct gx_device_bj_s gx_device_bj;
struct gx_device_bj_s {
        gx_device_common;
        gx_prn_device_common;
	int blackemphasis;	/* 0: normal, 1: black emphasis */
	int draft;		/* 0: normal, 1: draft printing */
	int color;		/* 0: Transparent */
				/* 1: M, 2: C, 4: Y, 7: K (Color decomp) */
				/* if > 8, print in black ink. */
	int thickness;		/* 0: normal, 1: thick paper */
	int paperkind;		/* 0: normal, 1: coated paper, 2: OHP, 3: BPF */
	int papersize;		/* 0:a4, 1:b5, 2:postcard, 3:letter, 4:legal */
	int sheetfeeder;
};


#define hp_device ((gx_device_hp *)pdev)
#define cdj       ((gx_device_cdj *)pdev)
#define pjxl      ((gx_device_pjxl *)pdev)
#define pj    ((gx_device_pj *)pdev)
#define bj    ((gx_device_bj *)pdev)

/* Note: the computation of color_info values here must match */
/* the computation in the set_bpp procedure below. */
#define prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page)\
    prn_device_body(gx_device_printer, procs, dev_name,\
    WIDTH_10THS, HEIGHT_10THS, x_dpi, y_dpi, 0, 0, 0, 0,\
    (bpp == 32 ? 4 : (bpp == 1 || bpp == 8) ? 1 : 3), bpp,\
    (bpp >= 8 ? 255 : 1), (bpp >= 8 ? 255 : bpp > 1 ? 1 : 0),\
    (bpp >= 8 ? 5 : 2), (bpp >= 8 ? 5 : bpp > 1 ? 2 : 0),\
    print_page)

#define cdj_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page, correction, shingling, depletion)\
{ prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page),\
    correction,\
    shingling,\
    depletion\
}

#define pjxl_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page, printqual, rendertype)\
{ prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page), 0, \
    printqual,\
    rendertype\
}

#define pj_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page)\
{ prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page), 0\
}

#define bj_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page, a, b, c, d, e, f, g)\
{ prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page),\
    a, b, c, d, e, f, g\
}


#define hp_colour_procs(proc_colour_open, proc_get_params, proc_put_params) {\
	proc_colour_open,\
	gx_default_get_initial_matrix,\
	gx_default_sync_output,\
	gdev_prn_output_page,\
	gdev_prn_close,\
	gdev_pcl_map_rgb_color,\
	gdev_pcl_map_color_rgb,\
	NULL,	/* fill_rectangle */\
	NULL,	/* tile_rectangle */\
	NULL,	/* copy_mono */\
	NULL,	/* copy_color */\
	NULL,	/* draw_line */\
	gx_default_get_bits,\
	proc_get_params,\
	proc_put_params\
}

private gx_device_procs cdj500_procs =
hp_colour_procs(dj500c_open, cdj_get_params, cdj_put_params);

private gx_device_procs cdj550_procs =
hp_colour_procs(dj550c_open, cdj_get_params, cdj_put_params);

private gx_device_procs dnj650c_procs =
hp_colour_procs(dnj650c_open, cdj_get_params, cdj_put_params);

private gx_device_procs lj4dith_procs =
hp_colour_procs(lj4dith_open, cdj_get_params, cdj_put_params);

private gx_device_procs pj_procs =
hp_colour_procs(pj_open, gdev_prn_get_params, pj_put_params);

private gx_device_procs pjxl_procs =
hp_colour_procs(pjxl_open, pjxl_get_params, pjxl_put_params);

private gx_device_procs pjxl300_procs =
hp_colour_procs(pjxl300_open, pjxl_get_params, pjxl_put_params);

private gx_device_procs bjc600_procs =
hp_colour_procs(bjc600_open, bj_get_params, bj_put_params);

private gx_device_procs escp_procs =
hp_colour_procs(escp_open, ep_get_params, ep_put_params);

gx_device_cdj far_data gs_cdjmono_device =
cdj_device(cdj500_procs, "cdjmono", 300, 300, 1,
	   dj500c_print_page, 4, 0, 1);

gx_device_cdj far_data gs_cdeskjet_device =
cdj_device(cdj500_procs, "cdeskjet", 300, 300, BITSPERPIXEL,
	   dj500c_print_page, 4, 2, 1);

gx_device_cdj far_data gs_cdjcolor_device =
cdj_device(cdj500_procs, "cdjcolor", 300, 300, 24,
	   dj500c_print_page, 4, 2, 1);

gx_device_cdj far_data gs_cdj500_device =
cdj_device(cdj500_procs, "cdj500", 300, 300, BITSPERPIXEL,
	   dj500c_print_page, 4, 2, 1);

gx_device_cdj far_data gs_cdj550_device =
cdj_device(cdj550_procs, "cdj550", 300, 300, BITSPERPIXEL,
	   dj550c_print_page, 0, 2, 1);

gx_device_pj far_data gs_declj250_device =
pj_device(pj_procs, "declj250", 180, 180, BITSPERPIXEL,
	  declj250_print_page);

gx_device_cdj far_data gs_dnj650c_device =
cdj_device(dnj650c_procs, "dnj650c", 300, 300, BITSPERPIXEL,
	   dnj650c_print_page, 0, 2, 1);
	   
gx_device_cdj far_data gs_lj4dith_device =
cdj_device(lj4dith_procs, "lj4dith", 600, 600, 8,
	   lj4dith_print_page, 4, 0, 1);

gx_device_pj far_data gs_pj_device =
pj_device(pj_procs, "pj", 180, 180, BITSPERPIXEL,
	  pj_print_page);

gx_device_pjxl far_data gs_pjxl_device =
pjxl_device(pjxl_procs, "pjxl", 180, 180, BITSPERPIXEL,
	    pjxl_print_page, 0, 0);

gx_device_pjxl far_data gs_pjxl300_device =
pjxl_device(pjxl300_procs, "pjxl300", 300, 300, BITSPERPIXEL,
	    pjxl300_print_page, 0, 0);

gx_device_cdj far_data gs_escp_device =
cdj_device(escp_procs, "escp", 360, 360, 8,
	   escp_print_page, 0, 0, 1);

gx_device_cdj far_data gs_escpc_device =
cdj_device(escp_procs, "escpc", 360, 360, 32,
	   escp_print_page, 0, 0, 1);

gx_device_bj far_data gs_bjc600_device =
bj_device(bjc600_procs, "bjc600", 360, 360, 8,
	  bjc600_print_page, 0, 0, 0, 0, 0, 0, 0);

gx_device_bj far_data gs_bjc600c_device =
bj_device(bjc600_procs, "bjc600c", 360, 360, 32,
	  bjc600_print_page, 0, 0, 0, 0, 0, 0, 0);

/* Forward references */
private int gdev_pcl_mode1compress(P3(const byte *, const byte *, byte *));
private int gdev_pcl_mode9compress(P4(int, const byte *, const byte *, byte *));
private int hp_colour_open(P2(gx_device *, int));
private int hp_colour_print_page(P3(gx_device_printer *, FILE *, int));
private int near put_param_int(P6(gs_param_list *, gs_param_name, int *, int, int, int));
private uint gdev_prn_rasterwidth(P2(const gx_device_printer *, int));
private int put_params_bpp(P3(gx_device *, gs_param_list *, int));
private int set_bpp(P2(gx_device *, int));
private void expand_line(P4(word *, int, int, int));
private int bj_paper_size(P1(gx_device *dev));

/* Open the printer and set up the margins. */
private int
dj500c_open(gx_device *pdev)
{ return hp_colour_open(pdev, DJ500C);
}

private int
dj550c_open(gx_device *pdev)
{ return hp_colour_open(pdev, DJ550C);
}

private int
dnj650c_open(gx_device *pdev)
{ return hp_colour_open(pdev, DNJ650C);
}

private int
lj4dith_open(gx_device *pdev)
{ return hp_colour_open(pdev, LJ4DITH);
}

private int
pjxl300_open(gx_device *pdev)
{ return hp_colour_open(pdev, PJXL300);
}

private int
pj_open(gx_device *pdev)
{ return hp_colour_open(pdev, PJ180);
}

private int
pjxl_open(gx_device *pdev)
{ return hp_colour_open(pdev, PJXL180);
}

private int
escp_open(gx_device *pdev)
{ return hp_colour_open(pdev, ESC_P);
}

private int
bjc600_open(gx_device *pdev)
{ return hp_colour_open(pdev, BJC600);
}


private int
hp_colour_open(gx_device *pdev, int ptype)
{	/* Change the margins if necessary. */
  static const float dj_a4[4] = { DESKJET_MARGINS_A4 };
  static const float dj_letter[4] = { DESKJET_MARGINS_LETTER };
  static const float lj4_all[4] = { LJET4_MARGINS };
  static const float pj_all[4] = { PAINTJET_MARGINS };
  static const float dnj_all[4] = { DESIGNJET_MARGINS };
  static const float ep_a4[4] = { ESC_P_MARGINS_A4 };
  static const float ep_letter[4] = { ESC_P_MARGINS_LETTER };
  static const float bj_a4[4] = { BJC600_MARGINS_A4 };
  static const float bj_letter[4] = { BJC600_MARGINS_LETTER };
  const float _ds *m;

  /* Set up colour params if put_params has not already done so */
  if (pdev->color_info.num_components == 0)
    {	int code = set_bpp(pdev, pdev->color_info.depth);
	if ( code < 0 )
	  return code;
    }

  switch (ptype) {
  case DJ500C:
  case DJ550C:
    m = (gdev_pcl_paper_size(pdev) == PAPER_SIZE_A4 ? dj_a4 :
	 dj_letter);
    break;
  case DNJ650C:
    m = dnj_all;
    break;
  case LJ4DITH:
    m = lj4_all;
    break;  
  case PJ180:
  case PJXL300:
  case PJXL180:
    m = pj_all;
    break;
  case ESC_P:
    m = (gdev_pcl_paper_size(pdev) == PAPER_SIZE_A4 ? ep_a4 :
	 ep_letter);
    break;
  case BJC600:
    switch (bj->papersize = bj_paper_size(pdev)) {
    case BJ_SIZE_A4: m = bj_a4; break;
    case BJ_SIZE_B5: m = bj_a4; break;
    case BJ_SIZE_PC: m = bj_a4; break;
    case BJ_SIZE_LETTER: m = bj_letter; break;
    case BJ_SIZE_LEGAL: m = bj_letter; break;
    default: m = bj_a4;
    }
    break;
  }
  gx_device_set_margins(pdev, m, true);
  return gdev_prn_open(pdev);
}

/* Added parameters for DeskJet 5xxC */

/* Get parameters.  In addition to the standard and printer 
 * parameters, we supply shingling and depletion parameters,
 * and control over the bits-per-pixel used in output rendering */
private int
cdj_get_params(gx_device *pdev, gs_param_list *plist)
{	int code = gdev_prn_get_params(pdev, plist);
	if ( code < 0 ||
	    (code = param_write_int(plist, "BlackCorrect", &cdj->correction)) < 0 ||
	    (code = param_write_int(plist, "Shingling", &cdj->shingling)) < 0 ||
	    (code = param_write_int(plist, "Depletion", &cdj->depletion)) < 0
	   )
	  ;
	return code;
}

/* Put parameters. */
private int
cdj_put_params(gx_device *pdev, gs_param_list *plist)
{	int correction = cdj->correction;
	int shingling = cdj->shingling;
	int depletion = cdj->depletion;
	int bpp = 0;
	int code = 0;

	code = put_param_int(plist, "BlackCorrect", &correction, 0, 9, code);
	code = put_param_int(plist, "Shingling", &shingling, 0, 2, code);
	code = put_param_int(plist, "Depletion", &depletion, 1, 3, code);
	code = put_param_int(plist, "BitsPerPixel", &bpp, 1, 32, code);

	if ( code < 0 )
	  return code;
	code = put_params_bpp(pdev, plist, bpp);
	if ( code < 0 )
	  return code;

	cdj->correction = correction;
	cdj->shingling = shingling;
	cdj->depletion = depletion;
	return 0;
}

/* Added parameters for PaintJet XL and PaintJet XL300 */

/* Get parameters.  In addition to the standard and printer
 * parameters, we supply print_quality and render_type 
 * parameters, together with bpp control. */
private int
pjxl_get_params(gx_device *pdev, gs_param_list *plist)
{	int code = gdev_prn_get_params(pdev, plist);
	if ( code < 0 ||
	    (code = param_write_int(plist, "PrintQuality", &pjxl->printqual)) < 0 ||
	    (code = param_write_int(plist, "RenderType", &pjxl->rendertype)) < 0
	   )
	  ;
	return code;
}

/* Put parameters. */
private int
pjxl_put_params(gx_device *pdev, gs_param_list *plist)
{	int printqual = pjxl->printqual;
	int rendertype = pjxl->rendertype;
	int bpp = 0;
	int code = 0;

	code = put_param_int(plist, "PrintQuality", &printqual, -1, 1, code);
	code = put_param_int(plist, "RenderType", &rendertype, 0, 10, code);
	code = put_param_int(plist, "BitsPerPixel", &bpp, 1, 32, code);

	if ( code < 0 )
	  return code;
	if ( rendertype > 0 )
	  {	/* If printer is doing the dithering, we must have a
		 * true-colour mode, ie. 16 or 24 bits per pixel */
		if ( bpp > 0 && bpp < 16 )
		  bpp = 24;
	  }
	code = put_params_bpp(pdev, plist, bpp);
	if ( code < 0 )
	  return code;

	pjxl->printqual = printqual;
	pjxl->rendertype = rendertype;
	return 0;
}

/* Added parameters for PaintJet */

/* Put parameters.  In addition to the standard and printer */
/* parameters, we allow control of the bits-per-pixel */
private int
pj_put_params(gx_device *pdev, gs_param_list *plist)
{	int bpp = 0;
	int code = put_param_int(plist, "BitsPerPixel", &bpp, 1, 32, 0);

	if ( code < 0 )
	  return code;
	return put_params_bpp(pdev, plist, bpp);
}

private int
bj_get_params(gx_device *pdev, gs_param_list *plist)
{	int code = gdev_prn_get_params(pdev, plist);
	if ( code < 0 ||
	    (code = param_write_int(plist, "BJblackemphasis",
				    &bj->blackemphasis)) < 0 ||
	    (code = param_write_int(plist, "BJdraft", &bj->draft)) < 0 ||
	    (code = param_write_int(plist, "BJthickness",
				    &bj->thickness)) < 0 ||
	    (code = param_write_int(plist, "BJpapersize",
				    &bj->papersize)) < 0 ||
    	    (code = param_write_int(plist, "BJsheetfeeder",
				    &bj->sheetfeeder)) < 0)
	  ;

	return code;
}


/* Put properties. */
private int
bj_put_params(gx_device *pdev, gs_param_list *plist) {
	int save_bpp = bj->color_info.depth;
	int bpp = 0;
	int code = 0;

	code = gdev_prn_put_params(pdev, plist);
	if ( code < 0 ) return code;

	code = put_param_int(plist, "BitsPerPixel", &bpp, 1, 32, code);
	code = put_param_int(plist, "BJblackemphasis", &bj->blackemphasis, 0, 1, code);
	code = put_param_int(plist, "BJdraft", &bj->draft, 0, 1, code);
	code = put_param_int(plist, "BJcolor", &bj->color, 0, 15, code);
	code = put_param_int(plist, "BJthickness", &bj->thickness, 0, 1, code);
	code = put_param_int(plist, "BJpaperkind", &bj->paperkind, 0, 3, code);
	code = put_param_int(plist, "BJpapertype", &bj->papersize, 0, 4, code);
	code = put_param_int(plist, "BJsheetfeeder", &bj->sheetfeeder, 1, 3, code);

	if ( code < 0 )
	  return_error(code);

	if (bpp != 0) {
	  set_bpp(pdev, bpp);

	  /* Close the device; gs_putdeviceprops will reopen it. */
	  if ( bpp != save_bpp && pdev->is_open )
	    { int ccode = gs_closedevice(pdev);
	      if ( ccode < 0 ) return ccode;
	    }
	}
	
	return code;
}

/* ------ Internal routines ------ */

/* The DeskJet500C can compress (mode 9) */
private int
dj500c_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
  return hp_colour_print_page(pdev, prn_stream, DJ500C);
}

/* The DeskJet550C can compress (mode 9) */
private int
dj550c_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
  return hp_colour_print_page(pdev, prn_stream, DJ550C);
}

/* The DesignJet650C can compress (mode 1) */
private int
dnj650c_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
  return hp_colour_print_page(pdev, prn_stream, DNJ650C);
}

private int
lj4dith_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
  return hp_colour_print_page(pdev, prn_stream, LJ4DITH);
}

/* The PJXL300 can compress (modes 2 & 3) */
private int
pjxl300_print_page(gx_device_printer * pdev, FILE * prn_stream)
{ int ret_code;
  /* Ensure we're operating in PCL mode */
  fputs("\033%-12345X@PJL enter language = PCL\n", prn_stream);
  ret_code = hp_colour_print_page(pdev, prn_stream, PJXL300);
  /* Reenter switch-configured language */
  fputs("\033%-12345X", prn_stream);
  return ret_code;
}

/* The PaintJet XL can compress (modes 2 & 3) */
private int
pjxl_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
  return hp_colour_print_page(pdev, prn_stream, PJXL180);
}

/* The PaintJet can compress (mode 1) */
private int
pj_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
  return hp_colour_print_page(pdev, prn_stream, PJ180);
}

/* The LJ250 can compress (mode 1) */
private int
declj250_print_page(gx_device_printer * pdev, FILE * prn_stream)
{ int ret_code;
  fputs("\033%8", prn_stream);	/* Enter PCL emulation mode */
  ret_code = hp_colour_print_page(pdev, prn_stream, DECLJ250);
  fputs("\033%@", prn_stream);	/* Exit PCL emulation mode */
  return ret_code;
}

/* The BJC-600 cannot compress w/o raster image commands. */
private int
escp_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
  return hp_colour_print_page(pdev, prn_stream, ESC_P);
}

/* The BJC-600 can compress w/ raster image commands. */
private int
bjc600_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
  return hp_colour_print_page(pdev, prn_stream, BJC600);
}


/* MACROS FOR DITHERING (we use macros for compact source and faster code) */
/* Floyd-Steinberg dithering. Often results in a dramatic improvement in
 * subjective image quality, but can also produce dramatic increases in
 * amount of printer data generated and actual printing time!! Mode 9 2D
 * compression is still useful for fairly flat colour or blank areas but its
 * compression is much less effective in areas where the dithering has
 * effectively randomised the dot distribution. */

#define SHIFT ((I * 8) - 13)
#define RSHIFT ((I * 8) - 16)
#define RANDOM (((rand() << RSHIFT) % (MAXVALUE / 2))  - MAXVALUE / 4);
#define MINVALUE  0
#define MAXVALUE  (255 << SHIFT)
#define THRESHOLD (128 << SHIFT)
#define C 8

#define FSdither(inP, out, errP, Err, Bit, Offset, Element)\
	oldErr = Err;\
	Err = (errP[Element] + ((Err * 7 + C) >> 4) + ((int)inP[Element] << SHIFT));\
	if (Err > THRESHOLD) {\
	  out |= Bit;\
	  Err -= MAXVALUE;\
	}\
	errP[Element + Offset] += ((Err * 3 + C) >> 4);\
	errP[Element] = ((Err * 5 + oldErr + C) >> 4);

/* Here we rely on compiler optimisation to remove lines of the form
 * (if (1 >= 4) {...}, ie. the constant boolean expressions */

#define FSDline(scan, i, j, plane_size, cErr, mErr, yErr, kErr, cP, mP, yP, kP, n)\
{\
    if (scan == 0) {       /* going_up */\
      for (i = 0; i < plane_size; i++) {\
	byte c, y, m, k, bitmask;\
	int oldErr;\
	bitmask = 0x80;\
	for (c = m = y = k = 0; bitmask != 0; bitmask >>= 1) {\
	  if (n >= 4) {\
	    if (*dp) {\
	      FSdither(dp, k, ep, kErr, bitmask, -n, 0);\
	      cErr = mErr = yErr = 0;\
	    } else {\
	      FSdither(dp, c, ep, cErr, bitmask, -n, n - 3);\
	      FSdither(dp, m, ep, mErr, bitmask, -n, n - 2);\
	      FSdither(dp, y, ep, yErr, bitmask, -n, n - 1);\
	    }\
	  } else {\
	    if (n >= 3) {\
	      FSdither(dp, c, ep, cErr, bitmask, -n, n - 3);\
	      FSdither(dp, m, ep, mErr, bitmask, -n, n - 2);\
	    }\
	    FSdither(dp, y, ep, yErr, bitmask, -n, n - 1);\
	  }\
	  dp += n, ep += n;\
	}\
	if (n >= 4)\
	  *kP++ = k;\
	if (n >= 3) {\
	  *cP++ = c;\
          *mP++ = m;\
	}\
	*yP++ = y;\
      }\
    } else {		/* going_down */\
      for (i = 0; i < plane_size; i++) {\
	byte c, y, m, k, bitmask;\
	int oldErr;\
	bitmask = 0x01;\
	for (c = m = y = k = 0; bitmask != 0; bitmask <<= 1) {\
          dp -= n, ep -= n;\
	  if (n >= 4) {\
            if (*(dp)) {\
	      cErr = mErr = yErr = 0;\
	      FSdither(dp, k, ep, kErr, bitmask, n, 0);\
	    } else {\
	      FSdither(dp, y, ep, yErr, bitmask, n, n - 1);\
	      FSdither(dp, m, ep, mErr, bitmask, n, n - 2);\
	      FSdither(dp, c, ep, cErr, bitmask, n, n - 3);\
	    }\
	  } else {\
	    FSdither(dp, y, ep, yErr, bitmask, n, n - 1);\
	    if (n >= 3) {\
	      FSdither(dp, m, ep, mErr, bitmask, n, n - 2);\
	      FSdither(dp, c, ep, cErr, bitmask, n, n - 3);\
	    }\
	  }\
	}\
	*--yP = y;\
	if (n >= 3)\
	  { *--mP = m;\
	    *--cP = c;\
	  }\
	if (n >= 4)\
	  *--kP = k;\
      }\
    }\
}
/* END MACROS FOR DITHERING */

/* Some convenient shorthand .. */
#define x_dpi        (pdev->x_pixels_per_inch)
#define y_dpi        (pdev->y_pixels_per_inch)
#define CONFIG_16BIT "\033*v6W\000\003\000\005\006\005"
#define CONFIG_24BIT "\033*v6W\000\003\000\010\010\010"

/* To calculate buffer size as next greater multiple of both parameter and W */
#define calc_buffsize(a, b) (((((a) + ((b) * W) - 1) / ((b) * W))) * W)


/*
 * Miscellaneous functions for Canon BJC-600 printers in raster command mode.
 */
#define fputshort(n, f) fputc((n)%256,f);fputc((n)/256,f)
private
int bj_paper_size(gx_device *dev)
{	return
	  (dev->height / dev->y_pixels_per_inch >= 11.8 ? BJ_SIZE_LEGAL :
	   dev->height / dev->y_pixels_per_inch >= 11.1 ? BJ_SIZE_A4 :
	   dev->height / dev->y_pixels_per_inch >= 10.0 ? BJ_SIZE_LETTER :
	   dev->height / dev->y_pixels_per_inch >= 6.0 ? BJ_SIZE_B5 :
	   BJ_SIZE_PC
	   );
}


private
int bj_cmd(byte cmd, int argsize, byte* arg, gx_device_printer* pdev, FILE* stream) {
  fputs("\033(", stream);
  putc(cmd, stream);
  fputshort(argsize, stream);
  fwrite(arg, sizeof(byte), argsize, stream);


  return 0;
}


private
int bj_raster_cmd_sub(char c, int rastsize, byte* data, FILE* stream) {
  fputs("\033(A", stream);
  fputshort(rastsize+1, stream);
  putc(c, stream);
  fwrite(data, sizeof(byte), rastsize, stream);
  putc('\015', stream);


  return 0;
}


private
int bj_raster_cmd(int c_id, int rastsize, byte* data, gx_device_printer* pdev,
    FILE* stream)
{
  char c;


/*
fprintf(stderr, "bj_raster_cmd(%d, %d, %p, ...) with color %d out of %d\n",
    c_id, rastsize, data, bj->color, pdev->color_info.num_components);
*/
  if (pdev->color_info.num_components == 1) {
    if (bj->color == 0) {
      bj_raster_cmd_sub('K', rastsize, data, stream);
    } else {
      if (bj->color == 7) bj_raster_cmd_sub('K', rastsize, data, stream);
      else {
	if (bj->color & 1) bj_raster_cmd_sub('M', rastsize, data, stream);
	if (bj->color & 2) bj_raster_cmd_sub('C', rastsize, data, stream);
	if (bj->color & 4) bj_raster_cmd_sub('Y', rastsize, data, stream);
      }
    }
  } else if (bj->color == 0) {
    bj_raster_cmd_sub("YMCK"[c_id], rastsize, data, stream);
  } else {			/* Color decomposition */
    if (bj->color & (int)"\004\001\002\010"[c_id]) {
      if (bj->color & 010) bj_raster_cmd_sub('K', rastsize, data, stream);
      else bj_raster_cmd_sub("YMCK"[c_id], rastsize, data, stream);
    }
  }


  return 0;
}


private
int bj_init_page(gx_device_printer* pdev, FILE* stream)
{
  byte papersize[3], resolution[2], param_c[3], param_l[2];


  papersize[0] = (byte)(pdev->height / pdev->y_pixels_per_inch * 10);
  papersize[1] =  1;
  papersize[2] = (byte)(pdev->width / pdev->x_pixels_per_inch * 10);


  resolution[0] = (byte)pdev->x_pixels_per_inch / 256;
  resolution[1] = (byte)pdev->x_pixels_per_inch % 256;


  param_c[0] = 0x10;
  param_c[1] = bj->draft ? 2 : (bj->paperkind << 4) + 1;
  param_c[2] = (bj->blackemphasis << 4) + bj->thickness;


  param_l[0] = 0x14;
  param_l[1] = (bj->paperkind > 2 ? 2 : bj->paperkind) << 4;


/*  fputs("\033~Z", stream); fputshort(1, stream); putc(1, stream);*/
  fputs("\033[K", stream); fputshort(2, stream); putc(0, stream); putc(15, stream);
  bj_cmd('a', 1, (byte*) "\001", pdev, stream);
  bj_cmd('b', 1, (byte*) "\001", pdev, stream);
  bj_cmd('d', 2, resolution, pdev, stream);
  bj_cmd('c', 3, param_c, pdev, stream);
  bj_cmd('l', 2, param_l, pdev, stream);
  bj_cmd('g', 3, papersize, pdev, stream);


  return 0;
}


private
int bj_v_skip(int n, gx_device_printer* pdev, FILE* stream)
{
  if (n) {
    fputs("\033(e", stream);
    putc(2, stream);
    putc(0, stream);
    putc(n/256, stream);
    putc(n%256, stream);
  }


  return 0;
}


private
int bj_finish_page(gx_device_printer* pdev, FILE* stream)
{
  bj_cmd('b', 1, (byte*) "\000", pdev, stream);
  bj_cmd('a', 1, (byte*) "\000", pdev, stream);
  fputs("\033@", stream);


  return 0;
}


/* 1D runlength compression for BJC-600
 * this code is borrowed from gdevpcl.c:gdev_pcl_mode2compress.
 */
private
int bj_compress(const byte *row, const byte *end_row, byte *compressed)
{
  register const byte *exam = row;
  register byte *cptr = compressed; /* output pointer into compressed bytes */
  

  while ( exam < end_row ) {
    /* Search ahead in the input looking for a run */
    /* of at least 4 identical bytes. */
    const byte *compr = exam;
    const byte *end_dis;
    const byte *next;
    register byte test, test2;
    register word testw;
    

    test = *exam;
    while ( exam < end_row ) {
      test2 = *++exam;
      if ( test == test2 )
	  break;
      test = test2;
    }
    

    /* Find out how long the run is */
    end_dis = exam - 1;
    if ( exam == end_row ) { /* no run */
      next = --end_row;
    } else { 

      next = exam + 1;
      while ( next < end_row && *next == test ) next++;
    }
    

    /* Now [compr..end_dis) should be encoded as dissimilar, */
    /* and [end_dis..next) should be encoded as similar. */
    /* Note that either of these ranges may be empty. */
    

    for ( ; ; ) {	/* Encode up to 128 dissimilar bytes */
      uint count = end_dis - compr; /* uint for faster switch */
      switch ( count ) { /* Use memcpy only if it's worthwhile. */
      case 6: cptr[6] = compr[5];
      case 5: cptr[5] = compr[4];
      case 4: cptr[4] = compr[3];
      case 3: cptr[3] = compr[2];
      case 2: cptr[2] = compr[1];
      case 1: cptr[1] = compr[0];
	*cptr = count - 1;
	cptr += count + 1;
      case 0: /* all done */
	break;
      default:
	if ( count > 128 ) count = 128;
	*cptr++ = count - 1;
	memcpy(cptr, compr, count);
	cptr += count, compr += count;
	continue;
      }
      break;
    }
    

    {	/* Encode up to 128 similar bytes. */
      /* Note that count may be <0 at end of row. */
      int count = next - end_dis;
      if (next < end_row || test != 0)
	while ( count > 0 ) { 

	  int this = (count > 128 ? 128 : count);
	  *cptr++ = 257 - this;
	  *cptr++ = (byte)test;
	  count -= this;
	}
      exam = next;
    }
  }
  return cptr - compressed;
}


/*
 * Canon BJC-600 features BJ raster image commands but currently not opened to
 * public.  So we should transform raster image to serial printer image.
 * Currently, resolution is fixed as 360dpi.
 */
private word *ep_storage;
private uint ep_storage_size_words;
private byte *ep_raster_buf[4][BJ_HEAD_ROWS_COLOUR], *ep_print_buf;
private int ep_num_comps, ep_plane_size, img_rows=BJ_HEAD_ROWS_COLOUR;


#define row_bytes (img_rows / 8)
#define row_words (row_bytes / sizeof(word))
#define min_rows (32)		/* for optimization of text image printing */


private int
ep_print_image(FILE *prn_stream, char cmd, byte *data, int size)
{
  static int ln_idx=0, vskip1=0, vskip2=0, real_rows;
  int i;
  static const char color[4] = {4,1,2,0};


  switch (cmd) {
  case 3:			/* Black */
  case 2:			/* Cyan */
  case 1:			/* Magenta */
  case 0:			/* Yellow */
    memcpy(ep_raster_buf[cmd][ln_idx+vskip2], data, size);
    return 0;
    break;
  case 'B':			/* blank line skip */
    if (!ln_idx) {
      vskip1 += size;
    } else if (size >= img_rows - (ln_idx+vskip2) || ln_idx+vskip2 >= min_rows) {
      /* The 'I' cmd must precede 'B' cmd! */
      vskip2 += size;
      ep_print_image(prn_stream, 'F', 0, 0); /* flush and reset status */
    } else {
      vskip2 += size;
    }
    return 0;
    break;
  case 'I':			/* Increment index */
    ln_idx += vskip2 + 1;
    vskip2 = 0;
    if (ln_idx < img_rows) return 0;
    /* if ep_raster_buf filled up, then fall through here and flush buffer */
  case 'F':			/* flush print buffer */
    if (!ln_idx) return 0;	/* The end of the page. */


    /* before print the image, perform vertical skip. */
    while (vskip1 >= (255*2)) {
      fputs("\033J\377", prn_stream); /* n/180in. feeding */
      vskip1 -= (255*2);
    }
    if (vskip1 > 255) {
      fputs("\033J\200", prn_stream);
      vskip1 -= 256;
    }
    if (vskip1) {
      /* n/360in. feeding */
      fputs("\033|J", prn_stream); putc(0, prn_stream); putc(vskip1, prn_stream);
    }


    /* Optimize the number of nozzles to be used. */
    if (ln_idx > 56) {		/* use 64 nozzles */
      real_rows = 64;
    } else if (ln_idx > 48) {	/* use 56 nozzles */
      real_rows = 56;
    } else if (ln_idx > 32) {	/* use 48 nozzles */
      real_rows = 48;
    } else {			/* use 32 nozzles */
      real_rows = 32;
    }


    for (i = 0; i < ep_num_comps; i++) {
      int lnum, hskip, print_size, img_rows;
      byte *p0, *p1, *p2, *p3;
      byte *inp, *inbuf, *outp, *outbuf;


      img_rows = real_rows;	/* Note that this img_rows is not the one that
				 * defined out of this function. */
      outbuf = ep_print_buf;


      /* Transpose raster image for serial printer image */
      for (lnum=0; lnum < img_rows; lnum+=8, outbuf++) {
	inbuf = inp = ep_raster_buf[i][lnum];
	for (outp = outbuf; inp < inbuf+ep_plane_size; inp++, outp += img_rows) {
	  memflip8x8(inp, ep_plane_size, outp, row_bytes);
	}
      }


      /* Set color */
      if (ep_num_comps == 1) {
	/* Don't set color (to enable user setting). */
	putc('\015', prn_stream);
      } else {
	/* set color to one of CMYK. */
	fputs("\015\033r", prn_stream);
	putc(color[i], prn_stream);
      }


      *(outp = ep_print_buf + ep_plane_size * img_rows) = 1; /* sentinel */


      p0 = p3 = ep_print_buf;


      /* print image p0 to p1 and h skip p1 to p2 if p2<outp,
       * then make p0=p2 and continue */
      while (p0 < outp) {
	static const word zeros[8] = {0,0,0,0,0,0,0,0};


	if (p3 < outp) {
	  /* p1 is the head of running zeros. */
	  /* note that h skip unit is 1/180inch */
	  for (p1 = p3; !memcmp(p3, zeros, row_bytes*2); p3 += row_bytes*2);
	  /* p2 is the head of non zero image. */
	  p2 = p3;
	redo:
	  for (p3 += row_bytes; memcmp(p3, zeros, row_bytes); p3 += row_bytes);
	  if (p3 < outp && memcmp(p3+row_bytes, zeros, row_bytes)) goto redo;
	} else p1 = p2 = outp;


	if (p0 < p1) {	/* print the image between p0 and p1 */
	  print_size = ((p1 < outp) ? p1 : outp) - p0;
	  fputs("\033|B", prn_stream); putc(img_rows, prn_stream);
	  fputshort(print_size, prn_stream);
	  fwrite(p0, sizeof(byte), print_size, prn_stream);
	}
	if (p1 < p2) {	/* skip running zeros from p1 to p2 */
	  hskip = (((p2 < outp) ? p2 : outp) - p1) / row_bytes / 2;
	  fputs("\033\\", prn_stream);
	  fputshort(hskip, prn_stream);
	}
	p0 = p2;
      }
    }
    return ep_print_image(prn_stream, 'R', 0, vskip2 + ln_idx); 
	/* Reset status */
    break;
  case 'R':			/* Reset status */
    ln_idx = 0;
    vskip1 = size;
    vskip2 = 0;
    memset(ep_storage, 0, ep_storage_size_words * W);
    return 0;
    break;
  default:			/* This should not happen */
    fprintf(stderr, "ep_print_image: illegal command character `%c'.\n", cmd);
    return 1;
  }


  /* NOT REACHED */
}


/* Send the page to the printer.  Compress each scan line. */
private int
hp_colour_print_page(gx_device_printer * pdev, FILE * prn_stream, int ptype)
{
  uint raster_width = gdev_prn_rasterwidth(pdev, 1);
/*  int line_size = gdev_prn_rasterwidth(pdev, 0); */
  int line_size = gdev_prn_raster(pdev);
  int line_size_words = (line_size + W - 1) / W;
  int paper_size = gdev_pcl_paper_size((gx_device *)pdev);
  int num_comps = pdev->color_info.num_components;
  int bits_per_pixel = pdev->color_info.depth;
  int storage_bpp = bits_per_pixel;
  int expanded_bpp = bits_per_pixel;
  int plane_size, databuff_size;
  int combined_escapes = 1;
  int errbuff_size = 0;
  int outbuff_size = 0;
  int compression = 0;
  int scan = 0;
  int *errors[2];
  const char *cid_string;
  byte *data[4], *plane_data[4][4], *out_data;
  byte *out_row, *out_row_alt;
  word *storage;
  uint storage_size_words;

  /* Tricks and cheats ... */
  switch (ptype) {
  case DJ550C:
    if (num_comps == 3)
      num_comps = 4;                      /* 4-component printing */
    break;
  case ESC_P:
  case BJC600:
    if (bits_per_pixel == 24)	/* prefer 3-component printing for bpp=24. */
      num_comps = 3;
    else if (num_comps != 1)
      num_comps = 4;
    break;
  case PJXL300:
  case PJXL180:
    if (pjxl->rendertype > 0) {
      if (bits_per_pixel < 16)
	pjxl->rendertype = 0;
      else {
	/* Control codes for CID sequence */
	cid_string = (bits_per_pixel == 16) ? CONFIG_16BIT : CONFIG_24BIT;
	/* Pretend we're a monobit device so we send the data out unchanged */
	bits_per_pixel = storage_bpp = expanded_bpp = 1;
	num_comps = 1;
      }
    }
    break;
  }

  if (storage_bpp == 8 && num_comps >= 3)
    bits_per_pixel = expanded_bpp = 3;	/* Only 3 bits of each byte used */

  plane_size = calc_buffsize(line_size, storage_bpp);
  ep_plane_size = plane_size;

  if (bits_per_pixel == 1) {		/* Data printed direct from i/p */
    databuff_size = 0;			/* so no data buffer required, */
    outbuff_size = plane_size * 4;	/* but need separate output buffers */
  }
  
  if (bits_per_pixel > 4) {		/* Error buffer for FS dithering */
    storage_bpp = expanded_bpp = 
      num_comps * 8;			/* 8, 24 or 32 bits */
    errbuff_size =			/* 4n extra values for line ends */
      calc_buffsize((plane_size * expanded_bpp + num_comps * 4) * I, 1);
  }

  databuff_size = plane_size * storage_bpp;

  storage_size_words = ((plane_size + plane_size) * num_comps +
			databuff_size + errbuff_size + outbuff_size) / W;

  storage = (ulong *) gs_malloc(storage_size_words, W, "hp_colour_print_page");
  ep_storage_size_words = (plane_size * (num_comps + 1)) / W * img_rows
      + 16;			/* Redundant space for sentinel and aligning. */
  ep_storage = (word *) gs_malloc(ep_storage_size_words, W, "ep_print_buffer");

  /*
   * The principal data pointers are stored as pairs of values, with
   * the selection being made by the 'scan' variable. The function of the
   * scan variable is overloaded, as it controls both the alternating
   * raster scan direction used in the Floyd-Steinberg dithering and also
   * the buffer alternation required for line-difference compression.
   *
   * Thus, the number of pointers required is as follows:
   * 
   *   errors:      2  (scan direction only)
   *   data:        4  (scan direction and alternating buffers)
   *   plane_data:  4  (scan direction and alternating buffers)
   */

  if (storage == 0 || ep_storage == 0) /* can't allocate working area */
    return_error(gs_error_VMerror);
  else {
    int i, j;
    byte *p = out_data = out_row = (byte *)storage;
    byte *ep_p = (byte *)ep_storage;
    data[0] = data[1] = data[2] = p;
    data[3] = p + databuff_size;
    out_row_alt = out_row + plane_size * 2;
    if (bits_per_pixel > 1) {
      p += databuff_size;
    }
    if (bits_per_pixel > 4) {
      errors[0] = (int *)p + num_comps * 2;
      errors[1] = errors[0] + databuff_size;
      p += errbuff_size;
    }
    for (i = 0; i < num_comps; i++) {
      plane_data[0][i] = plane_data[2][i] = p;
      p += plane_size;
    }
    for (i = 0; i < num_comps; i++) {
      plane_data[1][i] = p;
      plane_data[3][i] = p + plane_size;
      p += plane_size;
    }
    if (bits_per_pixel == 1) {
      out_data = out_row = p;	  /* size is outbuff_size * 4 */
      out_row_alt = out_row + plane_size * 2;
      data[1] += databuff_size;   /* coincides with plane_data pointers */
      data[3] += databuff_size;
    }
    for (i = 0; i < num_comps; i++) {
      for (j = 0; j < img_rows; j++) {
	ep_raster_buf[i][j] = ep_p;
	ep_p += plane_size;
      }
      /* Make a sentinel and align to word size.  */
      ep_print_buf = (byte *)((word)(ep_p + sizeof(word)) & ~(sizeof(word)-1));
    }
    ep_num_comps = num_comps;
  }
  
  /* Initialize printer. */
  if (ptype == BJC600) {
    bj_init_page(pdev, prn_stream);
  } else {
      if (ptype == LJ4DITH)  {
	  fputs("\033*rB", prn_stream);
      } else {
	  fputs("\033*rbC", prn_stream);                   /* End raster graphics */
      }
      fprintf(prn_stream, "\033*t%dR", (int)x_dpi); 
  /* Set resolution */
  }
  
  /* Clear temp storage */
  memset(storage, 0, storage_size_words * W);

#define DOFFSET (dev_t_margin(pdev) - DESKJET_PRINT_LIMIT)	/* Print position */
#define POFFSET (dev_t_margin(pdev) - PAINTJET_PRINT_LIMIT)
#define EOFFSET (dev_t_margin(pdev) - ESC_P_PRINT_LIMIT)
#define BOFFSET (dev_t_margin(pdev) - BJC600_PRINT_LIMIT)
  switch (ptype) {
  case LJ4DITH:
    /* Page size, orientation, top margin & perforation skip */
    fprintf(prn_stream, "\033&l26A\033&l0o0e0L\033*r0F" );
    fprintf(prn_stream, "\033*p0x0Y" ); /* These Offsets are hacked ! */
    fprintf(prn_stream, "\033&u600D\033*r1A" );
    /* Select data compression */
    compression = 3;
    combined_escapes = 0;
    break;
  case DJ500C:
  case DJ550C:
    /* Page size, orientation, top margin & perforation skip */
    fprintf(prn_stream, "\033&l%daolE", paper_size);
    /* Set depletion and shingling levels */
    fprintf(prn_stream, "\033*o%dd%dQ", cdj->depletion, cdj->shingling);
    /* Move to top left of printed area */
    fprintf(prn_stream, "\033*p%dY", (int)(300 * DOFFSET));
    /* Set number of planes ((-)1 is mono, (-)3 is (cmy)rgb, -4 is cmyk),
     * and raster width, then start raster graphics */
    fprintf(prn_stream, "\033*r%ds-%du0A", raster_width, num_comps);
    /* Select data compression */
    compression = 9;
    break;
  case DNJ650C:
    fprintf (prn_stream, "\033%%0B"); /* Enter HPGL/2 mode */
    fprintf (prn_stream, "BP5,1"); /* Turn off autorotation */
    fprintf (prn_stream, "PS%d,%d",
	     (int)((pdev->height/pdev->y_pixels_per_inch)*1016),
	     (int)((pdev->width/pdev->x_pixels_per_inch)*1016)); /* Set length/width of page */
    fprintf (prn_stream, "PU"); /* Pen up */
    fprintf (prn_stream, "PA%d,%d", 0, 0); /* Move pen to upper-left */
    fprintf (prn_stream, "\033%%1A"); /* Enter HP-RTL mode */
    fprintf (prn_stream, "\033&a1N"); /* No negative motion - allow plotting
						while receiving */
    { static const char temp[] = {
        033, '*', 'v', '6', 'W',
	000 /* color model */,
	000 /* pixel encoding mode */,
	003 /* number of bits per index */,
	010 /* bits red */,
	010 /* bits green */,
	010 /* bits blue */
      };
      fwrite (temp, 1, sizeof(temp), prn_stream);
    }

    /* Set raster width */
    fprintf(prn_stream, "\033*r%dS", raster_width);
    /* Start raster graphics */
    fprintf(prn_stream, "\033*r1A");

    /* Select data compression */
    compression = 1;
    /* No combined escapes for raster transfers */
    combined_escapes = 0;
    break;
  case PJXL300:
    /* Page size, orientation, top margin & perforation skip */
    fprintf(prn_stream, "\033&l%daolE", paper_size);
    /* Set no-negative-motion mode, for faster (unbuffered) printing */
    fprintf(prn_stream, "\033&a1N");
    /* Set print quality */
    fprintf(prn_stream, "\033*o%dQ", pjxl->printqual);
    /* Move to top left of printed area */
    fprintf(prn_stream, "\033*p%dY", (int)(300 * POFFSET));
    /* Configure colour setup */
    if (pjxl->rendertype > 0) {
      /* Set render type */
      fprintf(prn_stream, "\033*t%dJ", pjxl->rendertype);
      /* Configure image data */
      fputs(cid_string, prn_stream);
      /* Set raster width, then start raster graphics */
      fprintf(prn_stream, "\033*r%ds1A", raster_width);
    } else {
      /* Set number of planes (1 is mono, 3 is rgb),
       * and raster width, then start raster graphics */
      fprintf(prn_stream, "\033*r%ds-%du0A", raster_width, num_comps);
    }
    /* No combined escapes for raster transfers */
    combined_escapes = 0;
    break;
  case PJXL180:
    /* Page size, orientation, top margin & perforation skip */
    fprintf(prn_stream, "\033&l%daolE", paper_size);
    /* Set print quality */
    fprintf(prn_stream, "\033*o%dQ", pjxl->printqual);
    /* Move to top left of printed area */
    fprintf(prn_stream, "\033*p%dY", (int)(180 * POFFSET));
    /* Configure colour setup */
    if (pjxl->rendertype > 0) {
      /* Set render type */
      fprintf(prn_stream, "\033*t%dJ", pjxl->rendertype);
      /* Configure image data */
      fputs(cid_string, prn_stream);
      /* Set raster width, then start raster graphics */
      fprintf(prn_stream, "\033*r%ds1A", raster_width);
    } else {
      /* Set number of planes (1 is mono, 3 is rgb),
       * and raster width, then start raster graphics */
      fprintf(prn_stream, "\033*r%ds%du0A", raster_width, num_comps);
    }
    break;
  case PJ180:
  case DECLJ250:
    /* Disable perforation skip */
    fprintf(prn_stream, "\033&lL");
    /* Move to top left of printed area */
    fprintf(prn_stream, "\033&a%dV", (int)(720 * POFFSET));
    /* Set number of planes (1 is mono, 3 is rgb),
     * and raster width, then start raster graphics */
    fprintf(prn_stream, "\033*r%ds%du0A", raster_width, num_comps);
    if (ptype == DECLJ250) {
      /* No combined escapes for raster transfers */
      combined_escapes = 0;
      /* From here on, we're a standard Paintjet .. */
      ptype = PJ180;
    }
    /* Select data compression */
    compression = 1;
    break;
  case ESC_P:
    /* Move to top left of printed area (must be modified for large movement(YK))*/
    if ((int)(EOFFSET*360)) fprintf(prn_stream, "\033|J%c%c", 0, (int)(360*EOFFSET));
    combined_escapes = 0;
    break;
  case BJC600:
    /* Move to top left of printed area */
    bj_v_skip((int)(360*BOFFSET), pdev, prn_stream);
    combined_escapes = 0;
    compression = 2;		/* BJC600 uses the same method as mode 2 compression */
    break;
  }

  /* Unfortunately, the Paintjet XL300 PCL interpreter introduces a
   * version of the PCL language which is different to all earlier HP
   * colour and mono inkjets, in that it loses the very useful ability
   * to use combined escape sequences with the raster transfer
   * commands. In this respect, it is incompatible even with the older
   * 180 dpi PaintJet and PaintJet XL printers!  Another regrettable
   * omission is that 'mode 9' compression is not supported, as this
   * mode can give both computational and PCL file size advantages. */

  if (combined_escapes) {
    /* From now on, all escape commands start with \033*b, so we
     * combine them (if the printer supports this). */
    fputs("\033*b", prn_stream);
     /* Set compression if the mode has been defined. */
    if (compression)
      fprintf(prn_stream, "%dm", compression);
  }
  else if (ptype == BJC600)
      ;				/* Currently, nothing to do. */
  else
    if (compression)
      fprintf(prn_stream, "\033*b%dM", compression);

  /* Send each scan line in turn */
  {
    int lend = pdev->height - (dev_t_margin(pdev) + dev_b_margin(pdev)) * y_dpi;
    int cErr, mErr, yErr, kErr;
    int this_pass, lnum, i;
    int num_blank_lines = 0;
    int start_rows = (num_comps == 1) ?
      HEAD_ROWS_MONO - 1 : HEAD_ROWS_COLOUR - 1;
    word rmask = ~(word) 0 << ((-pdev->width * storage_bpp) & (W * 8 - 1));

    cErr = mErr = yErr = kErr = 0;

    if (bits_per_pixel > 4) { /* Randomly seed initial error buffer */
      int *ep = errors[0];
      for (i = 0; i < databuff_size; i++) {
	*ep++ = RANDOM;
      }
    }

    /* Inhibit blank line printing for RGB-only printers, since in
     * this case 'blank' means black!  Also disabled for XL300 due to
     * an obscure bug in the printer's firmware */
    if (ptype == PJ180 || ptype == PJXL180 || ptype == PJXL300)
      start_rows = -1;

    this_pass = start_rows;
    for (lnum = 0; lnum < lend; lnum++) {
      word *data_words = (word *)data[scan];
      register word *end_data = data_words + line_size_words;

      gdev_prn_copy_scan_lines(pdev, lnum, data[scan], line_size);

#ifdef bjc_arch_sensible
#if !arch_is_big_endian

      /**/ {
	  int w;
	  word* data_words = (word*) data[scan];

	  for (w = 0; w < line_size; ++w) {
	      data_words[w] = invert_word(data_words[w]);
	  }
      }

#endif
#endif

      /* Mask off 1-bits beyond the line width. */
      end_data[-1] &= rmask;

      /* Remove trailing 0s. */
      while (end_data > data_words && end_data[-1] == 0)
	end_data--;
      if (ptype != DNJ650C)	/* DesignJet can't skip blank lines ? ? */
	if (end_data == data_words) {	/* Blank line */
	  num_blank_lines++;
	  continue;
	}
      /* Skip blank lines if any */
      if (num_blank_lines > 0) {
	if (ptype == ESC_P) {
	  ep_print_image(prn_stream, 'B', 0, num_blank_lines);
	} else if (ptype == BJC600) {
	    bj_v_skip(num_blank_lines, pdev, prn_stream);
	} else if (num_blank_lines < this_pass) {
	  /* Moving down from current position
	   * causes head motion on the DeskJets, so
	   * if the number of lines is within the
	   * current pass of the print head, we're
	   * better off printing blanks. */
	  this_pass -= num_blank_lines;
	  if (combined_escapes) {
	    fputc('y', prn_stream);   /* Clear current and seed rows */
	    for (; num_blank_lines; num_blank_lines--)
	      fputc('w', prn_stream);
	  } else {
#if 0
/**************** The following code has been proposed ****************/
/**************** as a replacement: ****************/
	    fputs("\033*b1Y", prn_stream);   /* Clear current and seed rows */
	    if ( num_blank_lines > 1 )
	      fprintf(prn_stream, "\033*b%dY", num_blank_lines - 1);
	    num_blank_lines = 0;
#else
	    fputs("\033*bY", prn_stream);   /* Clear current and seed rows */
	    if (ptype == DNJ650C) {
	      fprintf (prn_stream, "\033*b%dY", num_blank_lines);
	      num_blank_lines = 0;
	    }
	    else {
	      for (; num_blank_lines; num_blank_lines--)
	        fputs("\033*bW", prn_stream);
	    }
#endif
	  }
	} else {
	  if (combined_escapes)
	    fprintf(prn_stream, "%dy", num_blank_lines);
	  else
	    fprintf(prn_stream, "\033*b%dY", num_blank_lines);
	}
	memset(plane_data[1 - scan][0], 0, plane_size * num_comps);
	num_blank_lines = 0;
	this_pass = start_rows;
      }
      {			/* Printing non-blank lines */
	register byte *kP = plane_data[scan + 2][3];
	register byte *cP = plane_data[scan + 2][2];
	register byte *mP = plane_data[scan + 2][1];
	register byte *yP = plane_data[scan + 2][0];
	register byte *dp = data[scan + 2];
	register int *ep = errors[scan];
	int zero_row_count;
	int i, j;
	byte *odp;

	if (this_pass)
	  this_pass--;
	else
	  this_pass = start_rows;

	if (expanded_bpp > bits_per_pixel)   /* Expand line if required */
	  expand_line(data_words, line_size, bits_per_pixel, expanded_bpp);

	/* In colour modes, we have some bit-shuffling to do before
	 * we can print the data; in FS mode we also have the
	 * dithering to take care of. */
	switch (expanded_bpp) {    /* Can be 1, 3, 8, 24 or 32 */
	case 3:
	  /* Transpose the data to get pixel planes. */
	  for (i = 0, odp = plane_data[scan][0]; i < databuff_size;
	       i += 8, odp++) {	/* The following is for 16-bit
				 * machines */
#define spread3(c)\
    { 0, c, c*0x100, c*0x101, c*0x10000L, c*0x10001L, c*0x10100L, c*0x10101L }
	    static ulong spr40[8] = spread3(0x40);
	    static ulong spr08[8] = spread3(8);
	    static ulong spr02[8] = spread3(2);
	    register byte *dp = data[scan] + i;
	    register ulong pword =
	    (spr40[dp[0]] << 1) +
	    (spr40[dp[1]]) +
	    (spr40[dp[2]] >> 1) +
	    (spr08[dp[3]] << 1) +
	    (spr08[dp[4]]) +
	    (spr08[dp[5]] >> 1) +
	    (spr02[dp[6]]) +
	    (spr02[dp[7]] >> 1);
	    odp[0] = (byte) (pword >> 16);
	    odp[plane_size] = (byte) (pword >> 8);
	    odp[plane_size * 2] = (byte) (pword);
	  }
	  break;

	case 8:
	  FSDline(scan, i, j, plane_size, cErr, mErr, yErr, kErr,
		  cP, mP, yP, kP, 1);
	  break;
	case 24:
	  FSDline(scan, i, j, plane_size, cErr, mErr, yErr, kErr,
		  cP, mP, yP, kP, 3);
	  break;
	case 32:
	  FSDline(scan, i, j, plane_size, cErr, mErr, yErr, kErr,
		  cP, mP, yP, kP, 4);
	  break;

	} /* switch(expanded_bpp) */

	/* Make sure all black is in the k plane */
	if (num_comps == 4) {
	  register word *kp = (word *)plane_data[scan][3];
	  register word *cp = (word *)plane_data[scan][2];
	  register word *mp = (word *)plane_data[scan][1];
	  register word *yp = (word *)plane_data[scan][0];
	  if (bits_per_pixel > 4) {  /* Done as 4 planes */
	    for (i = 0; i < plane_size / W; i++) {
	      word bits = *cp & *mp & *yp;
	      *kp++ |= bits;
	      bits = ~bits;
	      *cp++ &= bits;
	      *mp++ &= bits;
	      *yp++ &= bits;
	    }
	  } else {  /* This has really been done as 3 planes */
	    for (i = 0; i < plane_size / W; i++) {
	      word bits = *cp & *mp & *yp;
	      *kp++ = bits;
	      bits = ~bits;
	      *cp++ &= bits;
	      *mp++ &= bits;
	      *yp++ &= bits;
	    }
	  }
	}

#ifdef bjc_arch_sensible
#if !arch_is_big_endian

      /**/ {
	  int w;
	  word* data_words = (word*) data[scan];

	  for (w = 0; w < line_size; ++w) {
	      data_words[w] = invert_word(data_words[w]);
	  }
      }

#endif
#endif

	/* Transfer raster graphics
	 * in the order (K), C, M, Y. */
	for (zero_row_count = 0, i = num_comps - 1; i >= 0; i--) {
	  int output_plane = 1;
	  int out_count;
	  
	  switch (ptype) {
	  case DJ500C:    /* Always compress using mode 9 */
	  case DJ550C:
	    out_count = gdev_pcl_mode9compress(plane_size,
					       plane_data[scan][i],
					       plane_data[1 - scan][i],
					       out_data);

	    /* This optimisation allows early termination of the
	     * row, but this doesn't work correctly in an alternating
	     * mode 2 / mode 3 regime, so we only use it with mode 9
	     * compression */
           if (out_count == 0)
             { output_plane = 0;      /* No further output for this plane */
               if (i == 0)
                 fputc('w', prn_stream);
               else
                 zero_row_count++;
             }
           else
             { for (; zero_row_count; zero_row_count--)
                 fputc('v', prn_stream);
             }
	    break;
	  case PJ180:
	  case DNJ650C:
	    if (num_comps > 1)
	      { word *wp = (word *)plane_data[scan][i];
		for (j = 0; j < plane_size / W; j++, wp++)
		  *wp = ~*wp;
	      }
	    out_count = gdev_pcl_mode1compress((const byte *)
					       plane_data[scan][i],
					       (const byte *)
					       plane_data[scan][i] + plane_size - 1,
					       out_data);
	    break;
	  case PJXL180:    /* Need to invert data as CMY not supported */
	    if (num_comps > 1)
	      { word *wp = (word *)plane_data[scan][i];
		for (j = 0; j < plane_size / W; j++, wp++)
		  *wp = ~*wp;
	      }
	    /* fall through .. */
	  case PJXL300:     /* Compression modes 2 and 3 are both 
			     * available.  Try both and see which one
			     * produces the least output data. */
	  case LJ4DITH:
	    { const byte *plane = plane_data[scan][i];
	      byte *prev_plane = plane_data[1 - scan][i];
	      const word *row = (word *)plane;
	      const word *end_row = row + plane_size/W;
	      int count2 = gdev_pcl_mode2compress(row, end_row, out_row_alt);
	      int count3 = gdev_pcl_mode3compress(plane_size, plane, prev_plane, out_row);
	      int penalty = combined_escapes ? strlen("#m") : strlen("\033*b#M");
	      int penalty2 = (compression == 2 ? 0 : penalty);
	      int penalty3 = (compression == 3 ? 0 : penalty);
	      
	      if (count3 + penalty3 < count2 + penalty2)
		{ if ( compression != 3 ) {
		    if (combined_escapes)
		      fputs("3m", prn_stream);
		    else
		      fputs("\033*b3M", prn_stream);
		    compression = 3;
		  }
		  out_data = out_row;
		  out_count = count3;
		}
	      else
		{ if ( compression != 2 ) {
		    if (combined_escapes)
		      fputs("2m", prn_stream);
		    else
		      fputs("\033*b2M", prn_stream);
		    compression = 2;
		  }
		  out_data = out_row_alt;
		  out_count = count2;
		}
	    }
	    break;
	  case BJC600:
	    { const byte *plane = (byte *)plane_data[scan][i];
	      int count2 = bj_compress(plane, plane + plane_size, out_row_alt);

 	      out_data = out_row_alt;
	      out_count = count2;
	    }
	    break;
	  }
	  if (output_plane) {
	    if (combined_escapes)
	      fprintf(prn_stream, "%d%c", out_count, "wvvv"[i]);
	    else if (ptype == BJC600) {
	      if (out_count)
		  bj_raster_cmd(num_comps == 1 ? 3 : i,
				out_count, out_data, pdev, prn_stream);
	      if (i == 0) bj_v_skip(1, pdev, prn_stream);
	    } else if (ptype == ESC_P)
		ep_print_image(prn_stream, i, plane_data[scan][i], plane_size);
	    else
	      fprintf(prn_stream, "\033*b%d%c", out_count, "WVVV"[i]);
	    if (ptype < ESC_P)
	      fwrite(out_data, sizeof(byte), out_count, prn_stream);
	  }
	  
	} /* Transfer Raster Graphics ... */
	if (ptype == ESC_P)
	    ep_print_image(prn_stream, 'I', 0, 0); /* increment line index */
	scan = 1 - scan;          /* toggle scan direction */
      }	  /* Printing non-blank lines */
    }     /* for lnum ... */
  }       /* send each scan line in turn */

  if (combined_escapes)
    fputs("0M", prn_stream);

  /* end raster graphics */
  if (ptype == BJC600)
    bj_finish_page(pdev, prn_stream);
  else if (ptype != ESC_P) 
    fputs("\033*rbC\033E", prn_stream);

  /* eject page */
  if (ptype == PJ180)
    fputc('\f', prn_stream);
  else if (ptype == DNJ650C)
    fputs ("\033*rC\033%%0BPG;", prn_stream);
  else if (ptype == BJC600)
      ;				/* Currently, nothing to do */
  else if (ptype == ESC_P) {
    ep_print_image(prn_stream, 'F', 0, 0); /* flush print buffer */
    fputs("\014\033@", prn_stream);	/* reset after eject page */
  } else 
    fputs("\033&l0H", prn_stream);

  /* free temporary storage */
  gs_free((char *) ep_storage, ep_storage_size_words, W, "ep_print_buffer");
  gs_free((char *) storage, storage_size_words, W, "hp_colour_print_page");

  return 0;
}

/*
 * Mode 9 2D compression for the HP DeskJet 5xxC. This mode can give
 * very good compression ratios, especially if there are areas of flat
 * colour (or blank areas), and so is 'highly recommended' for colour
 * printing in particular because of the very large amounts of data which
 * can be generated
 */
private int
gdev_pcl_mode9compress(int bytecount, const byte * current, const byte * previous, byte * compressed)
{
  register const byte *cur = current;
  register const byte *prev = previous;
  register byte *out = compressed;
  const byte *end = current + bytecount;

  while (cur < end) {		/* Detect a run of unchanged bytes. */
    const byte *run = cur;
    register const byte *diff;
    int offset;
    while (cur < end && *cur == *prev) {
      cur++, prev++;
    }
    if (cur == end)
      break;			/* rest of row is unchanged */
    /* Detect a run of changed bytes. */
    /* We know that *cur != *prev. */
    diff = cur;
    do {
      prev++;
      cur++;
    }
    while (cur < end && *cur != *prev);
    /* Now [run..diff) are unchanged, and */
    /* [diff..cur) are changed. */
    offset = diff - run;
    {
      const byte *stop_test = cur - 4;
      int dissimilar, similar;

      while (diff < cur) {
	const byte *compr = diff;
	const byte *next;	/* end of run */
	byte value;
	while (diff <= stop_test &&
	       ((value = *diff) != diff[1] ||
		value != diff[2] ||
		value != diff[3]))
	  diff++;

	/* Find out how long the run is */
	if (diff > stop_test)	/* no run */
	  next = diff = cur;
	else {
	  next = diff + 4;
	  while (next < cur && *next == value)
	    next++;
	}

#define MAXOFFSETU 15
#define MAXCOUNTU 7
	/* output 'dissimilar' bytes, uncompressed */
	if ((dissimilar = diff - compr)) {
	  int temp, i;

	  if ((temp = --dissimilar) > MAXCOUNTU)
	    temp = MAXCOUNTU;
	  if (offset < MAXOFFSETU)
	    *out++ = (offset << 3) | (byte) temp;
	  else {
	    *out++ = (MAXOFFSETU << 3) | (byte) temp;
	    offset -= MAXOFFSETU;
	    while (offset >= 255) {
	      *out++ = 255;
	      offset -= 255;
	    }
	    *out++ = offset;
	  }
	  if (temp == MAXCOUNTU) {
	    temp = dissimilar - MAXCOUNTU;
	    while (temp >= 255) {
	      *out++ = 255;
	      temp -= 255;
	    }
	    *out++ = (byte) temp;
	  }
	  for (i = 0; i <= dissimilar; i++)
	    *out++ = *compr++;
	  offset = 0;
	}			/* end uncompressed */
#define MAXOFFSETC 3
#define MAXCOUNTC 31
	/* output 'similar' bytes, run-length encoded */
	if ((similar = next - diff)) {
	  int temp;

	  if ((temp = (similar -= 2)) > MAXCOUNTC)
	    temp = MAXCOUNTC;
	  if (offset < MAXOFFSETC)
	    *out++ = 0x80 | (offset << 5) | (byte) temp;
	  else {
	    *out++ = 0x80 | (MAXOFFSETC << 5) | (byte) temp;
	    offset -= MAXOFFSETC;
	    while (offset >= 255) {
	      *out++ = 255;
	      offset -= 255;
	    }
	    *out++ = offset;
	  }
	  if (temp == MAXCOUNTC) {
	    temp = similar - MAXCOUNTC;
	    while (temp >= 255) {
	      *out++ = 255;
	      temp -= 255;
	    }
	    *out++ = (byte) temp;
	  }
	  *out++ = value;
	  offset = 0;
	}			/* end compressed */
	diff = next;
      }
    }
  }
  return out - compressed;
}

/*
 * Row compression for the H-P PaintJet.
 * Compresses data from row up to end_row, storing the result
 * starting at compressed.  Returns the number of bytes stored.
 * The compressed format consists of a byte N followed by a
 * data byte that is to be repeated N+1 times.
 * In the worst case, the `compressed' representation is
 * twice as large as the input.
 * We complement the bytes at the same time, because
 * we accumulated the image in complemented form.
 */
private int
gdev_pcl_mode1compress(const byte *row, const byte *end_row, byte *compressed)
{	register const byte *in = row;
	register byte *out = compressed;
	while ( in < end_row )
           {	byte test = *in++;
		const byte *run = in;
		while ( in < end_row && *in == test ) in++;
		/* Note that in - run + 1 is the repetition count. */
		while ( in - run > 255 )
                   {	*out++ = 255;
			*out++ = test;
			run += 256;
                   }
		*out++ = in - run;
		*out++ = test;
           }
	return out - compressed;
}

/*
 * Map a r-g-b color to a color index.
 * We complement the colours, since we're using cmy anyway, and
 * because the buffering routines expect white to be zero.
 * Includes colour balancing, following HP recommendations, to try
 * and correct the greenish cast resulting from an equal mix of the
 * c, m, y, inks by reducing the cyan component to give a truer black.
 */
private gx_color_index
gdev_pcl_map_rgb_color(gx_device *pdev, gx_color_value r,
				 gx_color_value g, gx_color_value b)
{
  if (gx_color_value_to_byte(r & g & b) == 0xff)
    return (gx_color_index)0;         /* white */
  else {
    int correction = hp_device->correction;
    gx_color_value c = gx_max_color_value - r;
    gx_color_value m = gx_max_color_value - g;
    gx_color_value y = gx_max_color_value - b;
    
    /* Colour correction for better blacks when using the colour ink
     * cartridge (on the DeskJet 500C only). We reduce the cyan component
     * by some fraction (eg. 4/5) to correct the slightly greenish cast
     * resulting from an equal mix of the three inks */
    if (correction) {
      ulong maxval, minval, range;
      
      maxval = c >= m ? (c >= y ? c : y) : (m >= y ? m : y);
      if (maxval > 0) {
	minval = c <= m ? (c <= y ? c : y) : (m <= y? m : y);
	range = maxval - minval;
	
#define shift (gx_color_value_bits - 12)
	c = ((c >> shift) * (range + (maxval * correction))) /
	  ((maxval * (correction + 1)) >> shift);
      }
    }
    
    switch (pdev->color_info.depth) {
    case 1:
      return ((c | m | y) > gx_max_color_value / 2 ?
	      (gx_color_index)1 : (gx_color_index)0);
    case 8:
      if (pdev->color_info.num_components >= 3)
#define gx_color_value_to_1bit(cv) ((cv) >> (gx_color_value_bits - 1))
	return (gx_color_value_to_1bit(c) +
		(gx_color_value_to_1bit(m) << 1) +
		(gx_color_value_to_1bit(y) << 2));
      else
#define red_weight 306
#define green_weight 601
#define blue_weight 117
	return ((((ulong)c * red_weight +
		  (ulong)m * green_weight +
		  (ulong)y * blue_weight)
		 >> (gx_color_value_bits + 2)));
    case 16:
#define gx_color_value_to_5bits(cv) ((cv) >> (gx_color_value_bits - 5))
#define gx_color_value_to_6bits(cv) ((cv) >> (gx_color_value_bits - 6))
      return (gx_color_value_to_5bits(y) +
	      (gx_color_value_to_6bits(m) << 5) +
	      (gx_color_value_to_5bits(c) << 11));
    case 24:
      return (gx_color_value_to_byte(y) +
	      (gx_color_value_to_byte(m) << 8) +
	      ((ulong)gx_color_value_to_byte(c) << 16));
    case 32:
      { return ((c == m && c == y) ? ((ulong)gx_color_value_to_byte(c) << 24)
	  : (gx_color_value_to_byte(y) +
	     (gx_color_value_to_byte(m) << 8) +
	     ((ulong)gx_color_value_to_byte(c) << 16)));
      }
    }
  }
  return (gx_color_index)0;   /* This never happens */
}
    
/* Map a color index to a r-g-b color. */
private int
gdev_pcl_map_color_rgb(gx_device *pdev, gx_color_index color,
			    gx_color_value prgb[3])
{
  /* For the moment, we simply ignore any black correction */
  switch (pdev->color_info.depth) {
  case 1:
    prgb[0] = prgb[1] = prgb[2] = -((gx_color_value)color ^ 1);
    break;
  case 8:
      if (pdev->color_info.num_components >= 3)
	{ gx_color_value c = (gx_color_value)color ^ 7;
	  prgb[0] = -(c & 1);
	  prgb[1] = -((c >> 1) & 1);
	  prgb[2] = -(c >> 2);
	}
      else
	{ gx_color_value value = (gx_color_value)color ^ 0xff;
	  prgb[0] = prgb[1] = prgb[2] = (value << 8) + value;
	}
    break;
  case 16:
    { gx_color_value c = (gx_color_value)color ^ 0xffff;
      ushort value = c >> 11;
      prgb[0] = ((value << 11) + (value << 6) + (value << 1) +
		 (value >> 4)) >> (16 - gx_color_value_bits);
      value = (c >> 6) & 0x3f;
      prgb[1] = ((value << 10) + (value << 4) + (value >> 2))
	>> (16 - gx_color_value_bits);
      value = c & 0x1f;
      prgb[2] = ((value << 11) + (value << 6) + (value << 1) +
		 (value >> 4)) >> (16 - gx_color_value_bits);
    }
    break;
  case 24:
    { gx_color_value c = (gx_color_value)color ^ 0xffffff;
      prgb[0] = gx_color_value_from_byte(c >> 16);
      prgb[1] = gx_color_value_from_byte((c >> 8) & 0xff);
      prgb[2] = gx_color_value_from_byte(c & 0xff);
    }
    break;
  case 32:
#define  gx_maxcol gx_color_value_from_byte(gx_color_value_to_byte(gx_max_color_value))
    { gx_color_value w = gx_maxcol - gx_color_value_from_byte(color >> 24);
      prgb[0] = w - gx_color_value_from_byte((color >> 16) & 0xff);
      prgb[1] = w - gx_color_value_from_byte((color >> 8) & 0xff);
      prgb[2] = w - gx_color_value_from_byte(color & 0xff);
    }
    break;
  }
  return 0;
}

/*
 * Convert and expand scanlines:
 *
 *       (a)	16 -> 24 bit   (1-stage)
 *       (b)	16 -> 32 bit   (2-stage)
 *   or  (c)	24 -> 32 bit   (1-stage)
 */
private void
expand_line(word *line, int linesize, int bpp, int ebpp)
{
  int endline = linesize;
  byte *start = (byte *)line;
  register byte *in, *out;

  if (bpp == 16)              /* 16 to 24 (cmy) if required */
    { register byte b0, b1;
      endline = ((endline + 1) / 2);
      in = start + endline * 2;
      out = start + (endline *= 3);
      
      while (in > start)
	{ b0 = *--in;
	  b1 = *--in;
	  *--out = (b0 << 3) + ((b0 >> 2) & 0x7);
	  *--out = (b1 << 5) + ((b0 >> 3)  & 0x1c) + ((b1 >> 1) & 0x3);
	  *--out = (b1 & 0xf8) + (b1 >> 5);
	}
    }

  if (ebpp == 32)             /* 24 (cmy) to 32 (cmyk) if required */
    { register byte c, m, y;
      endline = ((endline + 2) / 3);
      in = start + endline * 3;
      out = start + endline * 4;

      while (in > start)
	{ y = *--in;
	  m = *--in;
	  c = *--in;
	  if (c == y && c == m) {
	    *--out = 0, *--out = 0, *--out = 0;
	    *--out = c;
	  } else {
	    *--out = y, *--out = m, *--out = c;
	    *--out = 0;
	  }
	}
    }
}

private int near
put_param_int(gs_param_list *plist, gs_param_name pname, int *pvalue,
  int minval, int maxval, int ecode)
{	int code, value;
	switch ( code = param_read_int(plist, pname, &value) )
	{
	default:
		return code;
	case 1:
		return ecode;
	case 0:
		if ( value < minval || value > maxval )
			param_return_error(plist, pname, gs_error_rangecheck);
		*pvalue = value;
		return (ecode < 0 ? ecode : 1);
	}
}	

private int
set_bpp(gx_device *pdev, int bpp)
{ gx_device_color_info *ci = &pdev->color_info;
  /* Only valid bits-per-pixel are 1, 3, 8, 16, 24, 32 */
  switch ( bpp )
    {
    case 1: case 3: case 8: case 16: case 24: case 32: break;
    default: return_error(gs_error_rangecheck);
    }
  ci->num_components = ((bpp == 1) || (bpp == 8) ? 1 : 3);
  ci->depth = ((bpp > 1) && (bpp < 8) ? 8 : bpp);
  ci->max_gray = (bpp >= 8 ? 255 : 1);
  ci->max_color = (bpp >= 8 ? 255 : bpp > 1 ? 1 : 0);
  ci->dither_grays = (bpp >= 8 ? 5 : 2);
  ci->dither_colors = (bpp >= 8 ? 5 : bpp > 1 ? 2 : 0);
  return 0;
}

/* new_bpp = 0 means don't change bpp */
private int
put_params_bpp(gx_device *pdev, gs_param_list *plist, int new_bpp)
{	if ( new_bpp == 0 )
	  return gdev_prn_put_params(pdev, plist);
	else
	  {	int save_bpp = cdj->color_info.depth;
		int code;
		if ( save_bpp == 8 && cdj->color_info.num_components == 3 )
		  save_bpp = 3;
		code = set_bpp(pdev, new_bpp);
		if ( code < 0 )
		  return code;
		pdev->color_info.depth = new_bpp;  /* set_bpp maps 3 to 8 */
		code = gdev_prn_put_params(pdev, plist);
		if ( code < 0 )
		  {	set_bpp(pdev, save_bpp);
			return code;
		  }
		set_bpp(pdev, new_bpp);		/* reset depth if needed */
		if ( new_bpp != save_bpp && pdev->is_open )
		  return gs_closedevice(pdev);
		return 0;
	  }
}

/* This returns either the number of pixels in a scan line, or the number
 * of bytes required to store the line, both clipped to the page margins */
private uint
gdev_prn_rasterwidth(const gx_device_printer *pdev, int pixelcount)
{
  ulong raster_width =
    pdev->width - pdev->x_pixels_per_inch * (dev_l_margin(pdev) + dev_r_margin(pdev));
  return (pixelcount ?
          (uint)raster_width :
          (uint)((raster_width * pdev->color_info.depth + 7) >> 3));
}